file_path
stringlengths
11
219
num_changed_lines
int64
0
58.4k
code
stringlengths
0
3.52M
repo_name
stringclasses
25 values
commit_date
stringclasses
5 values
sha
stringclasses
25 values
services/web/public/js/ace-1.2.5/mode-razor.js
2,793
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|async|await|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode "[0-2][0-7]{0,2}|" + // oct "3[0-7][0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ DocCommentHighlightRules.getStartRule("doc-start"), comments("no_regex"), { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "punctuation.operator", regex : /[.](?![.])/, next : "property" }, { token : "keyword.operator", regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], property: [{ token : "text", regex : "\\s+" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", next: "function_arguments" }, { token : "punctuation.operator", regex : /[.](?![.])/ }, { token : "support.function", regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : "support.function.dom", regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : "support.constant", regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : "identifier", regex : identifierRe }, { regex: "", token: "empty", next: "no_regex" } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("start"), { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); } else if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); if (!options || options.jsx != false) JSX.call(this); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); function JSX() { var tagRegex = identifierRe.replace("\\d", "\\d\\-"); var jsxTag = { onMatch : function(val, state, stack) { var offset = val.charAt(1) == "/" ? 2 : 1; if (offset == 1) { if (state != this.nextState) stack.unshift(this.next, this.nextState, 0); else stack.unshift(this.next); stack[2]++; } else if (offset == 2) { if (state == this.nextState) { stack[1]--; if (!stack[1] || stack[1] < 0) { stack.shift(); stack.shift(); } } } return [{ type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", value: val.slice(0, offset) }, { type: "meta.tag.tag-name.xml", value: val.substr(offset) }]; }, regex : "</?" + tagRegex + "", next: "jsxAttributes", nextState: "jsx" }; this.$rules.start.unshift(jsxTag); var jsxJsRule = { regex: "{", token: "paren.quasi.start", push: "start" }; this.$rules.jsx = [ jsxJsRule, jsxTag, {include : "reference"}, {defaultToken: "string"} ]; this.$rules.jsxAttributes = [{ token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", onMatch : function(value, currentState, stack) { if (currentState == stack[0]) stack.shift(); if (value.length == 2) { if (stack[0] == this.nextState) stack[1]--; if (!stack[1] || stack[1] < 0) { stack.splice(0, 2); } } this.next = stack[0] || "start"; return [{type: this.token, value: value}]; }, nextState: "jsx" }, jsxJsRule, comments("jsxAttributes"), { token : "entity.other.attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { token : "text.tag-whitespace.xml", regex : "\\s+" }, { token : "string.attribute-value.xml", regex : "'", stateName : "jsx_attr_q", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', stateName : "jsx_attr_qq", push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, jsxTag ]; this.$rules.reference = [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }]; } function comments(next) { return [ { token : "comment", // multi line comment regex : /\/\*/, next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] }, { token : "comment", regex : "\\/\\/", next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] } ]; } exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/css_completions",["require","exports","module"], function(require, exports, module) { "use strict"; var propertyMap = { "background": {"#$0": 1}, "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, "background-image": {"url('/$0')": 1}, "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, "background-attachment": {"scroll": 1, "fixed": 1}, "background-size": {"cover": 1, "contain": 1}, "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, "border-color": {"#$0": 1}, "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, "border-collapse": {"collapse": 1, "separate": 1}, "bottom": {"px": 1, "em": 1, "%": 1}, "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, "empty-cells": {"show": 1, "hide": 1}, "float": {"left": 1, "right": 1, "none": 1}, "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, "font-size": {"px": 1, "em": 1, "%": 1}, "font-weight": {"bold": 1, "normal": 1}, "font-style": {"italic": 1, "normal": 1}, "font-variant": {"normal": 1, "small-caps": 1}, "height": {"px": 1, "em": 1, "%": 1}, "left": {"px": 1, "em": 1, "%": 1}, "letter-spacing": {"normal": 1}, "line-height": {"normal": 1}, "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, "margin": {"px": 1, "em": 1, "%": 1}, "margin-right": {"px": 1, "em": 1, "%": 1}, "margin-left": {"px": 1, "em": 1, "%": 1}, "margin-top": {"px": 1, "em": 1, "%": 1}, "margin-bottom": {"px": 1, "em": 1, "%": 1}, "max-height": {"px": 1, "em": 1, "%": 1}, "max-width": {"px": 1, "em": 1, "%": 1}, "min-height": {"px": 1, "em": 1, "%": 1}, "min-width": {"px": 1, "em": 1, "%": 1}, "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "padding": {"px": 1, "em": 1, "%": 1}, "padding-top": {"px": 1, "em": 1, "%": 1}, "padding-right": {"px": 1, "em": 1, "%": 1}, "padding-bottom": {"px": 1, "em": 1, "%": 1}, "padding-left": {"px": 1, "em": 1, "%": 1}, "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, "right": {"px": 1, "em": 1, "%": 1}, "table-layout": {"fixed": 1, "auto": 1}, "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, "top": {"px": 1, "em": 1, "%": 1}, "vertical-align": {"top": 1, "bottom": 1}, "visibility": {"hidden": 1, "visible": 1}, "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, "width": {"px": 1, "em": 1, "%": 1}, "word-spacing": {"normal": 1}, "filter": {"alpha(opacity=$0100)": 1}, "text-shadow": {"$02px 2px 2px #777": 1}, "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, "-moz-border-radius": 1, "-moz-border-radius-topright": 1, "-moz-border-radius-bottomright": 1, "-moz-border-radius-topleft": 1, "-moz-border-radius-bottomleft": 1, "-webkit-border-radius": 1, "-webkit-border-top-right-radius": 1, "-webkit-border-top-left-radius": 1, "-webkit-border-bottom-right-radius": 1, "-webkit-border-bottom-left-radius": 1, "-moz-box-shadow": 1, "-webkit-box-shadow": 1, "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } }; var CssCompletions = function() { }; (function() { this.completionsDefined = false; this.defineCompletions = function() { if (document) { var style = document.createElement('c').style; for (var i in style) { if (typeof style[i] !== 'string') continue; var name = i.replace(/[A-Z]/g, function(x) { return '-' + x.toLowerCase(); }); if (!propertyMap.hasOwnProperty(name)) propertyMap[name] = 1; } } this.completionsDefined = true; } this.getCompletions = function(state, session, pos, prefix) { if (!this.completionsDefined) { this.defineCompletions(); } var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (state==='ruleset'){ var line = session.getLine(pos.row).substr(0, pos.column); if (/:[^;]+$/.test(line)) { /([\w\-]+):[^:]*$/.test(line); return this.getPropertyValueCompletions(state, session, pos, prefix); } else { return this.getPropertyCompletions(state, session, pos, prefix); } } return []; }; this.getPropertyCompletions = function(state, session, pos, prefix) { var properties = Object.keys(propertyMap); return properties.map(function(property){ return { caption: property, snippet: property + ': $0', meta: "property", score: Number.MAX_VALUE }; }); }; this.getPropertyValueCompletions = function(state, session, pos, prefix) { var line = session.getLine(pos.row).substr(0, pos.column); var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; if (!property) return []; var values = []; if (property in propertyMap && typeof propertyMap[property] === "object") { values = Object.keys(propertyMap[property]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "property value", score: Number.MAX_VALUE }; }); }; }).call(CssCompletions.prototype); exports.CssCompletions = CssCompletions; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssCompletions = require("./css_completions").CssCompletions; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.$completer = new CssCompletions(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": {"manifest": 1}, "head": {}, "title": {}, "base": {"href": 1, "target": 1}, "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, "noscript": {"href": 1}, "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, "section": {}, "nav": {}, "article": {"pubdate": 1}, "aside": {}, "h1": {}, "h2": {}, "h3": {}, "h4": {}, "h5": {}, "h6": {}, "header": {}, "footer": {}, "address": {}, "main": {}, "p": {}, "hr": {}, "pre": {}, "blockquote": {"cite": 1}, "ol": {"start": 1, "reversed": 1}, "ul": {}, "li": {"value": 1}, "dl": {}, "dt": {}, "dd": {}, "figure": {}, "figcaption": {}, "div": {}, "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, "em": {}, "strong": {}, "small": {}, "s": {}, "cite": {}, "q": {"cite": 1}, "dfn": {}, "abbr": {}, "data": {}, "time": {"datetime": 1}, "code": {}, "var": {}, "samp": {}, "kbd": {}, "sub": {}, "sup": {}, "i": {}, "b": {}, "u": {}, "mark": {}, "ruby": {}, "rt": {}, "rp": {}, "bdi": {}, "bdo": {}, "span": {}, "br": {}, "wbr": {}, "ins": {"cite": 1, "datetime": 1}, "del": {"cite": 1, "datetime": 1}, "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, "param": {"name": 1, "value": 1}, "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, "source": {"src": 1, "type": 1, "media": 1}, "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, "canvas": {"width": 1, "height": 1}, "map": {"name": 1}, "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, "svg": {}, "math": {}, "table": {"summary": 1}, "caption": {}, "colgroup": {"span": 1}, "col": {"span": 1}, "tbody": {}, "thead": {}, "tfoot": {}, "tr": {}, "td": {"headers": 1, "rowspan": 1, "colspan": 1}, "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, "fieldset": {"disabled": 1, "form": 1, "name": 1}, "legend": {}, "label": {"form": 1, "for": 1}, "input": { "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, "datalist": {}, "optgroup": {"disabled": 1, "label": 1}, "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, "output": {"for": 1, "form": 1, "name": 1}, "progress": {"value": 1, "max": 1}, "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, "details": {"open": 1}, "summary": {}, "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, "menu": {"type": 1, "label": 1}, "dialog": {"open": 1} }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } function findAttributeName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "attribute-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompletions(state, session, pos, prefix); if (is(token, "attribute-value")) return this.getAttributeValueCompletions(state, session, pos, prefix); var line = session.getLine(pos.row).substr(0, pos.column); if (/&[A-z]*$/i.test(line)) return this.getHTMLEntityCompletions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(Object.keys(attributeMap[tagName])); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; this.getAttributeValueCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); var attributeName = findAttributeName(session, pos); if (!tagName) return []; var values = []; if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { values = Object.keys(attributeMap[tagName][attributeName]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "attribute value", score: Number.MAX_VALUE }; }); }; this.getHTMLEntityCompletions = function(state, session, pos, prefix) { var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; return values.map(function(value){ return { caption: value, snippet: value, meta: "html entity", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/csharp_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var CSharpHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "variable.language": "this", "keyword": "abstract|event|new|struct|as|explicit|null|switch|base|extern|object|this|bool|false|operator|throw|break|finally|out|true|byte|fixed|override|try|case|float|params|typeof|catch|for|private|uint|char|foreach|protected|ulong|checked|goto|public|unchecked|class|if|readonly|unsafe|const|implicit|ref|ushort|continue|in|return|using|decimal|int|sbyte|virtual|default|interface|sealed|volatile|delegate|internal|short|void|do|is|sizeof|while|double|lock|stackalloc|else|long|static|enum|namespace|string|var|dynamic", "constant.language": "null|true|false" }, "identifier"); this.$rules = { "start" : [ { token : "comment", regex : "\\/\\/.*$" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment" }, { token : "string", // character regex : /'(?:.|\\(:?u[\da-fA-F]+|x[\da-fA-F]+|[tbrf'"n]))'/ }, { token : "string", start : '"', end : '"|$', next: [ {token: "constant.language.escape", regex: /\\(:?u[\da-fA-F]+|x[\da-fA-F]+|[tbrf'"n])/}, {token: "invalid", regex: /\\./} ] }, { token : "string", start : '@"', end : '"', next:[ {token: "constant.language.escape", regex: '""'} ] }, { token : "string", start : /\$"/, end : '"|$', next: [ {token: "constant.language.escape", regex: /\\(:?$)|{{/}, {token: "constant.language.escape", regex: /\\(:?u[\da-fA-F]+|x[\da-fA-F]+|[tbrf'"n])/}, {token: "invalid", regex: /\\./} ] }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "keyword", regex : "^\\s*#(if|else|elif|endif|define|undef|warning|error|line|region|endregion|pragma)" }, { token : "punctuation.operator", regex : "\\?|\\:|\\,|\\;|\\." }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : ".*?\\*\\/", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); this.normalizeRules(); }; oop.inherits(CSharpHighlightRules, TextHighlightRules); exports.CSharpHighlightRules = CSharpHighlightRules; }); ace.define("ace/mode/razor_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/html_highlight_rules","ace/mode/csharp_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var CSharpHighlightRules = require("./csharp_highlight_rules").CSharpHighlightRules; var blockPrefix = 'razor-block-'; var RazorLangHighlightRules = function() { CSharpHighlightRules.call(this); var processPotentialCallback = function(value, stackItem) { if (typeof stackItem === "function") return stackItem(value); return stackItem; }; var inBraces = 'in-braces'; this.$rules.start.unshift({ regex: '[\\[({]', onMatch: function(value, state, stack) { var prefix = /razor-[^\-]+-/.exec(state)[0]; stack.unshift(value); stack.unshift(prefix + inBraces); this.next = prefix + inBraces; return 'paren.lparen'; } }, { start: "@\\*", end: "\\*@", token: "comment" }); var parentCloseMap = { '{': '}', '[': ']', '(': ')' }; this.$rules[inBraces] = lang.deepCopy(this.$rules.start); this.$rules[inBraces].unshift({ regex: '[\\])}]', onMatch: function(value, state, stack) { var open = stack[1]; if (parentCloseMap[open] !== value) return 'invalid.illegal'; stack.shift(); // exit in-braces block stack.shift(); // exit brace marker this.next = processPotentialCallback(value, stack[0]) || 'start'; return 'paren.rparen'; } }); }; oop.inherits(RazorLangHighlightRules, CSharpHighlightRules); var RazorHighlightRules = function() { HtmlHighlightRules.call(this); var blockStartRule = { regex: '@[({]|@functions{', onMatch: function(value, state, stack) { stack.unshift(value); stack.unshift('razor-block-start'); this.next = 'razor-block-start'; return 'punctuation.block.razor'; } }; var blockEndMap = { '@{': '}', '@(': ')', '@functions{':'}' }; var blockEndRule = { regex: '[})]', onMatch: function(value, state, stack) { var blockStart = stack[1]; if (blockEndMap[blockStart] !== value) return 'invalid.illegal'; stack.shift(); // exit razor block stack.shift(); // remove block type marker this.next = stack.shift() || 'start'; return 'punctuation.block.razor'; } }; var shortStartRule = { regex: "@(?![{(])", onMatch: function(value, state, stack) { stack.unshift("razor-short-start"); this.next = "razor-short-start"; return 'punctuation.short.razor'; } }; var shortEndRule = { token: "", regex: "(?=[^A-Za-z_\\.()\\[\\]])", next: 'pop' }; var ifStartRule = { regex: "@(?=if)", onMatch: function(value, state, stack) { stack.unshift(function(value) { if (value !== '}') return 'start'; return stack.shift() || 'start'; }); this.next = 'razor-block-start'; return 'punctuation.control.razor'; } }; var razorStartRules = [ { start: "@\\*", end: "\\*@", token: "comment" }, { token: ["meta.directive.razor", "text", "identifier"], regex: "^(\\s*@model)(\\s+)(.+)$" }, blockStartRule, shortStartRule ]; for (var key in this.$rules) this.$rules[key].unshift.apply(this.$rules[key], razorStartRules); this.embedRules(RazorLangHighlightRules, "razor-block-", [blockEndRule], ["start"]); this.embedRules(RazorLangHighlightRules, "razor-short-", [shortEndRule], ["start"]); this.normalizeRules(); }; oop.inherits(RazorHighlightRules, HtmlHighlightRules); exports.RazorHighlightRules = RazorHighlightRules; exports.RazorLangHighlightRules = RazorLangHighlightRules; }); ace.define("ace/mode/razor_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var keywords = [ "abstract", "as", "base", "bool", "break", "byte", "case", "catch", "char", "checked", "class", "const", "continue", "decimal", "default", "delegate", "do", "double","else","enum", "event", "explicit", "extern", "false", "finally", "fixed", "float", "for", "foreach", "goto", "if", "implicit", "in", "int", "interface", "internal", "is", "lock", "long", "namespace", "new", "null", "object", "operator", "out", "override", "params", "private", "protected", "public", "readonly", "ref", "return", "sbyte", "sealed", "short", "sizeof", "stackalloc", "static", "string", "struct", "switch", "this", "throw", "true", "try", "typeof", "uint", "ulong", "unchecked", "unsafe", "ushort", "using", "var", "virtual", "void", "volatile", "while"]; var shortHands = [ "Html", "Model", "Url", "Layout" ]; var RazorCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { if(state.lastIndexOf("razor-short-start") == -1 && state.lastIndexOf("razor-block-start") == -1) return []; var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if(state.lastIndexOf("razor-short-start") != -1) { return this.getShortStartCompletions(state, session, pos, prefix); } if(state.lastIndexOf("razor-block-start") != -1) { return this.getKeywordCompletions(state, session, pos, prefix); } }; this.getShortStartCompletions = function(state, session, pos, prefix) { return shortHands.map(function(element){ return { value: element, meta: "keyword", score: Number.MAX_VALUE }; }); }; this.getKeywordCompletions = function(state, session, pos, prefix) { return shortHands.concat(keywords).map(function(element){ return { value: element, meta: "keyword", score: Number.MAX_VALUE }; }); }; }).call(RazorCompletions.prototype); exports.RazorCompletions = RazorCompletions; }); ace.define("ace/mode/razor",["require","exports","module","ace/lib/oop","ace/mode/html","ace/mode/razor_highlight_rules","ace/mode/razor_completions","ace/mode/html_completions"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlMode = require("./html").Mode; var RazorHighlightRules = require("./razor_highlight_rules").RazorHighlightRules; var RazorCompletions = require("./razor_completions").RazorCompletions; var HtmlCompletions = require("./html_completions").HtmlCompletions; var Mode = function() { HtmlMode.call(this); this.$highlightRules = new RazorHighlightRules(); this.$completer = new RazorCompletions(); this.$htmlCompleter = new HtmlCompletions(); }; oop.inherits(Mode, HtmlMode); (function() { this.getCompletions = function(state, session, pos, prefix) { var razorToken = this.$completer.getCompletions(state, session, pos, prefix); var htmlToken = this.$htmlCompleter.getCompletions(state, session, pos, prefix); return razorToken.concat(htmlToken); }; this.createWorker = function(session) { return null; }; this.$id = "ace/mode/razor"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/worker-php.js
7,019
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; if (!window.console) { window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; } window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); } } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!(range instanceof Range)) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject(array[i]); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } if (Object.prototype.toString.call(obj) !== "[object Object]") return obj; copy = {}; for (var key in obj) copy[key] = deepCopy(obj[key]); return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/php/php",["require","exports","module"], function(require, exports, module) { var PHP = {Constants:{}}; PHP.Constants.T_INCLUDE = 262; PHP.Constants.T_INCLUDE_ONCE = 261; PHP.Constants.T_EVAL = 260; PHP.Constants.T_REQUIRE = 259; PHP.Constants.T_REQUIRE_ONCE = 258; PHP.Constants.T_LOGICAL_OR = 263; PHP.Constants.T_LOGICAL_XOR = 264; PHP.Constants.T_LOGICAL_AND = 265; PHP.Constants.T_PRINT = 266; PHP.Constants.T_PLUS_EQUAL = 277; PHP.Constants.T_MINUS_EQUAL = 276; PHP.Constants.T_MUL_EQUAL = 275; PHP.Constants.T_DIV_EQUAL = 274; PHP.Constants.T_CONCAT_EQUAL = 273; PHP.Constants.T_MOD_EQUAL = 272; PHP.Constants.T_AND_EQUAL = 271; PHP.Constants.T_OR_EQUAL = 270; PHP.Constants.T_XOR_EQUAL = 269; PHP.Constants.T_SL_EQUAL = 268; PHP.Constants.T_SR_EQUAL = 267; PHP.Constants.T_BOOLEAN_OR = 278; PHP.Constants.T_BOOLEAN_AND = 279; PHP.Constants.T_IS_EQUAL = 283; PHP.Constants.T_IS_NOT_EQUAL = 282; PHP.Constants.T_IS_IDENTICAL = 281; PHP.Constants.T_IS_NOT_IDENTICAL = 280; PHP.Constants.T_IS_SMALLER_OR_EQUAL = 285; PHP.Constants.T_IS_GREATER_OR_EQUAL = 284; PHP.Constants.T_SL = 287; PHP.Constants.T_SR = 286; PHP.Constants.T_INSTANCEOF = 288; PHP.Constants.T_INC = 297; PHP.Constants.T_DEC = 296; PHP.Constants.T_INT_CAST = 295; PHP.Constants.T_DOUBLE_CAST = 294; PHP.Constants.T_STRING_CAST = 293; PHP.Constants.T_ARRAY_CAST = 292; PHP.Constants.T_OBJECT_CAST = 291; PHP.Constants.T_BOOL_CAST = 290; PHP.Constants.T_UNSET_CAST = 289; PHP.Constants.T_NEW = 299; PHP.Constants.T_CLONE = 298; PHP.Constants.T_EXIT = 300; PHP.Constants.T_IF = 301; PHP.Constants.T_ELSEIF = 302; PHP.Constants.T_ELSE = 303; PHP.Constants.T_ENDIF = 304; PHP.Constants.T_LNUMBER = 305; PHP.Constants.T_DNUMBER = 306; PHP.Constants.T_STRING = 307; PHP.Constants.T_STRING_VARNAME = 308; PHP.Constants.T_VARIABLE = 309; PHP.Constants.T_NUM_STRING = 310; PHP.Constants.T_INLINE_HTML = 311; PHP.Constants.T_CHARACTER = 312; PHP.Constants.T_BAD_CHARACTER = 313; PHP.Constants.T_ENCAPSED_AND_WHITESPACE = 314; PHP.Constants.T_CONSTANT_ENCAPSED_STRING = 315; PHP.Constants.T_ECHO = 316; PHP.Constants.T_DO = 317; PHP.Constants.T_WHILE = 318; PHP.Constants.T_ENDWHILE = 319; PHP.Constants.T_FOR = 320; PHP.Constants.T_ENDFOR = 321; PHP.Constants.T_FOREACH = 322; PHP.Constants.T_ENDFOREACH = 323; PHP.Constants.T_DECLARE = 324; PHP.Constants.T_ENDDECLARE = 325; PHP.Constants.T_AS = 326; PHP.Constants.T_SWITCH = 327; PHP.Constants.T_ENDSWITCH = 328; PHP.Constants.T_CASE = 329; PHP.Constants.T_DEFAULT = 330; PHP.Constants.T_BREAK = 331; PHP.Constants.T_CONTINUE = 332; PHP.Constants.T_GOTO = 333; PHP.Constants.T_FUNCTION = 334; PHP.Constants.T_CONST = 335; PHP.Constants.T_RETURN = 336; PHP.Constants.T_TRY = 337; PHP.Constants.T_CATCH = 338; PHP.Constants.T_THROW = 339; PHP.Constants.T_USE = 340; PHP.Constants.T_GLOBAL = 341; PHP.Constants.T_STATIC = 347; PHP.Constants.T_ABSTRACT = 346; PHP.Constants.T_FINAL = 345; PHP.Constants.T_PRIVATE = 344; PHP.Constants.T_PROTECTED = 343; PHP.Constants.T_PUBLIC = 342; PHP.Constants.T_VAR = 348; PHP.Constants.T_UNSET = 349; PHP.Constants.T_ISSET = 350; PHP.Constants.T_EMPTY = 351; PHP.Constants.T_HALT_COMPILER = 352; PHP.Constants.T_CLASS = 353; PHP.Constants.T_TRAIT = 382; PHP.Constants.T_INTERFACE = 354; PHP.Constants.T_EXTENDS = 355; PHP.Constants.T_IMPLEMENTS = 356; PHP.Constants.T_OBJECT_OPERATOR = 357; PHP.Constants.T_DOUBLE_ARROW = 358; PHP.Constants.T_LIST = 359; PHP.Constants.T_ARRAY = 360; PHP.Constants.T_CLASS_C = 361; PHP.Constants.T_TRAIT_C = 381; PHP.Constants.T_METHOD_C = 362; PHP.Constants.T_FUNC_C = 363; PHP.Constants.T_LINE = 364; PHP.Constants.T_FILE = 365; PHP.Constants.T_COMMENT = 366; PHP.Constants.T_DOC_COMMENT = 367; PHP.Constants.T_OPEN_TAG = 368; PHP.Constants.T_OPEN_TAG_WITH_ECHO = 369; PHP.Constants.T_CLOSE_TAG = 370; PHP.Constants.T_WHITESPACE = 371; PHP.Constants.T_START_HEREDOC = 372; PHP.Constants.T_END_HEREDOC = 373; PHP.Constants.T_DOLLAR_OPEN_CURLY_BRACES = 374; PHP.Constants.T_CURLY_OPEN = 375; PHP.Constants.T_PAAMAYIM_NEKUDOTAYIM = 376; PHP.Constants.T_DOUBLE_COLON = 376; PHP.Constants.T_NAMESPACE = 377; PHP.Constants.T_NS_C = 378; PHP.Constants.T_DIR = 379; PHP.Constants.T_NS_SEPARATOR = 380; PHP.Lexer = function( src, ini ) { var heredoc, lineBreaker = function( result ) { if (result.match(/\n/) !== null) { var quote = result.substring(0, 1); result = '[' + result.split(/\n/).join( quote + "," + quote ) + '].join("\\n")'; } return result; }, prev, openTag = (ini === undefined || (/^(on|true|1)$/i.test(ini.short_open_tag) ) ? /(\<\?php\s|\<\?|\<\%|\<script language\=('|")?php('|")?\>)/i : /(\<\?php\s|<\?=|\<script language\=('|")?php('|")?\>)/i), openTagStart = (ini === undefined || (/^(on|true|1)$/i.test(ini.short_open_tag)) ? /^(\<\?php\s|\<\?|\<\%|\<script language\=('|")?php('|")?\>)/i : /^(\<\?php\s|<\?=|\<script language\=('|")?php('|")?\>)/i), tokens = [ { value: PHP.Constants.T_NAMESPACE, re: /^namespace(?=\s)/i }, { value: PHP.Constants.T_USE, re: /^use(?=\s)/i }, { value: PHP.Constants.T_ABSTRACT, re: /^abstract(?=\s)/i }, { value: PHP.Constants.T_IMPLEMENTS, re: /^implements(?=\s)/i }, { value: PHP.Constants.T_INTERFACE, re: /^interface(?=\s)/i }, { value: PHP.Constants.T_CONST, re: /^const(?=\s)/i }, { value: PHP.Constants.T_STATIC, re: /^static(?=\s)/i }, { value: PHP.Constants.T_FINAL, re: /^final(?=\s)/i }, { value: PHP.Constants.T_VAR, re: /^var(?=\s)/i }, { value: PHP.Constants.T_GLOBAL, re: /^global(?=\s)/i }, { value: PHP.Constants.T_CLONE, re: /^clone(?=\s)/i }, { value: PHP.Constants.T_THROW, re: /^throw(?=\s)/i }, { value: PHP.Constants.T_EXTENDS, re: /^extends(?=\s)/i }, { value: PHP.Constants.T_AND_EQUAL, re: /^&=/ }, { value: PHP.Constants.T_AS, re: /^as(?=\s)/i }, { value: PHP.Constants.T_ARRAY_CAST, re: /^\(array\)/i }, { value: PHP.Constants.T_BOOL_CAST, re: /^\((bool|boolean)\)/i }, { value: PHP.Constants.T_DOUBLE_CAST, re: /^\((real|float|double)\)/i }, { value: PHP.Constants.T_INT_CAST, re: /^\((int|integer)\)/i }, { value: PHP.Constants.T_OBJECT_CAST, re: /^\(object\)/i }, { value: PHP.Constants.T_STRING_CAST, re: /^\(string\)/i }, { value: PHP.Constants.T_UNSET_CAST, re: /^\(unset\)/i }, { value: PHP.Constants.T_TRY, re: /^try(?=\s*{)/i }, { value: PHP.Constants.T_CATCH, re: /^catch(?=\s*\()/i }, { value: PHP.Constants.T_INSTANCEOF, re: /^instanceof(?=\s)/i }, { value: PHP.Constants.T_LOGICAL_OR, re: /^or(?=\s)/i }, { value: PHP.Constants.T_LOGICAL_AND, re: /^and(?=\s)/i }, { value: PHP.Constants.T_LOGICAL_XOR, re: /^xor(?=\s)/i }, { value: PHP.Constants.T_BOOLEAN_AND, re: /^&&/ }, { value: PHP.Constants.T_BOOLEAN_OR, re: /^\|\|/ }, { value: PHP.Constants.T_CONTINUE, re: /^continue(?=\s|;)/i }, { value: PHP.Constants.T_BREAK, re: /^break(?=\s|;)/i }, { value: PHP.Constants.T_ENDDECLARE, re: /^enddeclare(?=\s|;)/i }, { value: PHP.Constants.T_ENDFOR, re: /^endfor(?=\s|;)/i }, { value: PHP.Constants.T_ENDFOREACH, re: /^endforeach(?=\s|;)/i }, { value: PHP.Constants.T_ENDIF, re: /^endif(?=\s|;)/i }, { value: PHP.Constants.T_ENDSWITCH, re: /^endswitch(?=\s|;)/i }, { value: PHP.Constants.T_ENDWHILE, re: /^endwhile(?=\s|;)/i }, { value: PHP.Constants.T_CASE, re: /^case(?=\s)/i }, { value: PHP.Constants.T_DEFAULT, re: /^default(?=\s|:)/i }, { value: PHP.Constants.T_SWITCH, re: /^switch(?=[ (])/i }, { value: PHP.Constants.T_EXIT, re: /^(exit|die)(?=[ \(;])/i }, { value: PHP.Constants.T_CLOSE_TAG, re: /^(\?\>|\%\>|\<\/script\>)\s?\s?/i, func: function( result ) { insidePHP = false; return result; } }, { value: PHP.Constants.T_DOUBLE_ARROW, re: /^\=\>/ }, { value: PHP.Constants.T_DOUBLE_COLON, re: /^\:\:/ }, { value: PHP.Constants.T_METHOD_C, re: /^__METHOD__/ }, { value: PHP.Constants.T_LINE, re: /^__LINE__/ }, { value: PHP.Constants.T_FILE, re: /^__FILE__/ }, { value: PHP.Constants.T_FUNC_C, re: /^__FUNCTION__/ }, { value: PHP.Constants.T_NS_C, re: /^__NAMESPACE__/ }, { value: PHP.Constants.T_TRAIT_C, re: /^__TRAIT__/ }, { value: PHP.Constants.T_DIR, re: /^__DIR__/ }, { value: PHP.Constants.T_CLASS_C, re: /^__CLASS__/ }, { value: PHP.Constants.T_INC, re: /^\+\+/ }, { value: PHP.Constants.T_DEC, re: /^\-\-/ }, { value: PHP.Constants.T_CONCAT_EQUAL, re: /^\.\=/ }, { value: PHP.Constants.T_DIV_EQUAL, re: /^\/\=/ }, { value: PHP.Constants.T_XOR_EQUAL, re: /^\^\=/ }, { value: PHP.Constants.T_MUL_EQUAL, re: /^\*\=/ }, { value: PHP.Constants.T_MOD_EQUAL, re: /^\%\=/ }, { value: PHP.Constants.T_SL_EQUAL, re: /^<<=/ }, { value: PHP.Constants.T_START_HEREDOC, re: /^<<<[A-Z_0-9]+\s/i, func: function( result ){ heredoc = result.substring(3, result.length - 1); return result; } }, { value: PHP.Constants.T_SL, re: /^<</ }, { value: PHP.Constants.T_IS_SMALLER_OR_EQUAL, re: /^<=/ }, { value: PHP.Constants.T_SR_EQUAL, re: /^>>=/ }, { value: PHP.Constants.T_SR, re: /^>>/ }, { value: PHP.Constants.T_IS_GREATER_OR_EQUAL, re: /^>=/ }, { value: PHP.Constants.T_OR_EQUAL, re: /^\|\=/ }, { value: PHP.Constants.T_PLUS_EQUAL, re: /^\+\=/ }, { value: PHP.Constants.T_MINUS_EQUAL, re: /^-\=/ }, { value: PHP.Constants.T_OBJECT_OPERATOR, re: /^\-\>/i }, { value: PHP.Constants.T_CLASS, re: /^class(?=[\s\{])/i, afterWhitespace: true }, { value: PHP.Constants.T_TRAIT, re: /^trait(?=[\s]+[A-Za-z])/i, }, { value: PHP.Constants.T_PUBLIC, re: /^public(?=[\s])/i }, { value: PHP.Constants.T_PRIVATE, re: /^private(?=[\s])/i }, { value: PHP.Constants.T_PROTECTED, re: /^protected(?=[\s])/i }, { value: PHP.Constants.T_ARRAY, re: /^array(?=\s*?\()/i }, { value: PHP.Constants.T_EMPTY, re: /^empty(?=[ \(])/i }, { value: PHP.Constants.T_ISSET, re: /^isset(?=[ \(])/i }, { value: PHP.Constants.T_UNSET, re: /^unset(?=[ \(])/i }, { value: PHP.Constants.T_RETURN, re: /^return(?=[ "'(;])/i }, { value: PHP.Constants.T_FUNCTION, re: /^function(?=[ "'(;])/i }, { value: PHP.Constants.T_ECHO, re: /^echo(?=[ "'(;])/i }, { value: PHP.Constants.T_LIST, re: /^list(?=\s*?\()/i }, { value: PHP.Constants.T_PRINT, re: /^print(?=[ "'(;])/i }, { value: PHP.Constants.T_INCLUDE, re: /^include(?=[ "'(;])/i }, { value: PHP.Constants.T_INCLUDE_ONCE, re: /^include_once(?=[ "'(;])/i }, { value: PHP.Constants.T_REQUIRE, re: /^require(?=[ "'(;])/i }, { value: PHP.Constants.T_REQUIRE_ONCE, re: /^require_once(?=[ "'(;])/i }, { value: PHP.Constants.T_NEW, re: /^new(?=[ ])/i }, { value: PHP.Constants.T_COMMENT, re: /^\/\*([\S\s]*?)(?:\*\/|$)/ }, { value: PHP.Constants.T_COMMENT, re: /^\/\/.*(\s)?/ }, { value: PHP.Constants.T_COMMENT, re: /^\#.*(\s)?/ }, { value: PHP.Constants.T_ELSEIF, re: /^elseif(?=[\s(])/i }, { value: PHP.Constants.T_GOTO, re: /^goto(?=[\s(])/i }, { value: PHP.Constants.T_ELSE, re: /^else(?=[\s{:])/i }, { value: PHP.Constants.T_IF, re: /^if(?=[\s(])/i }, { value: PHP.Constants.T_DO, re: /^do(?=[ {])/i }, { value: PHP.Constants.T_WHILE, re: /^while(?=[ (])/i }, { value: PHP.Constants.T_FOREACH, re: /^foreach(?=[ (])/i }, { value: PHP.Constants.T_ISSET, re: /^isset(?=[ (])/i }, { value: PHP.Constants.T_IS_IDENTICAL, re: /^===/ }, { value: PHP.Constants.T_IS_EQUAL, re: /^==/ }, { value: PHP.Constants.T_IS_NOT_IDENTICAL, re: /^\!==/ }, { value: PHP.Constants.T_IS_NOT_EQUAL, re: /^(\!=|\<\>)/ }, { value: PHP.Constants.T_FOR, re: /^for(?=[ (])/i }, { value: PHP.Constants.T_DNUMBER, re: /^[0-9]*\.[0-9]+([eE][-]?[0-9]*)?/ }, { value: PHP.Constants.T_LNUMBER, re: /^(0x[0-9A-F]+|[0-9]+)/i }, { value: PHP.Constants.T_OPEN_TAG_WITH_ECHO, re: /^(\<\?=|\<\%=)/i }, { value: PHP.Constants.T_OPEN_TAG, re: openTagStart }, { value: PHP.Constants.T_VARIABLE, re: /^\$[a-zA-Z_\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*/ }, { value: PHP.Constants.T_WHITESPACE, re: /^\s+/ }, { value: PHP.Constants.T_CONSTANT_ENCAPSED_STRING, re: /^("(?:[^"\\]|\\[\s\S])*"|'(?:[^'\\]|\\[\s\S])*')/, func: function( result, token ) { var curlyOpen = 0, len, bracketOpen = 0; if (result.substring( 0,1 ) === "'") { return result; } var match = result.match( /(?:[^\\]|\\.)*[^\\]\$[a-zA-Z_\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*/g ); if ( match !== null ) { while( result.length > 0 ) { len = result.length; match = result.match( /^[\[\]\;\:\?\(\)\!\.\,\>\<\=\+\-\/\*\|\&\@\^\%\"\'\{\}]/ ); if ( match !== null ) { results.push( match[ 0 ] ); result = result.substring( 1 ); if ( curlyOpen > 0 && match[ 0 ] === "}") { curlyOpen--; } if ( match[ 0 ] === "[" ) { bracketOpen++; } if ( match[ 0 ] === "]" ) { bracketOpen--; } } match = result.match(/^\$[a-zA-Z_\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*/); if ( match !== null ) { results.push([ parseInt(PHP.Constants.T_VARIABLE, 10), match[ 0 ], line ]); result = result.substring( match[ 0 ].length ); match = result.match(/^(\-\>)\s*([a-zA-Z_\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*)\s*(\()/); if ( match !== null ) { results.push([ parseInt(PHP.Constants.T_OBJECT_OPERATOR, 10), match[ 1 ], line ]); results.push([ parseInt(PHP.Constants.T_STRING, 10), match[ 2 ], line ]); if (match[3]) { results.push(match[3]); } result = result.substring( match[ 0 ].length ); } if ( result.match( /^\[/g ) !== null ) { continue; } } var re; if ( curlyOpen > 0) { re = /^([^\\\$"{}\]\(\)\->]|\\.)+/g; } else { re = /^([^\\\$"{]|\\.|{[^\$]|\$(?=[^a-zA-Z_\x7f-\uffff]))+/g;; } var type, match2; while(( match = result.match( re )) !== null ) { if (result.length === 1) { throw new Error(match); } type = 0; if( curlyOpen > 0 ){ if( match2 = match[0].match(/^[\[\]\;\:\?\(\)\!\.\,\>\<\=\+\-\/\*\|\&\{\}\@\^\%\$\~]/) ){ results.push(match2[0]); }else{ type = PHP.Constants.T_STRING; } }else{ type = PHP.Constants.T_ENCAPSED_AND_WHITESPACE; } if( type ){ results.push([ parseInt(type, 10), match[ 0 ].replace(/\n/g,"\\n").replace(/\r/g,""), line ]); } line += match[ 0 ].split('\n').length - 1; result = result.substring( match[ 0 ].length ); } if( curlyOpen > 0 && result.match(/^\->/) !== null ) { results.push([ parseInt(PHP.Constants.T_OBJECT_OPERATOR, 10), '->', line ]); result = result.substring( 2 ); } if( result.match(/^{\$/) !== null ) { results.push([ parseInt(PHP.Constants.T_CURLY_OPEN, 10), "{", line ]); result = result.substring( 1 ); curlyOpen++; } if (len === result.length) { if ((match = result.match( /^(([^\\]|\\.)*?[^\\]\$[a-zA-Z_\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*)/g )) !== null) { return; } } } return undefined; } else { result = result.replace(/\r/g,""); } return result; } }, { value: PHP.Constants.T_NS_SEPARATOR, re: /^\\(?=[a-zA-Z_])/ }, { value: PHP.Constants.T_STRING, re: /^[a-zA-Z_\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*/ }, { value: -1, re: /^[\[\]\;\:\?\(\)\!\.\,\>\<\=\+\-\/\*\|\&\{\}\@\^\%\"\'\$\~]/ }]; var results = [], line = 1, insidePHP = false, cancel = true; if ( src === null ) { return results; } if ( typeof src !== "string" ) { src = src.toString(); } while (src.length > 0 && cancel === true) { if ( insidePHP === true ) { if ( heredoc !== undefined ) { var regexp = new RegExp('([\\S\\s]*?)(\\r\\n|\\n|\\r)(' + heredoc + ')(;|\\r\\n|\\n)',"i"); var result = src.match( regexp ); if ( result !== null ) { results.push([ parseInt(PHP.Constants.T_ENCAPSED_AND_WHITESPACE, 10), result[ 1 ].replace(/^\n/g,"").replace(/\\\$/g,"$") + "\n", line ]); line += result[ 1 ].split('\n').length; results.push([ parseInt(PHP.Constants.T_END_HEREDOC, 10), result[ 3 ], line ]); src = src.substring( result[1].length + result[2].length + result[3].length ); heredoc = undefined; } if (result === null) { throw Error("sup"); } } else { cancel = tokens.some(function( token ){ if ( token.afterWhitespace === true ) { var last = results[ results.length - 1 ]; if ( !Array.isArray( last ) || (last[ 0 ] !== PHP.Constants.T_WHITESPACE && last[ 0 ] !== PHP.Constants.T_OPEN_TAG && last[ 0 ] !== PHP.Constants.T_COMMENT)) { return false; } } var result = src.match( token.re ); if ( result !== null ) { if ( token.value !== -1) { var resultString = result[ 0 ]; if (token.func !== undefined ) { resultString = token.func( resultString, token ); } if (resultString !== undefined ) { results.push([ parseInt(token.value, 10), resultString, line ]); line += resultString.split('\n').length - 1; } } else { results.push( result[ 0 ] ); } src = src.substring(result[ 0 ].length); return true; } return false; }); } } else { var result = openTag.exec( src ); if ( result !== null ) { if ( result.index > 0 ) { var resultString = src.substring(0, result.index); results.push ([ parseInt(PHP.Constants.T_INLINE_HTML, 10), resultString, line ]); line += resultString.split('\n').length - 1; src = src.substring( result.index ); } insidePHP = true; } else { results.push ([ parseInt(PHP.Constants.T_INLINE_HTML, 10), src.replace(/^\n/, ""), line ]); return results; } } } return results; }; PHP.Parser = function ( preprocessedTokens, eval ) { var yybase = this.yybase, yydefault = this.yydefault, yycheck = this.yycheck, yyaction = this.yyaction, yylen = this.yylen, yygbase = this.yygbase, yygcheck = this.yygcheck, yyp = this.yyp, yygoto = this.yygoto, yylhs = this.yylhs, terminals = this.terminals, translate = this.translate, yygdefault = this.yygdefault; this.pos = -1; this.line = 1; this.tokenMap = this.createTokenMap( ); this.dropTokens = {}; this.dropTokens[ PHP.Constants.T_WHITESPACE ] = 1; this.dropTokens[ PHP.Constants.T_OPEN_TAG ] = 1; var tokens = []; preprocessedTokens.forEach( function( token, index ) { if ( typeof token === "object" && token[ 0 ] === PHP.Constants.T_OPEN_TAG_WITH_ECHO) { tokens.push([ PHP.Constants.T_OPEN_TAG, token[ 1 ], token[ 2 ] ]); tokens.push([ PHP.Constants.T_ECHO, token[ 1 ], token[ 2 ] ]); } else { tokens.push( token ); } }); this.tokens = tokens; var tokenId = this.TOKEN_NONE; this.startAttributes = { 'startLine': 1 }; this.endAttributes = {}; var attributeStack = [ this.startAttributes ]; var state = 0; var stateStack = [ state ]; this.yyastk = []; this.stackPos = 0; var yyn; var origTokenId; for (;;) { if ( yybase[ state ] === 0 ) { yyn = yydefault[ state ]; } else { if (tokenId === this.TOKEN_NONE ) { origTokenId = this.getNextToken( ); tokenId = (origTokenId >= 0 && origTokenId < this.TOKEN_MAP_SIZE) ? translate[ origTokenId ] : this.TOKEN_INVALID; attributeStack[ this.stackPos ] = this.startAttributes; } if (((yyn = yybase[ state ] + tokenId) >= 0 && yyn < this.YYLAST && yycheck[ yyn ] === tokenId || (state < this.YY2TBLSTATE && (yyn = yybase[state + this.YYNLSTATES] + tokenId) >= 0 && yyn < this.YYLAST && yycheck[ yyn ] === tokenId)) && (yyn = yyaction[ yyn ]) !== this.YYDEFAULT ) { if (yyn > 0) { ++this.stackPos; stateStack[ this.stackPos ] = state = yyn; this.yyastk[ this.stackPos ] = this.tokenValue; attributeStack[ this.stackPos ] = this.startAttributes; tokenId = this.TOKEN_NONE; if (yyn < this.YYNLSTATES) continue; yyn -= this.YYNLSTATES; } else { yyn = -yyn; } } else { yyn = yydefault[ state ]; } } for (;;) { if ( yyn === 0 ) { return this.yyval; } else if (yyn !== this.YYUNEXPECTED ) { for (var attr in this.endAttributes) { attributeStack[ this.stackPos - yylen[ yyn ] ][ attr ] = this.endAttributes[ attr ]; } try { this['yyn' + yyn](attributeStack[ this.stackPos - yylen[ yyn ] ]); } catch (e) { throw e; } this.stackPos -= yylen[ yyn ]; yyn = yylhs[ yyn ]; if ((yyp = yygbase[ yyn ] + stateStack[ this.stackPos ]) >= 0 && yyp < this.YYGLAST && yygcheck[ yyp ] === yyn) { state = yygoto[ yyp ]; } else { state = yygdefault[ yyn ]; } ++this.stackPos; stateStack[ this.stackPos ] = state; this.yyastk[ this.stackPos ] = this.yyval; attributeStack[ this.stackPos ] = this.startAttributes; } else { if (eval !== true) { var expected = []; for (var i = 0; i < this.TOKEN_MAP_SIZE; ++i) { if ((yyn = yybase[ state ] + i) >= 0 && yyn < this.YYLAST && yycheck[ yyn ] == i || state < this.YY2TBLSTATE && (yyn = yybase[ state + this.YYNLSTATES] + i) && yyn < this.YYLAST && yycheck[ yyn ] == i ) { if (yyaction[ yyn ] != this.YYUNEXPECTED) { if (expected.length == 4) { expected = []; break; } expected.push( this.terminals[ i ] ); } } } var expectedString = ''; if (expected.length) { expectedString = ', expecting ' + expected.join(' or '); } throw new PHP.ParseError('syntax error, unexpected ' + terminals[ tokenId ] + expectedString, this.startAttributes['startLine']); } else { return this.startAttributes['startLine']; } } if (state < this.YYNLSTATES) break; yyn = state - this.YYNLSTATES; } } }; PHP.ParseError = function( msg, line ) { this.message = msg; this.line = line; }; PHP.Parser.prototype.MODIFIER_PUBLIC = 1; PHP.Parser.prototype.MODIFIER_PROTECTED = 2; PHP.Parser.prototype.MODIFIER_PRIVATE = 4; PHP.Parser.prototype.MODIFIER_STATIC = 8; PHP.Parser.prototype.MODIFIER_ABSTRACT = 16; PHP.Parser.prototype.MODIFIER_FINAL = 32; PHP.Parser.prototype.getNextToken = function( ) { this.startAttributes = {}; this.endAttributes = {}; var token, tmp; while (this.tokens[++this.pos] !== undefined) { token = this.tokens[this.pos]; if (typeof token === "string") { this.startAttributes['startLine'] = this.line; this.endAttributes['endLine'] = this.line; if ('b"' === token) { this.tokenValue = 'b"'; return '"'.charCodeAt(0); } else { this.tokenValue = token; return token.charCodeAt(0); } } else { this.line += ((tmp = token[ 1 ].match(/\n/g)) === null) ? 0 : tmp.length; if (PHP.Constants.T_COMMENT === token[0]) { if (!Array.isArray(this.startAttributes['comments'])) { this.startAttributes['comments'] = []; } this.startAttributes['comments'].push( { type: "comment", comment: token[1], line: token[2] }); } else if (PHP.Constants.T_DOC_COMMENT === token[0]) { this.startAttributes['comments'].push( new PHPParser_Comment_Doc(token[1], token[2]) ); } else if (this.dropTokens[token[0]] === undefined) { this.tokenValue = token[1]; this.startAttributes['startLine'] = token[2]; this.endAttributes['endLine'] = this.line; return this.tokenMap[token[0]]; } } } this.startAttributes['startLine'] = this.line; return 0; }; PHP.Parser.prototype.tokenName = function( token ) { var constants = ["T_INCLUDE","T_INCLUDE_ONCE","T_EVAL","T_REQUIRE","T_REQUIRE_ONCE","T_LOGICAL_OR","T_LOGICAL_XOR","T_LOGICAL_AND","T_PRINT","T_PLUS_EQUAL","T_MINUS_EQUAL","T_MUL_EQUAL","T_DIV_EQUAL","T_CONCAT_EQUAL","T_MOD_EQUAL","T_AND_EQUAL","T_OR_EQUAL","T_XOR_EQUAL","T_SL_EQUAL","T_SR_EQUAL","T_BOOLEAN_OR","T_BOOLEAN_AND","T_IS_EQUAL","T_IS_NOT_EQUAL","T_IS_IDENTICAL","T_IS_NOT_IDENTICAL","T_IS_SMALLER_OR_EQUAL","T_IS_GREATER_OR_EQUAL","T_SL","T_SR","T_INSTANCEOF","T_INC","T_DEC","T_INT_CAST","T_DOUBLE_CAST","T_STRING_CAST","T_ARRAY_CAST","T_OBJECT_CAST","T_BOOL_CAST","T_UNSET_CAST","T_NEW","T_CLONE","T_EXIT","T_IF","T_ELSEIF","T_ELSE","T_ENDIF","T_LNUMBER","T_DNUMBER","T_STRING","T_STRING_VARNAME","T_VARIABLE","T_NUM_STRING","T_INLINE_HTML","T_CHARACTER","T_BAD_CHARACTER","T_ENCAPSED_AND_WHITESPACE","T_CONSTANT_ENCAPSED_STRING","T_ECHO","T_DO","T_WHILE","T_ENDWHILE","T_FOR","T_ENDFOR","T_FOREACH","T_ENDFOREACH","T_DECLARE","T_ENDDECLARE","T_AS","T_SWITCH","T_ENDSWITCH","T_CASE","T_DEFAULT","T_BREAK","T_CONTINUE","T_GOTO","T_FUNCTION","T_CONST","T_RETURN","T_TRY","T_CATCH","T_THROW","T_USE","T_INSTEADOF","T_GLOBAL","T_STATIC","T_ABSTRACT","T_FINAL","T_PRIVATE","T_PROTECTED","T_PUBLIC","T_VAR","T_UNSET","T_ISSET","T_EMPTY","T_HALT_COMPILER","T_CLASS","T_TRAIT","T_INTERFACE","T_EXTENDS","T_IMPLEMENTS","T_OBJECT_OPERATOR","T_DOUBLE_ARROW","T_LIST","T_ARRAY","T_CALLABLE","T_CLASS_C","T_TRAIT_C","T_METHOD_C","T_FUNC_C","T_LINE","T_FILE","T_COMMENT","T_DOC_COMMENT","T_OPEN_TAG","T_OPEN_TAG_WITH_ECHO","T_CLOSE_TAG","T_WHITESPACE","T_START_HEREDOC","T_END_HEREDOC","T_DOLLAR_OPEN_CURLY_BRACES","T_CURLY_OPEN","T_PAAMAYIM_NEKUDOTAYIM","T_DOUBLE_COLON","T_NAMESPACE","T_NS_C","T_DIR","T_NS_SEPARATOR"]; var current = "UNKNOWN"; constants.some(function( constant ) { if (PHP.Constants[ constant ] === token) { current = constant; return true; } else { return false; } }); return current; }; PHP.Parser.prototype.createTokenMap = function() { var tokenMap = {}, name, i; var T_DOUBLE_COLON = PHP.Constants.T_PAAMAYIM_NEKUDOTAYIM; for ( i = 256; i < 1000; ++i ) { if ( T_DOUBLE_COLON === i ) { tokenMap[ i ] = this.T_PAAMAYIM_NEKUDOTAYIM; } else if( PHP.Constants.T_OPEN_TAG_WITH_ECHO === i ) { tokenMap[ i ] = PHP.Constants.T_ECHO; } else if( PHP.Constants.T_CLOSE_TAG === i ) { tokenMap[ i ] = 59; } else if ( 'UNKNOWN' !== (name = this.tokenName( i ) ) ) { tokenMap[ i ] = this[name]; } } return tokenMap; }; var yynStandard = function () { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.MakeArray = function( arr ) { return Array.isArray( arr ) ? arr : [ arr ]; } PHP.Parser.prototype.parseString = function( str ) { var bLength = 0; if ('b' === str[0]) { bLength = 1; } if ('\'' === str[ bLength ]) { str = str.replace( ['\\\\', '\\\''], [ '\\', '\'']); } else { str = this.parseEscapeSequences( str, '"'); } return str; }; PHP.Parser.prototype.parseEscapeSequences = function( str, quote ) { if (undefined !== quote) { str = str.replace(new RegExp('\\' + quote, "g"), quote); } var replacements = { '\\': '\\', '$': '$', 'n': "\n", 'r': "\r", 't': "\t", 'f': "\f", 'v': "\v", 'e': "\x1B" }; return str.replace( /~\\\\([\\\\$nrtfve]|[xX][0-9a-fA-F]{1,2}|[0-7]{1,3})~/g, function ( matches ){ var str = matches[1]; if ( replacements[ str ] !== undefined ) { return replacements[ str ]; } else if ('x' === str[ 0 ] || 'X' === str[ 0 ]) { return chr(hexdec(str)); } else { return chr(octdec(str)); } } ); }; PHP.Parser.prototype.TOKEN_NONE = -1; PHP.Parser.prototype.TOKEN_INVALID = 149; PHP.Parser.prototype.TOKEN_MAP_SIZE = 384; PHP.Parser.prototype.YYLAST = 913; PHP.Parser.prototype.YY2TBLSTATE = 328; PHP.Parser.prototype.YYGLAST = 415; PHP.Parser.prototype.YYNLSTATES = 544; PHP.Parser.prototype.YYUNEXPECTED = 32767; PHP.Parser.prototype.YYDEFAULT = -32766; PHP.Parser.prototype.YYERRTOK = 256; PHP.Parser.prototype.T_INCLUDE = 257; PHP.Parser.prototype.T_INCLUDE_ONCE = 258; PHP.Parser.prototype.T_EVAL = 259; PHP.Parser.prototype.T_REQUIRE = 260; PHP.Parser.prototype.T_REQUIRE_ONCE = 261; PHP.Parser.prototype.T_LOGICAL_OR = 262; PHP.Parser.prototype.T_LOGICAL_XOR = 263; PHP.Parser.prototype.T_LOGICAL_AND = 264; PHP.Parser.prototype.T_PRINT = 265; PHP.Parser.prototype.T_PLUS_EQUAL = 266; PHP.Parser.prototype.T_MINUS_EQUAL = 267; PHP.Parser.prototype.T_MUL_EQUAL = 268; PHP.Parser.prototype.T_DIV_EQUAL = 269; PHP.Parser.prototype.T_CONCAT_EQUAL = 270; PHP.Parser.prototype.T_MOD_EQUAL = 271; PHP.Parser.prototype.T_AND_EQUAL = 272; PHP.Parser.prototype.T_OR_EQUAL = 273; PHP.Parser.prototype.T_XOR_EQUAL = 274; PHP.Parser.prototype.T_SL_EQUAL = 275; PHP.Parser.prototype.T_SR_EQUAL = 276; PHP.Parser.prototype.T_BOOLEAN_OR = 277; PHP.Parser.prototype.T_BOOLEAN_AND = 278; PHP.Parser.prototype.T_IS_EQUAL = 279; PHP.Parser.prototype.T_IS_NOT_EQUAL = 280; PHP.Parser.prototype.T_IS_IDENTICAL = 281; PHP.Parser.prototype.T_IS_NOT_IDENTICAL = 282; PHP.Parser.prototype.T_IS_SMALLER_OR_EQUAL = 283; PHP.Parser.prototype.T_IS_GREATER_OR_EQUAL = 284; PHP.Parser.prototype.T_SL = 285; PHP.Parser.prototype.T_SR = 286; PHP.Parser.prototype.T_INSTANCEOF = 287; PHP.Parser.prototype.T_INC = 288; PHP.Parser.prototype.T_DEC = 289; PHP.Parser.prototype.T_INT_CAST = 290; PHP.Parser.prototype.T_DOUBLE_CAST = 291; PHP.Parser.prototype.T_STRING_CAST = 292; PHP.Parser.prototype.T_ARRAY_CAST = 293; PHP.Parser.prototype.T_OBJECT_CAST = 294; PHP.Parser.prototype.T_BOOL_CAST = 295; PHP.Parser.prototype.T_UNSET_CAST = 296; PHP.Parser.prototype.T_NEW = 297; PHP.Parser.prototype.T_CLONE = 298; PHP.Parser.prototype.T_EXIT = 299; PHP.Parser.prototype.T_IF = 300; PHP.Parser.prototype.T_ELSEIF = 301; PHP.Parser.prototype.T_ELSE = 302; PHP.Parser.prototype.T_ENDIF = 303; PHP.Parser.prototype.T_LNUMBER = 304; PHP.Parser.prototype.T_DNUMBER = 305; PHP.Parser.prototype.T_STRING = 306; PHP.Parser.prototype.T_STRING_VARNAME = 307; PHP.Parser.prototype.T_VARIABLE = 308; PHP.Parser.prototype.T_NUM_STRING = 309; PHP.Parser.prototype.T_INLINE_HTML = 310; PHP.Parser.prototype.T_CHARACTER = 311; PHP.Parser.prototype.T_BAD_CHARACTER = 312; PHP.Parser.prototype.T_ENCAPSED_AND_WHITESPACE = 313; PHP.Parser.prototype.T_CONSTANT_ENCAPSED_STRING = 314; PHP.Parser.prototype.T_ECHO = 315; PHP.Parser.prototype.T_DO = 316; PHP.Parser.prototype.T_WHILE = 317; PHP.Parser.prototype.T_ENDWHILE = 318; PHP.Parser.prototype.T_FOR = 319; PHP.Parser.prototype.T_ENDFOR = 320; PHP.Parser.prototype.T_FOREACH = 321; PHP.Parser.prototype.T_ENDFOREACH = 322; PHP.Parser.prototype.T_DECLARE = 323; PHP.Parser.prototype.T_ENDDECLARE = 324; PHP.Parser.prototype.T_AS = 325; PHP.Parser.prototype.T_SWITCH = 326; PHP.Parser.prototype.T_ENDSWITCH = 327; PHP.Parser.prototype.T_CASE = 328; PHP.Parser.prototype.T_DEFAULT = 329; PHP.Parser.prototype.T_BREAK = 330; PHP.Parser.prototype.T_CONTINUE = 331; PHP.Parser.prototype.T_GOTO = 332; PHP.Parser.prototype.T_FUNCTION = 333; PHP.Parser.prototype.T_CONST = 334; PHP.Parser.prototype.T_RETURN = 335; PHP.Parser.prototype.T_TRY = 336; PHP.Parser.prototype.T_CATCH = 337; PHP.Parser.prototype.T_THROW = 338; PHP.Parser.prototype.T_USE = 339; PHP.Parser.prototype.T_INSTEADOF = 340; PHP.Parser.prototype.T_GLOBAL = 341; PHP.Parser.prototype.T_STATIC = 342; PHP.Parser.prototype.T_ABSTRACT = 343; PHP.Parser.prototype.T_FINAL = 344; PHP.Parser.prototype.T_PRIVATE = 345; PHP.Parser.prototype.T_PROTECTED = 346; PHP.Parser.prototype.T_PUBLIC = 347; PHP.Parser.prototype.T_VAR = 348; PHP.Parser.prototype.T_UNSET = 349; PHP.Parser.prototype.T_ISSET = 350; PHP.Parser.prototype.T_EMPTY = 351; PHP.Parser.prototype.T_HALT_COMPILER = 352; PHP.Parser.prototype.T_CLASS = 353; PHP.Parser.prototype.T_TRAIT = 354; PHP.Parser.prototype.T_INTERFACE = 355; PHP.Parser.prototype.T_EXTENDS = 356; PHP.Parser.prototype.T_IMPLEMENTS = 357; PHP.Parser.prototype.T_OBJECT_OPERATOR = 358; PHP.Parser.prototype.T_DOUBLE_ARROW = 359; PHP.Parser.prototype.T_LIST = 360; PHP.Parser.prototype.T_ARRAY = 361; PHP.Parser.prototype.T_CALLABLE = 362; PHP.Parser.prototype.T_CLASS_C = 363; PHP.Parser.prototype.T_TRAIT_C = 364; PHP.Parser.prototype.T_METHOD_C = 365; PHP.Parser.prototype.T_FUNC_C = 366; PHP.Parser.prototype.T_LINE = 367; PHP.Parser.prototype.T_FILE = 368; PHP.Parser.prototype.T_COMMENT = 369; PHP.Parser.prototype.T_DOC_COMMENT = 370; PHP.Parser.prototype.T_OPEN_TAG = 371; PHP.Parser.prototype.T_OPEN_TAG_WITH_ECHO = 372; PHP.Parser.prototype.T_CLOSE_TAG = 373; PHP.Parser.prototype.T_WHITESPACE = 374; PHP.Parser.prototype.T_START_HEREDOC = 375; PHP.Parser.prototype.T_END_HEREDOC = 376; PHP.Parser.prototype.T_DOLLAR_OPEN_CURLY_BRACES = 377; PHP.Parser.prototype.T_CURLY_OPEN = 378; PHP.Parser.prototype.T_PAAMAYIM_NEKUDOTAYIM = 379; PHP.Parser.prototype.T_NAMESPACE = 380; PHP.Parser.prototype.T_NS_C = 381; PHP.Parser.prototype.T_DIR = 382; PHP.Parser.prototype.T_NS_SEPARATOR = 383; PHP.Parser.prototype.terminals = [ "$EOF", "error", "T_INCLUDE", "T_INCLUDE_ONCE", "T_EVAL", "T_REQUIRE", "T_REQUIRE_ONCE", "','", "T_LOGICAL_OR", "T_LOGICAL_XOR", "T_LOGICAL_AND", "T_PRINT", "'='", "T_PLUS_EQUAL", "T_MINUS_EQUAL", "T_MUL_EQUAL", "T_DIV_EQUAL", "T_CONCAT_EQUAL", "T_MOD_EQUAL", "T_AND_EQUAL", "T_OR_EQUAL", "T_XOR_EQUAL", "T_SL_EQUAL", "T_SR_EQUAL", "'?'", "':'", "T_BOOLEAN_OR", "T_BOOLEAN_AND", "'|'", "'^'", "'&'", "T_IS_EQUAL", "T_IS_NOT_EQUAL", "T_IS_IDENTICAL", "T_IS_NOT_IDENTICAL", "'<'", "T_IS_SMALLER_OR_EQUAL", "'>'", "T_IS_GREATER_OR_EQUAL", "T_SL", "T_SR", "'+'", "'-'", "'.'", "'*'", "'/'", "'%'", "'!'", "T_INSTANCEOF", "'~'", "T_INC", "T_DEC", "T_INT_CAST", "T_DOUBLE_CAST", "T_STRING_CAST", "T_ARRAY_CAST", "T_OBJECT_CAST", "T_BOOL_CAST", "T_UNSET_CAST", "'@'", "'['", "T_NEW", "T_CLONE", "T_EXIT", "T_IF", "T_ELSEIF", "T_ELSE", "T_ENDIF", "T_LNUMBER", "T_DNUMBER", "T_STRING", "T_STRING_VARNAME", "T_VARIABLE", "T_NUM_STRING", "T_INLINE_HTML", "T_ENCAPSED_AND_WHITESPACE", "T_CONSTANT_ENCAPSED_STRING", "T_ECHO", "T_DO", "T_WHILE", "T_ENDWHILE", "T_FOR", "T_ENDFOR", "T_FOREACH", "T_ENDFOREACH", "T_DECLARE", "T_ENDDECLARE", "T_AS", "T_SWITCH", "T_ENDSWITCH", "T_CASE", "T_DEFAULT", "T_BREAK", "T_CONTINUE", "T_GOTO", "T_FUNCTION", "T_CONST", "T_RETURN", "T_TRY", "T_CATCH", "T_THROW", "T_USE", "T_INSTEADOF", "T_GLOBAL", "T_STATIC", "T_ABSTRACT", "T_FINAL", "T_PRIVATE", "T_PROTECTED", "T_PUBLIC", "T_VAR", "T_UNSET", "T_ISSET", "T_EMPTY", "T_HALT_COMPILER", "T_CLASS", "T_TRAIT", "T_INTERFACE", "T_EXTENDS", "T_IMPLEMENTS", "T_OBJECT_OPERATOR", "T_DOUBLE_ARROW", "T_LIST", "T_ARRAY", "T_CALLABLE", "T_CLASS_C", "T_TRAIT_C", "T_METHOD_C", "T_FUNC_C", "T_LINE", "T_FILE", "T_START_HEREDOC", "T_END_HEREDOC", "T_DOLLAR_OPEN_CURLY_BRACES", "T_CURLY_OPEN", "T_PAAMAYIM_NEKUDOTAYIM", "T_NAMESPACE", "T_NS_C", "T_DIR", "T_NS_SEPARATOR", "';'", "'{'", "'}'", "'('", "')'", "'$'", "']'", "'`'", "'\"'" , "???" ]; PHP.Parser.prototype.translate = [ 0, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 47, 148, 149, 145, 46, 30, 149, 143, 144, 44, 41, 7, 42, 43, 45, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 25, 140, 35, 12, 37, 24, 59, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 60, 149, 146, 29, 149, 147, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 141, 28, 142, 49, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 149, 1, 2, 3, 4, 5, 6, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 26, 27, 31, 32, 33, 34, 36, 38, 39, 40, 48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 149, 149, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 149, 149, 149, 149, 149, 149, 131, 132, 133, 134, 135, 136, 137, 138, 139 ]; PHP.Parser.prototype.yyaction = [ 61, 62, 363, 63, 64,-32766,-32766,-32766, 509, 65, 708, 709, 710, 707, 706, 705,-32766,-32766,-32766,-32766, -32766,-32766, 132,-32766,-32766,-32766,-32766,-32766,-32767,-32767, -32767,-32767,-32766, 335,-32766,-32766,-32766,-32766,-32766, 66, 67, 351, 663, 664, 40, 68, 548, 69, 232, 233, 70, 71, 72, 73, 74, 75, 76, 77, 30, 246, 78, 336, 364, -112, 0, 469, 833, 834, 365, 641, 890, 436, 590, 41, 835, 53, 27, 366, 294, 367, 687, 368, 921, 369, 923, 922, 370,-32766,-32766,-32766, 42, 43, 371, 339, 126, 44, 372, 337, 79, 297, 349, 292, 293,-32766, 918,-32766,-32766, 373, 374, 375, 376, 377, 391, 199, 361, 338, 573, 613, 378, 379, 380, 381, 845, 839, 840, 841, 842, 836, 837, 253, -32766, 87, 88, 89, 391, 843, 838, 338, 597, 519, 128, 80, 129, 273, 332, 257, 261, 47, 673, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 799, 247, 884, 108, 109, 110, 226, 247, 21,-32766, 310,-32766,-32766,-32766, 642, 548,-32766,-32766,-32766,-32766, 56, 353,-32766,-32766,-32766, 55,-32766,-32766,-32766,-32766, -32766, 58,-32766,-32766,-32766,-32766,-32766,-32766,-32766,-32766, -32766, 557,-32766,-32766, 518,-32766, 548, 890,-32766, 390, -32766, 228, 252,-32766,-32766,-32766,-32766,-32766, 275,-32766, 234,-32766, 587, 588,-32766,-32766,-32766,-32766,-32766,-32766, -32766, 46, 236,-32766,-32766, 281,-32766, 682, 348,-32766, 390,-32766, 346, 333, 521,-32766,-32766,-32766, 271, 911, 262, 237, 446, 911,-32766, 894, 59, 700, 358, 135, 548, 123, 538, 35,-32766, 333, 122,-32766,-32766,-32766, 271,-32766, 124,-32766, 692,-32766,-32766,-32766,-32766, 700, 273, 22,-32766,-32766,-32766,-32766, 239,-32766,-32766, 612, -32766, 548, 134,-32766, 390,-32766, 462, 354,-32766,-32766, -32766,-32766,-32766, 227,-32766, 238,-32766, 845, 542,-32766, 856, 611, 200,-32766,-32766,-32766, 259, 280,-32766,-32766, 201,-32766, 855, 129,-32766, 390, 130, 202, 333, 206, -32766,-32766,-32766, 271,-32766,-32766,-32766, 125, 601,-32766, 136, 299, 700, 489, 28, 548, 105, 106, 107,-32766, 498, 499,-32766,-32766,-32766, 207,-32766, 133,-32766, 525, -32766,-32766,-32766,-32766, 663, 664, 527,-32766,-32766,-32766, -32766, 528,-32766,-32766, 610,-32766, 548, 427,-32766, 390, -32766, 532, 539,-32766,-32766,-32766,-32766,-32766, 240,-32766, 247,-32766, 697, 543,-32766, 554, 523, 608,-32766,-32766, -32766, 686, 535,-32766,-32766, 54,-32766, 57, 60,-32766, 390, 246, -155, 278, 345,-32766,-32766,-32766, 506, 347, -152, 471, 402, 403,-32766, 405, 404, 272, 493, 416, 548, 318, 417, 505,-32766, 517, 548,-32766,-32766,-32766, 549,-32766, 562,-32766, 916,-32766,-32766,-32766,-32766, 564, 826, 848,-32766,-32766,-32766,-32766, 694,-32766,-32766, 485, -32766, 548, 487,-32766, 390,-32766, 504, 802,-32766,-32766, -32766,-32766,-32766, 279,-32766, 911,-32766, 502, 492,-32766, 413, 483, 269,-32766,-32766,-32766, 243, 337,-32766,-32766, 418,-32766, 454, 229,-32766, 390, 274, 373, 374, 344, -32766,-32766,-32766, 360, 614,-32766, 573, 613, 378, 379, -274, 548, 615, -332, 844,-32766, 258, 51,-32766,-32766, -32766, 270,-32766, 346,-32766, 52,-32766, 260, 0,-32766, -333,-32766,-32766,-32766,-32766,-32766,-32766, 205,-32766,-32766, 49,-32766, 548, 424,-32766, 390,-32766, -266, 264,-32766, -32766,-32766,-32766,-32766, 409,-32766, 343,-32766, 265, 312, -32766, 470, 513, -275,-32766,-32766,-32766, 920, 337,-32766, -32766, 530,-32766, 531, 600,-32766, 390, 592, 373, 374, 578, 581,-32766,-32766, 644, 629,-32766, 573, 613, 378, 379, 635, 548, 636, 576, 627,-32766, 625, 693,-32766, -32766,-32766, 691,-32766, 591,-32766, 582,-32766, 203, 204, -32766, 584, 583,-32766,-32766,-32766,-32766, 586, 599,-32766, -32766, 589,-32766, 690, 558,-32766, 390, 197, 683, 919, 86, 520, 522,-32766, 524, 833, 834, 529, 533,-32766, 534, 537, 541, 835, 48, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 127, 31, 633, 337, 330, 634, 585,-32766, 32, 291, 337, 330, 478, 373, 374, 917, 291, 891, 889, 875, 373, 374, 553, 613, 378, 379, 737, 739, 887, 553, 613, 378, 379, 824, 451, 675, 839, 840, 841, 842, 836, 837, 320, 895, 277, 885, 23, 33, 843, 838, 556, 277, 337, 330, -32766, 34,-32766, 555, 291, 36, 37, 38, 373, 374, 39, 45, 50, 81, 82, 83, 84, 553, 613, 378, 379,-32767,-32767,-32767,-32767, 103, 104, 105, 106, 107, 337, 85, 131, 137, 337, 138, 198, 224, 225, 277, 373, 374, -332, 230, 373, 374, 24, 337, 231, 573, 613, 378, 379, 573, 613, 378, 379, 373, 374, 235, 248, 249, 250, 337, 251, 0, 573, 613, 378, 379, 276, 329, 331, 373, 374,-32766, 337, 574, 490, 792, 337, 609, 573, 613, 378, 379, 373, 374, 25, 300, 373, 374, 319, 337, 795, 573, 613, 378, 379, 573, 613, 378, 379, 373, 374, 516, 355, 359, 445, 482, 796, 507, 573, 613, 378, 379, 508, 548, 337, 890, 775, 791, 337, 604, 803, 808, 806, 698, 373, 374, 888, 807, 373, 374,-32766,-32766,-32766, 573, 613, 378, 379, 573, 613, 378, 379, 873, 832, 804, 872, 851, -32766, 809,-32766,-32766,-32766,-32766, 805, 20, 26, 29, 298, 480, 515, 770, 778, 827, 457, 0, 900, 455, 774, 0, 0, 0, 874, 870, 886, 823, 915, 852, 869, 488, 0, 391, 793, 0, 338, 0, 0, 0, 340, 0, 273 ]; PHP.Parser.prototype.yycheck = [ 2, 3, 4, 5, 6, 8, 9, 10, 70, 11, 104, 105, 106, 107, 108, 109, 8, 9, 10, 8, 9, 24, 60, 26, 27, 28, 29, 30, 31, 32, 33, 34, 24, 7, 26, 27, 28, 29, 30, 41, 42, 7, 123, 124, 7, 47, 70, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 144, 0, 75, 68, 69, 70, 25, 72, 70, 74, 7, 76, 77, 78, 79, 7, 81, 142, 83, 70, 85, 72, 73, 88, 8, 9, 10, 92, 93, 94, 95, 7, 97, 98, 95, 100, 7, 7, 103, 104, 24, 142, 26, 27, 105, 106, 111, 112, 113, 136, 7, 7, 139, 114, 115, 116, 117, 122, 123, 132, 125, 126, 127, 128, 129, 130, 131, 8, 8, 9, 10, 136, 137, 138, 139, 140, 141, 25, 143, 141, 145, 142, 147, 148, 24, 72, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 144, 48, 72, 44, 45, 46, 30, 48, 144, 64, 72, 8, 9, 10, 140, 70, 8, 9, 10, 74, 60, 25, 77, 78, 79, 60, 81, 24, 83, 26, 85, 60, 24, 88, 26, 27, 28, 92, 93, 94, 64, 140, 97, 98, 70, 100, 70, 72, 103, 104, 74, 145, 7, 77, 78, 79, 111, 81, 7, 83, 30, 85, 140, 140, 88, 8, 9, 10, 92, 93, 94, 133, 134, 97, 98, 145, 100, 140, 7, 103, 104, 24, 139, 96, 141, 140, 141, 111, 101, 75, 75, 30, 70, 75, 64, 70, 60, 110, 121, 12, 70, 141, 25, 143, 74, 96, 141, 77, 78, 79, 101, 81, 141, 83, 140, 85, 140, 141, 88, 110, 145, 144, 92, 93, 94, 64, 7, 97, 98, 142, 100, 70, 141, 103, 104, 74, 145, 141, 77, 78, 79, 111, 81, 7, 83, 30, 85, 132, 25, 88, 132, 142, 12, 92, 93, 94, 120, 60, 97, 98, 12, 100, 148, 141, 103, 104, 141, 12, 96, 12, 140, 141, 111, 101, 8, 9, 10, 141, 25, 64, 90, 91, 110, 65, 66, 70, 41, 42, 43, 74, 65, 66, 77, 78, 79, 12, 81, 25, 83, 25, 85, 140, 141, 88, 123, 124, 25, 92, 93, 94, 64, 25, 97, 98, 142, 100, 70, 120, 103, 104, 74, 25, 25, 77, 78, 79, 111, 81, 30, 83, 48, 85, 140, 141, 88, 140, 141, 30, 92, 93, 94, 140, 141, 97, 98, 60, 100, 60, 60, 103, 104, 61, 72, 75, 70, 140, 141, 111, 67, 70, 87, 99, 70, 70, 64, 70, 72, 102, 89, 70, 70, 71, 70, 70, 74, 70, 70, 77, 78, 79, 70, 81, 70, 83, 70, 85, 140, 141, 88, 70, 144, 70, 92, 93, 94, 64, 70, 97, 98, 72, 100, 70, 72, 103, 104, 74, 72, 72, 77, 78, 79, 111, 81, 75, 83, 75, 85, 89, 86, 88, 79, 101, 118, 92, 93, 94, 87, 95, 97, 98, 87, 100, 87, 87, 103, 104, 118, 105, 106, 95, 140, 141, 111, 95, 115, 64, 114, 115, 116, 117, 135, 70, 115, 120, 132, 74, 120, 140, 77, 78, 79, 119, 81, 139, 83, 140, 85, 120, -1, 88, 120, 140, 141, 92, 93, 94, 64, 121, 97, 98, 121, 100, 70, 122, 103, 104, 74, 135, 135, 77, 78, 79, 111, 81, 139, 83, 139, 85, 135, 135, 88, 135, 135, 135, 92, 93, 94, 142, 95, 97, 98, 140, 100, 140, 140, 103, 104, 140, 105, 106, 140, 140, 141, 111, 140, 140, 64, 114, 115, 116, 117, 140, 70, 140, 140, 140, 74, 140, 140, 77, 78, 79, 140, 81, 140, 83, 140, 85, 41, 42, 88, 140, 140, 141, 92, 93, 94, 140, 140, 97, 98, 140, 100, 140, 140, 103, 104, 60, 140, 142, 141, 141, 141, 111, 141, 68, 69, 141, 141, 72, 141, 141, 141, 76, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 141, 143, 142, 95, 96, 142, 140, 141, 143, 101, 95, 96, 142, 105, 106, 142, 101, 142, 142, 142, 105, 106, 114, 115, 116, 117, 50, 51, 142, 114, 115, 116, 117, 142, 123, 142, 125, 126, 127, 128, 129, 130, 131, 142, 136, 142, 144, 143, 137, 138, 142, 136, 95, 96, 143, 143, 145, 142, 101, 143, 143, 143, 105, 106, 143, 143, 143, 143, 143, 143, 143, 114, 115, 116, 117, 35, 36, 37, 38, 39, 40, 41, 42, 43, 95, 143, 143, 143, 95, 143, 143, 143, 143, 136, 105, 106, 120, 143, 105, 106, 144, 95, 143, 114, 115, 116, 117, 114, 115, 116, 117, 105, 106, 143, 143, 143, 143, 95, 143, -1, 114, 115, 116, 117, 143, 143, 143, 105, 106, 143, 95, 142, 80, 146, 95, 142, 114, 115, 116, 117, 105, 106, 144, 144, 105, 106, 144, 95, 142, 114, 115, 116, 117, 114, 115, 116, 117, 105, 106, 82, 144, 144, 144, 144, 142, 84, 114, 115, 116, 117, 144, 70, 95, 72, 144, 144, 95, 142, 144, 146, 144, 142, 105, 106, 146, 144, 105, 106, 8, 9, 10, 114, 115, 116, 117, 114, 115, 116, 117, 144, 144, 144, 144, 144, 24, 104, 26, 27, 28, 29, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, 144, -1, 144, 144, 144, -1, -1, -1, 146, 146, 146, 146, 146, 146, 146, 146, -1, 136, 147, -1, 139, -1, -1, -1, 143, -1, 145 ]; PHP.Parser.prototype.yybase = [ 0, 574, 581, 623, 655, 2, 718, 402, 747, 659, 672, 688, 743, 701, 705, 483, 483, 483, 483, 483, 351, 356, 366, 366, 367, 366, 344, -2, -2, -2, 200, 200, 231, 231, 231, 231, 231, 231, 231, 231, 200, 231, 451, 482, 532, 316, 370, 115, 146, 285, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 401, 44, 474, 429, 476, 481, 487, 488, 739, 740, 741, 734, 733, 416, 736, 539, 541, 342, 542, 543, 552, 557, 559, 536, 567, 737, 755, 569, 735, 738, 123, 123, 123, 123, 123, 123, 123, 123, 123, 122, 11, 336, 336, 336, 336, 336, 336, 336, 336, 336, 336, 336, 336, 336, 336, 336, 227, 227, 173, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 577, 79, 178, 846, 8, -3, -3, -3, -3, 642, 706, 706, 706, 706, 157, 179, 242, 431, 431, 360, 431, 525, 368, 767, 767, 767, 767, 767, 767, 767, 767, 767, 767, 767, 767, 350, 375, 315, 315, 652, 652, -81, -81, -81, -81, 251, 185, 188, 184, -62, 348, 195, 195, 195, 408, 392, 410, 1, 192, 129, 129, 129, -24, -24, -24, -24, 499, -24, -24, -24, 113, 108, 108, 12, 161, 349, 526, 271, 398, 529, 438, 130, 206, 265, 427, 76, 414, 427, 288, 295, 76, 166, 44, 262, 422, 141, 491, 372, 494, 413, 71, 92, 93, 267, 135, 100, 34, 415, 745, 746, 742, -38, 420, -10, 135, 147, 744, 498, 107, 26, 493, 144, 377, 363, 369, 332, 363, 400, 377, 588, 377, 376, 377, 360, 37, 582, 376, 377, 374, 376, 388, 363, 364, 412, 369, 377, 441, 443, 390, 106, 332, 377, 390, 377, 400, 64, 590, 591, 323, 592, 589, 593, 649, 608, 362, 500, 399, 407, 620, 625, 636, 365, 354, 614, 524, 425, 359, 355, 423, 570, 578, 357, 406, 414, 394, 352, 403, 531, 433, 403, 653, 434, 385, 417, 411, 444, 310, 318, 501, 425, 668, 757, 380, 637, 684, 403, 609, 387, 87, 325, 638, 382, 403, 639, 403, 696, 503, 615, 403, 697, 384, 435, 425, 352, 352, 352, 700, 66, 699, 583, 702, 707, 704, 748, 721, 749, 584, 750, 358, 583, 722, 751, 682, 215, 613, 422, 436, 389, 447, 221, 257, 752, 403, 403, 506, 499, 403, 395, 685, 397, 426, 753, 392, 391, 647, 683, 403, 418, 754, 221, 723, 587, 724, 450, 568, 507, 648, 509, 327, 725, 353, 497, 610, 454, 622, 455, 461, 404, 510, 373, 732, 612, 247, 361, 664, 463, 405, 692, 641, 464, 465, 511, 343, 437, 335, 409, 396, 665, 293, 467, 468, 472, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 0, 0, 0, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, -2, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 0, 0, 0, 0, 0, 0, 0, 0, 0, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 123, 767, 767, 767, 767, 767, 767, 767, 767, 767, 767, 767, 123, 123, 123, 123, 123, 123, 123, 123, 0, 129, 129, 129, 129, -94, -94, -94, 767, 767, 767, 767, 767, 767, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, -94, -94, 129, 129, 767, 767, -24, -24, -24, -24, -24, 108, 108, 108, -24, 108, 145, 145, 145, 108, 108, 108, 100, 100, 0, 0, 0, 0, 0, 0, 0, 145, 0, 0, 0, 376, 0, 0, 0, 145, 260, 260, 221, 260, 260, 135, 0, 0, 425, 376, 0, 364, 376, 0, 0, 0, 0, 0, 0, 531, 0, 87, 637, 241, 425, 0, 0, 0, 0, 0, 0, 0, 425, 289, 289, 306, 0, 358, 0, 0, 0, 306, 241, 0, 0, 221 ]; PHP.Parser.prototype.yydefault = [ 3,32767,32767, 1,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767, 104, 96, 110, 95, 106, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 358, 358, 122, 122, 122, 122, 122, 122, 122, 122, 316,32767,32767,32767,32767,32767,32767,32767,32767,32767, 173, 173, 173,32767, 348, 348, 348, 348, 348, 348, 348,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767, 363,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767, 232, 233, 235, 236, 172, 125, 349, 362, 171, 199, 201, 250, 200, 177, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 176, 229, 228, 197, 313, 313, 316, 32767,32767,32767,32767,32767,32767,32767,32767, 198, 202, 204, 203, 219, 220, 217, 218, 175, 221, 222, 223, 224, 157, 157, 157, 357, 357,32767, 357,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767, 158,32767, 211, 212, 276, 276, 117, 117, 117, 117, 117,32767,32767,32767,32767, 284,32767,32767, 32767,32767,32767, 286,32767,32767, 206, 207, 205,32767, 32767,32767,32767,32767,32767,32767,32767,32767, 285,32767, 32767,32767,32767,32767,32767,32767,32767, 334, 321, 272, 32767,32767,32767, 265,32767, 107, 109,32767,32767,32767, 32767, 302, 339,32767,32767,32767, 17,32767,32767,32767, 370, 334,32767,32767, 19,32767,32767,32767,32767, 227, 32767, 338, 332,32767,32767,32767,32767,32767,32767, 63, 32767,32767,32767,32767,32767, 63, 281, 63,32767, 63, 32767, 315, 287,32767, 63, 74,32767, 72,32767,32767, 76,32767, 63, 93, 93, 254, 315, 54, 63, 254, 63,32767,32767,32767,32767, 4,32767,32767,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767,32767, 267,32767, 323,32767, 337, 336, 324,32767, 265,32767, 215, 194, 266,32767, 196,32767,32767, 270, 273,32767,32767,32767, 134,32767, 268, 180,32767,32767, 32767,32767, 365,32767,32767, 174,32767,32767,32767, 130, 32767, 61, 332,32767,32767, 355,32767,32767, 332, 269, 208, 209, 210,32767, 121,32767, 310,32767,32767,32767, 32767,32767,32767, 327,32767, 333,32767,32767,32767,32767, 111,32767, 302,32767,32767,32767, 75,32767,32767, 178, 126,32767,32767, 364,32767,32767,32767, 320,32767,32767, 32767,32767,32767, 62,32767,32767, 77,32767,32767,32767, 32767, 332,32767,32767,32767, 115,32767, 169,32767,32767, 32767,32767,32767,32767,32767,32767,32767,32767,32767,32767, 32767, 332,32767,32767,32767,32767,32767,32767,32767, 4, 32767, 151,32767,32767,32767,32767,32767,32767,32767, 25, 25, 3, 137, 3, 137, 25, 101, 25, 25, 137, 93, 93, 25, 25, 25, 144, 25, 25, 25, 25, 25, 25, 25, 25 ]; PHP.Parser.prototype.yygoto = [ 141, 141, 173, 173, 173, 173, 173, 173, 173, 173, 141, 173, 142, 143, 144, 148, 153, 155, 181, 175, 172, 172, 172, 172, 174, 174, 174, 174, 174, 174, 174, 168, 169, 170, 171, 179, 757, 758, 392, 760, 781, 782, 783, 784, 785, 786, 787, 789, 725, 145, 146, 147, 149, 150, 151, 152, 154, 177, 178, 180, 196, 208, 209, 210, 211, 212, 213, 214, 215, 217, 218, 219, 220, 244, 245, 266, 267, 268, 430, 431, 432, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 156, 157, 158, 159, 176, 160, 194, 161, 162, 163, 164, 195, 165, 193, 139, 166, 167, 452, 452, 452, 452, 452, 452, 452, 452, 452, 452, 452, 453, 453, 453, 453, 453, 453, 453, 453, 453, 453, 453, 551, 551, 551, 464, 491, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 394, 407, 552, 552, 552, 810, 810, 662, 662, 662, 662, 662, 594, 283, 595, 510, 399, 399, 567, 679, 632, 849, 850, 863, 660, 714, 426, 222, 622, 622, 622, 622, 223, 617, 623, 494, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 395, 465, 472, 514, 904, 398, 398, 425, 425, 459, 425, 419, 322, 421, 421, 393, 396, 412, 422, 428, 460, 463, 473, 481, 501, 5, 476, 284, 327, 1, 15, 2, 6, 7, 550, 550, 550, 8, 9, 10, 668, 16, 11, 17, 12, 18, 13, 19, 14, 704, 328, 881, 881, 643, 628, 626, 626, 624, 626, 526, 401, 652, 647, 847, 847, 847, 847, 847, 847, 847, 847, 847, 847, 847, 437, 438, 441, 447, 477, 479, 497, 290, 910, 910, 400, 400, 486, 880, 880, 263, 913, 910, 303, 255, 723, 306, 822, 821, 306, 896, 896, 896, 861, 304, 323, 410, 913, 913, 897, 316, 420, 769, 658, 559, 879, 671, 536, 324, 466, 565, 311, 311, 311, 801, 241, 676, 496, 439, 440, 442, 444, 448, 475, 631, 858, 311, 285, 286, 603, 495, 712, 0, 406, 321, 0, 0, 0, 314, 0, 0, 429, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 411 ]; PHP.Parser.prototype.yygcheck = [ 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 86, 6, 6, 6, 21, 21, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 35, 71, 7, 7, 7, 35, 35, 35, 35, 35, 35, 35, 29, 44, 29, 35, 86, 86, 12, 12, 12, 12, 12, 12, 12, 12, 75, 40, 35, 35, 35, 35, 40, 35, 35, 35, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 82, 36, 36, 36, 104, 82, 82, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 28, 13, 42, 42, 42, 2, 13, 2, 13, 13, 5, 5, 5, 13, 13, 13, 54, 13, 13, 13, 13, 13, 13, 13, 13, 67, 67, 83, 83, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 52, 52, 52, 52, 52, 52, 52, 4, 105, 105, 89, 89, 94, 84, 84, 92, 105, 105, 26, 92, 71, 4, 91, 91, 4, 84, 84, 84, 97, 30, 70, 30, 105, 105, 102, 27, 30, 72, 50, 10, 84, 55, 46, 9, 30, 11, 90, 90, 90, 80, 30, 56, 30, 85, 85, 85, 85, 85, 85, 43, 96, 90, 44, 44, 34, 77, 69, -1, 4, 90, -1, -1, -1, 4, -1, -1, 4, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 71 ]; PHP.Parser.prototype.yygbase = [ 0, 0, -286, 0, 10, 239, 130, 154, 0, -10, 25, -23, -29, -289, 0, -30, 0, 0, 0, 0, 0, 83, 0, 0, 0, 0, 245, 84, -11, 142, -28, 0, 0, 0, -13, -88, -42, 0, 0, 0, -344, 0, -38, -12, -188, 0, 23, 0, 0, 0, 66, 0, 247, 0, 205, 24, -18, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 13, 0, -15, 85, 74, 70, 0, 0, 148, 0, -14, 0, 0, -6, 0, -35, 11, 47, 278, -77, 0, 0, 44, 68, 43, 38, 72, 94, 0, -16, 109, 0, 0, 0, 0, 87, 0, 170, 34, 0 ]; PHP.Parser.prototype.yygdefault = [ -32768, 362, 3, 546, 382, 570, 571, 572, 307, 305, 560, 566, 467, 4, 568, 140, 295, 575, 296, 500, 577, 414, 579, 580, 308, 309, 415, 315, 216, 593, 503, 313, 596, 357, 602, 301, 449, 383, 350, 461, 221, 423, 456, 630, 282, 638, 540, 646, 649, 450, 657, 352, 433, 434, 667, 672, 677, 680, 334, 325, 474, 684, 685, 256, 689, 511, 512, 703, 242, 711, 317, 724, 342, 788, 790, 397, 408, 484, 797, 326, 800, 384, 385, 386, 387, 435, 818, 815, 289, 866, 287, 443, 254, 853, 468, 356, 903, 862, 288, 388, 389, 302, 898, 341, 905, 912, 458 ]; PHP.Parser.prototype.yylhs = [ 0, 1, 2, 2, 4, 4, 3, 3, 3, 3, 3, 3, 3, 3, 3, 8, 8, 10, 10, 10, 10, 9, 9, 11, 13, 13, 14, 14, 14, 14, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 33, 33, 34, 27, 27, 30, 30, 6, 7, 7, 7, 37, 37, 37, 38, 38, 41, 41, 39, 39, 42, 42, 22, 22, 29, 29, 32, 32, 31, 31, 43, 23, 23, 23, 23, 44, 44, 45, 45, 46, 46, 20, 20, 16, 16, 47, 18, 18, 48, 17, 17, 19, 19, 36, 36, 49, 49, 50, 50, 51, 51, 51, 51, 52, 52, 53, 53, 54, 54, 24, 24, 55, 55, 55, 25, 25, 56, 56, 40, 40, 57, 57, 57, 57, 62, 62, 63, 63, 64, 64, 64, 64, 65, 66, 66, 61, 61, 58, 58, 60, 60, 68, 68, 67, 67, 67, 67, 67, 67, 59, 59, 69, 69, 26, 26, 21, 21, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 71, 77, 77, 79, 79, 80, 81, 81, 81, 81, 81, 81, 86, 86, 35, 35, 35, 72, 72, 87, 87, 82, 82, 88, 88, 88, 88, 88, 73, 73, 73, 76, 76, 76, 78, 78, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 93, 12, 12, 12, 12, 12, 12, 74, 74, 74, 74, 94, 94, 96, 96, 95, 95, 97, 97, 28, 28, 28, 28, 99, 99, 98, 98, 98, 98, 98, 100, 100, 84, 84, 89, 89, 83, 83, 101, 101, 101, 101, 90, 90, 90, 90, 85, 85, 91, 91, 91, 70, 70, 102, 102, 102, 75, 75, 103, 103, 104, 104, 104, 104, 92, 92, 92, 92, 105, 105, 105, 105, 105, 105, 105, 106, 106, 106 ]; PHP.Parser.prototype.yylen = [ 1, 1, 2, 0, 1, 3, 1, 1, 1, 1, 3, 5, 4, 3, 3, 3, 1, 1, 3, 2, 4, 3, 1, 3, 2, 0, 1, 1, 1, 1, 3, 7, 10, 5, 7, 9, 5, 2, 3, 2, 3, 2, 3, 3, 3, 3, 1, 2, 5, 7, 8, 10, 5, 1, 5, 3, 3, 2, 1, 2, 8, 1, 3, 0, 1, 9, 7, 6, 5, 1, 2, 2, 0, 2, 0, 2, 0, 2, 1, 3, 1, 4, 1, 4, 1, 4, 1, 3, 3, 3, 4, 4, 5, 0, 2, 4, 3, 1, 1, 1, 4, 0, 2, 5, 0, 2, 6, 0, 2, 0, 3, 1, 0, 1, 3, 3, 5, 0, 1, 1, 1, 1, 0, 1, 3, 1, 2, 3, 1, 1, 2, 4, 3, 1, 1, 3, 2, 0, 3, 3, 8, 3, 1, 3, 0, 2, 4, 5, 4, 4, 3, 1, 1, 1, 3, 1, 1, 0, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 3, 1, 0, 1, 1, 6, 3, 4, 4, 1, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 5, 4, 4, 4, 2, 2, 4, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1, 4, 3, 3, 2, 9, 10, 3, 0, 4, 1, 3, 2, 4, 6, 8, 4, 4, 4, 1, 1, 1, 2, 3, 1, 1, 1, 1, 1, 1, 0, 3, 3, 4, 4, 0, 2, 3, 0, 1, 1, 0, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 2, 1, 1, 3, 2, 2, 4, 3, 1, 3, 3, 3, 0, 2, 0, 1, 3, 1, 3, 1, 1, 1, 1, 1, 6, 4, 3, 6, 4, 4, 4, 1, 3, 1, 2, 1, 1, 4, 1, 3, 6, 4, 4, 4, 4, 1, 4, 0, 1, 1, 3, 1, 3, 1, 1, 4, 0, 0, 2, 3, 1, 3, 1, 4, 2, 2, 2, 1, 2, 1, 4, 3, 3, 3, 6, 3, 1, 1, 1 ]; PHP.Parser.prototype.yyn0 = function () { this.yyval = this.yyastk[ this.stackPos ]; }; PHP.Parser.prototype.yyn1 = function ( attributes ) { this.yyval = this.Stmt_Namespace_postprocess(this.yyastk[ this.stackPos-(1-1) ]); }; PHP.Parser.prototype.yyn2 = function ( attributes ) { if (Array.isArray(this.yyastk[ this.stackPos-(2-2) ])) { this.yyval = this.yyastk[ this.stackPos-(2-1) ].concat( this.yyastk[ this.stackPos-(2-2) ]); } else { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; }; PHP.Parser.prototype.yyn3 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn4 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn5 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn6 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn7 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn8 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn9 = function ( attributes ) { this.yyval = this.Node_Stmt_HaltCompiler(attributes); }; PHP.Parser.prototype.yyn10 = function ( attributes ) { this.yyval = this.Node_Stmt_Namespace(this.Node_Name(this.yyastk[ this.stackPos-(3-2) ], attributes), null, attributes); }; PHP.Parser.prototype.yyn11 = function ( attributes ) { this.yyval = this.Node_Stmt_Namespace(this.Node_Name(this.yyastk[ this.stackPos-(5-2) ], attributes), this.yyastk[ this.stackPos-(5-4) ], attributes); }; PHP.Parser.prototype.yyn12 = function ( attributes ) { this.yyval = this.Node_Stmt_Namespace(null, this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn13 = function ( attributes ) { this.yyval = this.Node_Stmt_Use(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn14 = function ( attributes ) { this.yyval = this.Node_Stmt_Const(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn15 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn16 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn17 = function ( attributes ) { this.yyval = this.Node_Stmt_UseUse(this.Node_Name(this.yyastk[ this.stackPos-(1-1) ], attributes), null, attributes); }; PHP.Parser.prototype.yyn18 = function ( attributes ) { this.yyval = this.Node_Stmt_UseUse(this.Node_Name(this.yyastk[ this.stackPos-(3-1) ], attributes), this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn19 = function ( attributes ) { this.yyval = this.Node_Stmt_UseUse(this.Node_Name(this.yyastk[ this.stackPos-(2-2) ], attributes), null, attributes); }; PHP.Parser.prototype.yyn20 = function ( attributes ) { this.yyval = this.Node_Stmt_UseUse(this.Node_Name(this.yyastk[ this.stackPos-(4-2) ], attributes), this.yyastk[ this.stackPos-(4-4) ], attributes); }; PHP.Parser.prototype.yyn21 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn22 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn23 = function ( attributes ) { this.yyval = this.Node_Const(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn24 = function ( attributes ) { if (Array.isArray(this.yyastk[ this.stackPos-(2-2) ])) { this.yyval = this.yyastk[ this.stackPos-(2-1) ].concat( this.yyastk[ this.stackPos-(2-2) ]); } else { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; }; PHP.Parser.prototype.yyn25 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn26 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn27 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn28 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn29 = function ( attributes ) { throw new Error('__halt_compiler() can only be used from the outermost scope'); }; PHP.Parser.prototype.yyn30 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn31 = function ( attributes ) { this.yyval = this.Node_Stmt_If(this.yyastk[ this.stackPos-(7-3) ], {'stmts': Array.isArray(this.yyastk[ this.stackPos-(7-5) ]) ? this.yyastk[ this.stackPos-(7-5) ] : [this.yyastk[ this.stackPos-(7-5) ]], 'elseifs': this.yyastk[ this.stackPos-(7-6) ], 'Else': this.yyastk[ this.stackPos-(7-7) ]}, attributes); }; PHP.Parser.prototype.yyn32 = function ( attributes ) { this.yyval = this.Node_Stmt_If(this.yyastk[ this.stackPos-(10-3) ], {'stmts': this.yyastk[ this.stackPos-(10-6) ], 'elseifs': this.yyastk[ this.stackPos-(10-7) ], 'else': this.yyastk[ this.stackPos-(10-8) ]}, attributes); }; PHP.Parser.prototype.yyn33 = function ( attributes ) { this.yyval = this.Node_Stmt_While(this.yyastk[ this.stackPos-(5-3) ], this.yyastk[ this.stackPos-(5-5) ], attributes); }; PHP.Parser.prototype.yyn34 = function ( attributes ) { this.yyval = this.Node_Stmt_Do(this.yyastk[ this.stackPos-(7-5) ], Array.isArray(this.yyastk[ this.stackPos-(7-2) ]) ? this.yyastk[ this.stackPos-(7-2) ] : [this.yyastk[ this.stackPos-(7-2) ]], attributes); }; PHP.Parser.prototype.yyn35 = function ( attributes ) { this.yyval = this.Node_Stmt_For({'init': this.yyastk[ this.stackPos-(9-3) ], 'cond': this.yyastk[ this.stackPos-(9-5) ], 'loop': this.yyastk[ this.stackPos-(9-7) ], 'stmts': this.yyastk[ this.stackPos-(9-9) ]}, attributes); }; PHP.Parser.prototype.yyn36 = function ( attributes ) { this.yyval = this.Node_Stmt_Switch(this.yyastk[ this.stackPos-(5-3) ], this.yyastk[ this.stackPos-(5-5) ], attributes); }; PHP.Parser.prototype.yyn37 = function ( attributes ) { this.yyval = this.Node_Stmt_Break(null, attributes); }; PHP.Parser.prototype.yyn38 = function ( attributes ) { this.yyval = this.Node_Stmt_Break(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn39 = function ( attributes ) { this.yyval = this.Node_Stmt_Continue(null, attributes); }; PHP.Parser.prototype.yyn40 = function ( attributes ) { this.yyval = this.Node_Stmt_Continue(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn41 = function ( attributes ) { this.yyval = this.Node_Stmt_Return(null, attributes); }; PHP.Parser.prototype.yyn42 = function ( attributes ) { this.yyval = this.Node_Stmt_Return(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn43 = function ( attributes ) { this.yyval = this.Node_Stmt_Global(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn44 = function ( attributes ) { this.yyval = this.Node_Stmt_Static(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn45 = function ( attributes ) { this.yyval = this.Node_Stmt_Echo(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn46 = function ( attributes ) { this.yyval = this.Node_Stmt_InlineHTML(this.yyastk[ this.stackPos-(1-1) ], attributes); }; PHP.Parser.prototype.yyn47 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn48 = function ( attributes ) { this.yyval = this.Node_Stmt_Unset(this.yyastk[ this.stackPos-(5-3) ], attributes); }; PHP.Parser.prototype.yyn49 = function ( attributes ) { this.yyval = this.Node_Stmt_Foreach(this.yyastk[ this.stackPos-(7-3) ], this.yyastk[ this.stackPos-(7-5) ], {'keyVar': null, 'byRef': false, 'stmts': this.yyastk[ this.stackPos-(7-7) ]}, attributes); }; PHP.Parser.prototype.yyn50 = function ( attributes ) { this.yyval = this.Node_Stmt_Foreach(this.yyastk[ this.stackPos-(8-3) ], this.yyastk[ this.stackPos-(8-6) ], {'keyVar': null, 'byRef': true, 'stmts': this.yyastk[ this.stackPos-(8-8) ]}, attributes); }; PHP.Parser.prototype.yyn51 = function ( attributes ) { this.yyval = this.Node_Stmt_Foreach(this.yyastk[ this.stackPos-(10-3) ], this.yyastk[ this.stackPos-(10-8) ], {'keyVar': this.yyastk[ this.stackPos-(10-5) ], 'byRef': this.yyastk[ this.stackPos-(10-7) ], 'stmts': this.yyastk[ this.stackPos-(10-10) ]}, attributes); }; PHP.Parser.prototype.yyn52 = function ( attributes ) { this.yyval = this.Node_Stmt_Declare(this.yyastk[ this.stackPos-(5-3) ], this.yyastk[ this.stackPos-(5-5) ], attributes); }; PHP.Parser.prototype.yyn53 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn54 = function ( attributes ) { this.yyval = this.Node_Stmt_TryCatch(this.yyastk[ this.stackPos-(5-3) ], this.yyastk[ this.stackPos-(5-5) ], attributes); }; PHP.Parser.prototype.yyn55 = function ( attributes ) { this.yyval = this.Node_Stmt_Throw(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn56 = function ( attributes ) { this.yyval = this.Node_Stmt_Goto(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn57 = function ( attributes ) { this.yyval = this.Node_Stmt_Label(this.yyastk[ this.stackPos-(2-1) ], attributes); }; PHP.Parser.prototype.yyn58 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn59 = function ( attributes ) { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn60 = function ( attributes ) { this.yyval = this.Node_Stmt_Catch(this.yyastk[ this.stackPos-(8-3) ], this.yyastk[ this.stackPos-(8-4) ].substring( 1 ), this.yyastk[ this.stackPos-(8-7) ], attributes); }; PHP.Parser.prototype.yyn61 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn62 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn63 = function ( attributes ) { this.yyval = false; }; PHP.Parser.prototype.yyn64 = function ( attributes ) { this.yyval = true; }; PHP.Parser.prototype.yyn65 = function ( attributes ) { this.yyval = this.Node_Stmt_Function(this.yyastk[ this.stackPos-(9-3) ], {'byRef': this.yyastk[ this.stackPos-(9-2) ], 'params': this.yyastk[ this.stackPos-(9-5) ], 'stmts': this.yyastk[ this.stackPos-(9-8) ]}, attributes); }; PHP.Parser.prototype.yyn66 = function ( attributes ) { this.yyval = this.Node_Stmt_Class(this.yyastk[ this.stackPos-(7-2) ], {'type': this.yyastk[ this.stackPos-(7-1) ], 'Extends': this.yyastk[ this.stackPos-(7-3) ], 'Implements': this.yyastk[ this.stackPos-(7-4) ], 'stmts': this.yyastk[ this.stackPos-(7-6) ]}, attributes); }; PHP.Parser.prototype.yyn67 = function ( attributes ) { this.yyval = this.Node_Stmt_Interface(this.yyastk[ this.stackPos-(6-2) ], {'Extends': this.yyastk[ this.stackPos-(6-3) ], 'stmts': this.yyastk[ this.stackPos-(6-5) ]}, attributes); }; PHP.Parser.prototype.yyn68 = function ( attributes ) { this.yyval = this.Node_Stmt_Trait(this.yyastk[ this.stackPos-(5-2) ], this.yyastk[ this.stackPos-(5-4) ], attributes); }; PHP.Parser.prototype.yyn69 = function ( attributes ) { this.yyval = 0; }; PHP.Parser.prototype.yyn70 = function ( attributes ) { this.yyval = this.MODIFIER_ABSTRACT; }; PHP.Parser.prototype.yyn71 = function ( attributes ) { this.yyval = this.MODIFIER_FINAL; }; PHP.Parser.prototype.yyn72 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn73 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(2-2) ]; }; PHP.Parser.prototype.yyn74 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn75 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(2-2) ]; }; PHP.Parser.prototype.yyn76 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn77 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(2-2) ]; }; PHP.Parser.prototype.yyn78 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn79 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn80 = function ( attributes ) { this.yyval = Array.isArray(this.yyastk[ this.stackPos-(1-1) ]) ? this.yyastk[ this.stackPos-(1-1) ] : [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn81 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(4-2) ]; }; PHP.Parser.prototype.yyn82 = function ( attributes ) { this.yyval = Array.isArray(this.yyastk[ this.stackPos-(1-1) ]) ? this.yyastk[ this.stackPos-(1-1) ] : [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn83 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(4-2) ]; }; PHP.Parser.prototype.yyn84 = function ( attributes ) { this.yyval = Array.isArray(this.yyastk[ this.stackPos-(1-1) ]) ? this.yyastk[ this.stackPos-(1-1) ] : [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn85 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(4-2) ]; }; PHP.Parser.prototype.yyn86 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn87 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn88 = function ( attributes ) { this.yyval = this.Node_Stmt_DeclareDeclare(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn89 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn90 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(4-3) ]; }; PHP.Parser.prototype.yyn91 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(4-2) ]; }; PHP.Parser.prototype.yyn92 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(5-3) ]; }; PHP.Parser.prototype.yyn93 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn94 = function ( attributes ) { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn95 = function ( attributes ) { this.yyval = this.Node_Stmt_Case(this.yyastk[ this.stackPos-(4-2) ], this.yyastk[ this.stackPos-(4-4) ], attributes); }; PHP.Parser.prototype.yyn96 = function ( attributes ) { this.yyval = this.Node_Stmt_Case(null, this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn97 = function () { this.yyval = this.yyastk[ this.stackPos ]; }; PHP.Parser.prototype.yyn98 = function () { this.yyval = this.yyastk[ this.stackPos ]; }; PHP.Parser.prototype.yyn99 = function ( attributes ) { this.yyval = Array.isArray(this.yyastk[ this.stackPos-(1-1) ]) ? this.yyastk[ this.stackPos-(1-1) ] : [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn100 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(4-2) ]; }; PHP.Parser.prototype.yyn101 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn102 = function ( attributes ) { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn103 = function ( attributes ) { this.yyval = this.Node_Stmt_ElseIf(this.yyastk[ this.stackPos-(5-3) ], Array.isArray(this.yyastk[ this.stackPos-(5-5) ]) ? this.yyastk[ this.stackPos-(5-5) ] : [this.yyastk[ this.stackPos-(5-5) ]], attributes); }; PHP.Parser.prototype.yyn104 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn105 = function ( attributes ) { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn106 = function ( attributes ) { this.yyval = this.Node_Stmt_ElseIf(this.yyastk[ this.stackPos-(6-3) ], this.yyastk[ this.stackPos-(6-6) ], attributes); }; PHP.Parser.prototype.yyn107 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn108 = function ( attributes ) { this.yyval = this.Node_Stmt_Else(Array.isArray(this.yyastk[ this.stackPos-(2-2) ]) ? this.yyastk[ this.stackPos-(2-2) ] : [this.yyastk[ this.stackPos-(2-2) ]], attributes); }; PHP.Parser.prototype.yyn109 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn110 = function ( attributes ) { this.yyval = this.Node_Stmt_Else(this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn111 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn112 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn113 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn114 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn115 = function ( attributes ) { this.yyval = this.Node_Param(this.yyastk[ this.stackPos-(3-3) ].substring( 1 ), null, this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn116 = function ( attributes ) { this.yyval = this.Node_Param(this.yyastk[ this.stackPos-(5-3) ].substring( 1 ), this.yyastk[ this.stackPos-(5-5) ], this.yyastk[ this.stackPos-(5-1) ], this.yyastk[ this.stackPos-(5-2) ], attributes); }; PHP.Parser.prototype.yyn117 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn118 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn119 = function ( attributes ) { this.yyval = 'array'; }; PHP.Parser.prototype.yyn120 = function ( attributes ) { this.yyval = 'callable'; }; PHP.Parser.prototype.yyn121 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn122 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn123 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn124 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn125 = function ( attributes ) { this.yyval = this.Node_Arg(this.yyastk[ this.stackPos-(1-1) ], false, attributes); }; PHP.Parser.prototype.yyn126 = function ( attributes ) { this.yyval = this.Node_Arg(this.yyastk[ this.stackPos-(2-2) ], true, attributes); }; PHP.Parser.prototype.yyn127 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn128 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn129 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(1-1) ].substring( 1 ), attributes); }; PHP.Parser.prototype.yyn130 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn131 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn132 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn133 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn134 = function ( attributes ) { this.yyval = this.Node_Stmt_StaticVar(this.yyastk[ this.stackPos-(1-1) ].substring( 1 ), null, attributes); }; PHP.Parser.prototype.yyn135 = function ( attributes ) { this.yyval = this.Node_Stmt_StaticVar(this.yyastk[ this.stackPos-(3-1) ].substring( 1 ), this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn136 = function ( attributes ) { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn137 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn138 = function ( attributes ) { this.yyval = this.Node_Stmt_Property(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn139 = function ( attributes ) { this.yyval = this.Node_Stmt_ClassConst(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn140 = function ( attributes ) { this.yyval = this.Node_Stmt_ClassMethod(this.yyastk[ this.stackPos-(8-4) ], {'type': this.yyastk[ this.stackPos-(8-1) ], 'byRef': this.yyastk[ this.stackPos-(8-3) ], 'params': this.yyastk[ this.stackPos-(8-6) ], 'stmts': this.yyastk[ this.stackPos-(8-8) ]}, attributes); }; PHP.Parser.prototype.yyn141 = function ( attributes ) { this.yyval = this.Node_Stmt_TraitUse(this.yyastk[ this.stackPos-(3-2) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn142 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn143 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn144 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn145 = function ( attributes ) { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn146 = function ( attributes ) { this.yyval = this.Node_Stmt_TraitUseAdaptation_Precedence(this.yyastk[ this.stackPos-(4-1) ][0], this.yyastk[ this.stackPos-(4-1) ][1], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn147 = function ( attributes ) { this.yyval = this.Node_Stmt_TraitUseAdaptation_Alias(this.yyastk[ this.stackPos-(5-1) ][0], this.yyastk[ this.stackPos-(5-1) ][1], this.yyastk[ this.stackPos-(5-3) ], this.yyastk[ this.stackPos-(5-4) ], attributes); }; PHP.Parser.prototype.yyn148 = function ( attributes ) { this.yyval = this.Node_Stmt_TraitUseAdaptation_Alias(this.yyastk[ this.stackPos-(4-1) ][0], this.yyastk[ this.stackPos-(4-1) ][1], this.yyastk[ this.stackPos-(4-3) ], null, attributes); }; PHP.Parser.prototype.yyn149 = function ( attributes ) { this.yyval = this.Node_Stmt_TraitUseAdaptation_Alias(this.yyastk[ this.stackPos-(4-1) ][0], this.yyastk[ this.stackPos-(4-1) ][1], null, this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn150 = function ( attributes ) { this.yyval = array(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ]); }; PHP.Parser.prototype.yyn151 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn152 = function ( attributes ) { this.yyval = array(null, this.yyastk[ this.stackPos-(1-1) ]); }; PHP.Parser.prototype.yyn153 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn154 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn155 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn156 = function ( attributes ) { this.yyval = this.MODIFIER_PUBLIC; }; PHP.Parser.prototype.yyn157 = function ( attributes ) { this.yyval = this.MODIFIER_PUBLIC; }; PHP.Parser.prototype.yyn158 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn159 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn160 = function ( attributes ) { this.Stmt_Class_verifyModifier(this.yyastk[ this.stackPos-(2-1) ], this.yyastk[ this.stackPos-(2-2) ]); this.yyval = this.yyastk[ this.stackPos-(2-1) ] | this.yyastk[ this.stackPos-(2-2) ]; }; PHP.Parser.prototype.yyn161 = function ( attributes ) { this.yyval = this.MODIFIER_PUBLIC; }; PHP.Parser.prototype.yyn162 = function ( attributes ) { this.yyval = this.MODIFIER_PROTECTED; }; PHP.Parser.prototype.yyn163 = function ( attributes ) { this.yyval = this.MODIFIER_PRIVATE; }; PHP.Parser.prototype.yyn164 = function ( attributes ) { this.yyval = this.MODIFIER_STATIC; }; PHP.Parser.prototype.yyn165 = function ( attributes ) { this.yyval = this.MODIFIER_ABSTRACT; }; PHP.Parser.prototype.yyn166 = function ( attributes ) { this.yyval = this.MODIFIER_FINAL; }; PHP.Parser.prototype.yyn167 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn168 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn169 = function ( attributes ) { this.yyval = this.Node_Stmt_PropertyProperty(this.yyastk[ this.stackPos-(1-1) ].substring( 1 ), null, attributes); }; PHP.Parser.prototype.yyn170 = function ( attributes ) { this.yyval = this.Node_Stmt_PropertyProperty(this.yyastk[ this.stackPos-(3-1) ].substring( 1 ), this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn171 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn172 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn173 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn174 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn175 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn176 = function ( attributes ) { this.yyval = this.Node_Expr_AssignList(this.yyastk[ this.stackPos-(6-3) ], this.yyastk[ this.stackPos-(6-6) ], attributes); }; PHP.Parser.prototype.yyn177 = function ( attributes ) { this.yyval = this.Node_Expr_Assign(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn178 = function ( attributes ) { this.yyval = this.Node_Expr_AssignRef(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-4) ], attributes); }; PHP.Parser.prototype.yyn179 = function ( attributes ) { this.yyval = this.Node_Expr_AssignRef(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-4) ], attributes); }; PHP.Parser.prototype.yyn180 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn181 = function ( attributes ) { this.yyval = this.Node_Expr_Clone(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn182 = function ( attributes ) { this.yyval = this.Node_Expr_AssignPlus(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn183 = function ( attributes ) { this.yyval = this.Node_Expr_AssignMinus(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn184 = function ( attributes ) { this.yyval = this.Node_Expr_AssignMul(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn185 = function ( attributes ) { this.yyval = this.Node_Expr_AssignDiv(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn186 = function ( attributes ) { this.yyval = this.Node_Expr_AssignConcat(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn187 = function ( attributes ) { this.yyval = this.Node_Expr_AssignMod(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn188 = function ( attributes ) { this.yyval = this.Node_Expr_AssignBitwiseAnd(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn189 = function ( attributes ) { this.yyval = this.Node_Expr_AssignBitwiseOr(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn190 = function ( attributes ) { this.yyval = this.Node_Expr_AssignBitwiseXor(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn191 = function ( attributes ) { this.yyval = this.Node_Expr_AssignShiftLeft(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn192 = function ( attributes ) { this.yyval = this.Node_Expr_AssignShiftRight(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn193 = function ( attributes ) { this.yyval = this.Node_Expr_PostInc(this.yyastk[ this.stackPos-(2-1) ], attributes); }; PHP.Parser.prototype.yyn194 = function ( attributes ) { this.yyval = this.Node_Expr_PreInc(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn195 = function ( attributes ) { this.yyval = this.Node_Expr_PostDec(this.yyastk[ this.stackPos-(2-1) ], attributes); }; PHP.Parser.prototype.yyn196 = function ( attributes ) { this.yyval = this.Node_Expr_PreDec(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn197 = function ( attributes ) { this.yyval = this.Node_Expr_BooleanOr(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn198 = function ( attributes ) { this.yyval = this.Node_Expr_BooleanAnd(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn199 = function ( attributes ) { this.yyval = this.Node_Expr_LogicalOr(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn200 = function ( attributes ) { this.yyval = this.Node_Expr_LogicalAnd(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn201 = function ( attributes ) { this.yyval = this.Node_Expr_LogicalXor(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn202 = function ( attributes ) { this.yyval = this.Node_Expr_BitwiseOr(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn203 = function ( attributes ) { this.yyval = this.Node_Expr_BitwiseAnd(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn204 = function ( attributes ) { this.yyval = this.Node_Expr_BitwiseXor(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn205 = function ( attributes ) { this.yyval = this.Node_Expr_Concat(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn206 = function ( attributes ) { this.yyval = this.Node_Expr_Plus(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn207 = function ( attributes ) { this.yyval = this.Node_Expr_Minus(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn208 = function ( attributes ) { this.yyval = this.Node_Expr_Mul(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn209 = function ( attributes ) { this.yyval = this.Node_Expr_Div(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn210 = function ( attributes ) { this.yyval = this.Node_Expr_Mod(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn211 = function ( attributes ) { this.yyval = this.Node_Expr_ShiftLeft(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn212 = function ( attributes ) { this.yyval = this.Node_Expr_ShiftRight(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn213 = function ( attributes ) { this.yyval = this.Node_Expr_UnaryPlus(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn214 = function ( attributes ) { this.yyval = this.Node_Expr_UnaryMinus(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn215 = function ( attributes ) { this.yyval = this.Node_Expr_BooleanNot(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn216 = function ( attributes ) { this.yyval = this.Node_Expr_BitwiseNot(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn217 = function ( attributes ) { this.yyval = this.Node_Expr_Identical(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn218 = function ( attributes ) { this.yyval = this.Node_Expr_NotIdentical(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn219 = function ( attributes ) { this.yyval = this.Node_Expr_Equal(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn220 = function ( attributes ) { this.yyval = this.Node_Expr_NotEqual(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn221 = function ( attributes ) { this.yyval = this.Node_Expr_Smaller(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn222 = function ( attributes ) { this.yyval = this.Node_Expr_SmallerOrEqual(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn223 = function ( attributes ) { this.yyval = this.Node_Expr_Greater(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn224 = function ( attributes ) { this.yyval = this.Node_Expr_GreaterOrEqual(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn225 = function ( attributes ) { this.yyval = this.Node_Expr_Instanceof(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn226 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn227 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn228 = function ( attributes ) { this.yyval = this.Node_Expr_Ternary(this.yyastk[ this.stackPos-(5-1) ], this.yyastk[ this.stackPos-(5-3) ], this.yyastk[ this.stackPos-(5-5) ], attributes); }; PHP.Parser.prototype.yyn229 = function ( attributes ) { this.yyval = this.Node_Expr_Ternary(this.yyastk[ this.stackPos-(4-1) ], null, this.yyastk[ this.stackPos-(4-4) ], attributes); }; PHP.Parser.prototype.yyn230 = function ( attributes ) { this.yyval = this.Node_Expr_Isset(this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn231 = function ( attributes ) { this.yyval = this.Node_Expr_Empty(this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn232 = function ( attributes ) { this.yyval = this.Node_Expr_Include(this.yyastk[ this.stackPos-(2-2) ], "Node_Expr_Include", attributes); }; PHP.Parser.prototype.yyn233 = function ( attributes ) { this.yyval = this.Node_Expr_Include(this.yyastk[ this.stackPos-(2-2) ], "Node_Expr_IncludeOnce", attributes); }; PHP.Parser.prototype.yyn234 = function ( attributes ) { this.yyval = this.Node_Expr_Eval(this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn235 = function ( attributes ) { this.yyval = this.Node_Expr_Include(this.yyastk[ this.stackPos-(2-2) ], "Node_Expr_Require", attributes); }; PHP.Parser.prototype.yyn236 = function ( attributes ) { this.yyval = this.Node_Expr_Include(this.yyastk[ this.stackPos-(2-2) ], "Node_Expr_RequireOnce", attributes); }; PHP.Parser.prototype.yyn237 = function ( attributes ) { this.yyval = this.Node_Expr_Cast_Int(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn238 = function ( attributes ) { this.yyval = this.Node_Expr_Cast_Double(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn239 = function ( attributes ) { this.yyval = this.Node_Expr_Cast_String(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn240 = function ( attributes ) { this.yyval = this.Node_Expr_Cast_Array(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn241 = function ( attributes ) { this.yyval = this.Node_Expr_Cast_Object(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn242 = function ( attributes ) { this.yyval = this.Node_Expr_Cast_Bool(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn243 = function ( attributes ) { this.yyval = this.Node_Expr_Cast_Unset(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn244 = function ( attributes ) { this.yyval = this.Node_Expr_Exit(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn245 = function ( attributes ) { this.yyval = this.Node_Expr_ErrorSuppress(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn246 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn247 = function ( attributes ) { this.yyval = this.Node_Expr_Array(this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn248 = function ( attributes ) { this.yyval = this.Node_Expr_Array(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn249 = function ( attributes ) { this.yyval = this.Node_Expr_ShellExec(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn250 = function ( attributes ) { this.yyval = this.Node_Expr_Print(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn251 = function ( attributes ) { this.yyval = this.Node_Expr_Closure({'static': false, 'byRef': this.yyastk[ this.stackPos-(9-2) ], 'params': this.yyastk[ this.stackPos-(9-4) ], 'uses': this.yyastk[ this.stackPos-(9-6) ], 'stmts': this.yyastk[ this.stackPos-(9-8) ]}, attributes); }; PHP.Parser.prototype.yyn252 = function ( attributes ) { this.yyval = this.Node_Expr_Closure({'static': true, 'byRef': this.yyastk[ this.stackPos-(10-3) ], 'params': this.yyastk[ this.stackPos-(10-5) ], 'uses': this.yyastk[ this.stackPos-(10-7) ], 'stmts': this.yyastk[ this.stackPos-(10-9) ]}, attributes); }; PHP.Parser.prototype.yyn253 = function ( attributes ) { this.yyval = this.Node_Expr_New(this.yyastk[ this.stackPos-(3-2) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn254 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn255 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(4-3) ]; }; PHP.Parser.prototype.yyn256 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn257 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn258 = function ( attributes ) { this.yyval = this.Node_Expr_ClosureUse(this.yyastk[ this.stackPos-(2-2) ].substring( 1 ), this.yyastk[ this.stackPos-(2-1) ], attributes); }; PHP.Parser.prototype.yyn259 = function ( attributes ) { this.yyval = this.Node_Expr_FuncCall(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn260 = function ( attributes ) { this.yyval = this.Node_Expr_StaticCall(this.yyastk[ this.stackPos-(6-1) ], this.yyastk[ this.stackPos-(6-3) ], this.yyastk[ this.stackPos-(6-5) ], attributes); }; PHP.Parser.prototype.yyn261 = function ( attributes ) { this.yyval = this.Node_Expr_StaticCall(this.yyastk[ this.stackPos-(8-1) ], this.yyastk[ this.stackPos-(8-4) ], this.yyastk[ this.stackPos-(8-7) ], attributes); }; PHP.Parser.prototype.yyn262 = function ( attributes ) { if (this.yyastk[ this.stackPos-(4-1) ].type === "Node_Expr_StaticPropertyFetch") { this.yyval = this.Node_Expr_StaticCall(this.yyastk[ this.stackPos-(4-1) ].Class, this.Node_Expr_Variable(this.yyastk[ this.stackPos-(4-1) ].name, attributes), this.yyastk[ this.stackPos-(4-3) ], attributes); } else if (this.yyastk[ this.stackPos-(4-1) ].type === "Node_Expr_ArrayDimFetch") { var tmp = this.yyastk[ this.stackPos-(4-1) ]; while (tmp.variable.type === "Node_Expr_ArrayDimFetch") { tmp = tmp.variable; } this.yyval = this.Node_Expr_StaticCall(tmp.variable.Class, this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); tmp.variable = this.Node_Expr_Variable(tmp.variable.name, attributes); } else { throw new Exception; } }; PHP.Parser.prototype.yyn263 = function ( attributes ) { this.yyval = this.Node_Expr_FuncCall(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn264 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn265 = function ( attributes ) { this.yyval = this.Node_Name('static', attributes); }; PHP.Parser.prototype.yyn266 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn267 = function ( attributes ) { this.yyval = this.Node_Name(this.yyastk[ this.stackPos-(1-1) ], attributes); }; PHP.Parser.prototype.yyn268 = function ( attributes ) { this.yyval = this.Node_Name_FullyQualified(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn269 = function ( attributes ) { this.yyval = this.Node_Name_Relative(this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn270 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn271 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn272 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn273 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn274 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn275 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn276 = function () { this.yyval = this.yyastk[ this.stackPos ]; }; PHP.Parser.prototype.yyn277 = function ( attributes ) { this.yyval = this.Node_Expr_PropertyFetch(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn278 = function ( attributes ) { this.yyval = this.Node_Expr_PropertyFetch(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn279 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn280 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn281 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn282 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn283 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn284 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn285 = function ( attributes ) { this.yyval = [this.Scalar_String_parseEscapeSequences(this.yyastk[ this.stackPos-(1-1) ], '`')]; }; PHP.Parser.prototype.yyn286 = function ( attributes ) { ; this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn287 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn288 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn289 = function ( attributes ) { this.yyval = this.Node_Scalar_LNumber(this.Scalar_LNumber_parse(this.yyastk[ this.stackPos-(1-1) ]), attributes); }; PHP.Parser.prototype.yyn290 = function ( attributes ) { this.yyval = this.Node_Scalar_DNumber(this.Scalar_DNumber_parse(this.yyastk[ this.stackPos-(1-1) ]), attributes); }; PHP.Parser.prototype.yyn291 = function ( attributes ) { this.yyval = this.Scalar_String_create(this.yyastk[ this.stackPos-(1-1) ], attributes); }; PHP.Parser.prototype.yyn292 = function ( attributes ) { this.yyval = {type: "Node_Scalar_LineConst", attributes: attributes}; }; PHP.Parser.prototype.yyn293 = function ( attributes ) { this.yyval = {type: "Node_Scalar_FileConst", attributes: attributes}; }; PHP.Parser.prototype.yyn294 = function ( attributes ) { this.yyval = {type: "Node_Scalar_DirConst", attributes: attributes}; }; PHP.Parser.prototype.yyn295 = function ( attributes ) { this.yyval = {type: "Node_Scalar_ClassConst", attributes: attributes}; }; PHP.Parser.prototype.yyn296 = function ( attributes ) { this.yyval = {type: "Node_Scalar_TraitConst", attributes: attributes}; }; PHP.Parser.prototype.yyn297 = function ( attributes ) { this.yyval = {type: "Node_Scalar_MethodConst", attributes: attributes}; }; PHP.Parser.prototype.yyn298 = function ( attributes ) { this.yyval = {type: "Node_Scalar_FuncConst", attributes: attributes}; }; PHP.Parser.prototype.yyn299 = function ( attributes ) { this.yyval = {type: "Node_Scalar_NSConst", attributes: attributes}; }; PHP.Parser.prototype.yyn300 = function ( attributes ) { this.yyval = this.Node_Scalar_String(this.Scalar_String_parseDocString(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-2) ]), attributes); }; PHP.Parser.prototype.yyn301 = function ( attributes ) { this.yyval = this.Node_Scalar_String('', attributes); }; PHP.Parser.prototype.yyn302 = function ( attributes ) { this.yyval = this.Node_Expr_ConstFetch(this.yyastk[ this.stackPos-(1-1) ], attributes); }; PHP.Parser.prototype.yyn303 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn304 = function ( attributes ) { this.yyval = this.Node_Expr_ClassConstFetch(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn305 = function ( attributes ) { this.yyval = this.Node_Expr_UnaryPlus(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn306 = function ( attributes ) { this.yyval = this.Node_Expr_UnaryMinus(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn307 = function ( attributes ) { this.yyval = this.Node_Expr_Array(this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn308 = function ( attributes ) { this.yyval = this.Node_Expr_Array(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn309 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn310 = function ( attributes ) { this.yyval = this.Node_Expr_ClassConstFetch(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn311 = function ( attributes ) { ; this.yyval = this.Node_Scalar_Encapsed(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn312 = function ( attributes ) { ; this.yyval = this.Node_Scalar_Encapsed(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn313 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn314 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn315 = function () { this.yyval = this.yyastk[ this.stackPos ]; }; PHP.Parser.prototype.yyn316 = function () { this.yyval = this.yyastk[ this.stackPos ]; }; PHP.Parser.prototype.yyn317 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn318 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn319 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayItem(this.yyastk[ this.stackPos-(3-3) ], this.yyastk[ this.stackPos-(3-1) ], false, attributes); }; PHP.Parser.prototype.yyn320 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayItem(this.yyastk[ this.stackPos-(1-1) ], null, false, attributes); }; PHP.Parser.prototype.yyn321 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn322 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn323 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn324 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn325 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(6-2) ], this.yyastk[ this.stackPos-(6-5) ], attributes); }; PHP.Parser.prototype.yyn326 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn327 = function ( attributes ) { this.yyval = this.Node_Expr_PropertyFetch(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn328 = function ( attributes ) { this.yyval = this.Node_Expr_MethodCall(this.yyastk[ this.stackPos-(6-1) ], this.yyastk[ this.stackPos-(6-3) ], this.yyastk[ this.stackPos-(6-5) ], attributes); }; PHP.Parser.prototype.yyn329 = function ( attributes ) { this.yyval = this.Node_Expr_FuncCall(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn330 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn331 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn332 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn333 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn334 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn335 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(2-2) ], attributes); }; PHP.Parser.prototype.yyn336 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn337 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn338 = function ( attributes ) { this.yyval = this.Node_Expr_StaticPropertyFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-4) ], attributes); }; PHP.Parser.prototype.yyn339 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn340 = function ( attributes ) { this.yyval = this.Node_Expr_StaticPropertyFetch(this.yyastk[ this.stackPos-(3-1) ], this.yyastk[ this.stackPos-(3-3) ].substring( 1 ), attributes); }; PHP.Parser.prototype.yyn341 = function ( attributes ) { this.yyval = this.Node_Expr_StaticPropertyFetch(this.yyastk[ this.stackPos-(6-1) ], this.yyastk[ this.stackPos-(6-5) ], attributes); }; PHP.Parser.prototype.yyn342 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn343 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn344 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn345 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.yyastk[ this.stackPos-(4-1) ], this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn346 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(1-1) ].substring( 1 ), attributes); }; PHP.Parser.prototype.yyn347 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn348 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn349 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn350 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn351 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn352 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn353 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn354 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn355 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(1-1) ]; }; PHP.Parser.prototype.yyn356 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(4-3) ]; }; PHP.Parser.prototype.yyn357 = function ( attributes ) { this.yyval = null; }; PHP.Parser.prototype.yyn358 = function ( attributes ) { this.yyval = []; }; PHP.Parser.prototype.yyn359 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn360 = function ( attributes ) { this.yyastk[ this.stackPos-(3-1) ].push( this.yyastk[ this.stackPos-(3-3) ] ); this.yyval = this.yyastk[ this.stackPos-(3-1) ]; }; PHP.Parser.prototype.yyn361 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn362 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayItem(this.yyastk[ this.stackPos-(3-3) ], this.yyastk[ this.stackPos-(3-1) ], false, attributes); }; PHP.Parser.prototype.yyn363 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayItem(this.yyastk[ this.stackPos-(1-1) ], null, false, attributes); }; PHP.Parser.prototype.yyn364 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayItem(this.yyastk[ this.stackPos-(4-4) ], this.yyastk[ this.stackPos-(4-1) ], true, attributes); }; PHP.Parser.prototype.yyn365 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayItem(this.yyastk[ this.stackPos-(2-2) ], null, true, attributes); }; PHP.Parser.prototype.yyn366 = function ( attributes ) { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn367 = function ( attributes ) { this.yyastk[ this.stackPos-(2-1) ].push( this.yyastk[ this.stackPos-(2-2) ] ); this.yyval = this.yyastk[ this.stackPos-(2-1) ]; }; PHP.Parser.prototype.yyn368 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(1-1) ]]; }; PHP.Parser.prototype.yyn369 = function ( attributes ) { this.yyval = [this.yyastk[ this.stackPos-(2-1) ], this.yyastk[ this.stackPos-(2-2) ]]; }; PHP.Parser.prototype.yyn370 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(1-1) ].substring( 1 ), attributes); }; PHP.Parser.prototype.yyn371 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.Node_Expr_Variable(this.yyastk[ this.stackPos-(4-1) ].substring( 1 ), attributes), this.yyastk[ this.stackPos-(4-3) ], attributes); }; PHP.Parser.prototype.yyn372 = function ( attributes ) { this.yyval = this.Node_Expr_PropertyFetch(this.Node_Expr_Variable(this.yyastk[ this.stackPos-(3-1) ].substring( 1 ), attributes), this.yyastk[ this.stackPos-(3-3) ], attributes); }; PHP.Parser.prototype.yyn373 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn374 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(3-2) ], attributes); }; PHP.Parser.prototype.yyn375 = function ( attributes ) { this.yyval = this.Node_Expr_ArrayDimFetch(this.Node_Expr_Variable(this.yyastk[ this.stackPos-(6-2) ], attributes), this.yyastk[ this.stackPos-(6-4) ], attributes); }; PHP.Parser.prototype.yyn376 = function ( attributes ) { this.yyval = this.yyastk[ this.stackPos-(3-2) ]; }; PHP.Parser.prototype.yyn377 = function ( attributes ) { this.yyval = this.Node_Scalar_String(this.yyastk[ this.stackPos-(1-1) ], attributes); }; PHP.Parser.prototype.yyn378 = function ( attributes ) { this.yyval = this.Node_Scalar_String(this.yyastk[ this.stackPos-(1-1) ], attributes); }; PHP.Parser.prototype.yyn379 = function ( attributes ) { this.yyval = this.Node_Expr_Variable(this.yyastk[ this.stackPos-(1-1) ].substring( 1 ), attributes); }; PHP.Parser.prototype.Stmt_Namespace_postprocess = function( a ) { return a; }; PHP.Parser.prototype.Node_Stmt_Echo = function() { return { type: "Node_Stmt_Echo", exprs: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_If = function() { return { type: "Node_Stmt_If", cond: arguments[ 0 ], stmts: arguments[ 1 ].stmts, elseifs: arguments[ 1 ].elseifs, Else: arguments[ 1 ].Else || null, attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_For = function() { return { type: "Node_Stmt_For", init: arguments[ 0 ].init, cond: arguments[ 0 ].cond, loop: arguments[ 0 ].loop, stmts: arguments[ 0 ].stmts, attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_Function = function() { return { type: "Node_Stmt_Function", name: arguments[ 0 ], byRef: arguments[ 1 ].byRef, params: arguments[ 1 ].params, stmts: arguments[ 1 ].stmts, attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Stmt_Class_verifyModifier = function() { }; PHP.Parser.prototype.Node_Stmt_Namespace = function() { return { type: "Node_Stmt_Namespace", name: arguments[ 0 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Use = function() { return { type: "Node_Stmt_Use", name: arguments[ 0 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_UseUse = function() { return { type: "Node_Stmt_UseUse", name: arguments[ 0 ], as: arguments[1], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_TraitUseAdaptation_Precedence = function() { return { type: "Node_Stmt_TraitUseAdaptation_Precedence", name: arguments[ 0 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_TraitUseAdaptation_Alias = function() { return { type: "Node_Stmt_TraitUseAdaptation_Alias", name: arguments[ 0 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Trait = function() { return { type: "Node_Stmt_Trait", name: arguments[ 0 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_TraitUse = function() { return { type: "Node_Stmt_TraitUse", name: arguments[ 0 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Class = function() { return { type: "Node_Stmt_Class", name: arguments[ 0 ], Type: arguments[ 1 ].type, Extends: arguments[ 1 ].Extends, Implements: arguments[ 1 ].Implements, stmts: arguments[ 1 ].stmts, attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_ClassMethod = function() { return { type: "Node_Stmt_ClassMethod", name: arguments[ 0 ], Type: arguments[ 1 ].type, byRef: arguments[ 1 ].byRef, params: arguments[ 1 ].params, stmts: arguments[ 1 ].stmts, attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_ClassConst = function() { return { type: "Node_Stmt_ClassConst", consts: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_Interface = function() { return { type: "Node_Stmt_Interface", name: arguments[ 0 ], Extends: arguments[ 1 ].Extends, stmts: arguments[ 1 ].stmts, attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Throw = function() { return { type: "Node_Stmt_Throw", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_Catch = function() { return { type: "Node_Stmt_Catch", Type: arguments[ 0 ], variable: arguments[ 1 ], stmts: arguments[ 2 ], attributes: arguments[ 3 ] }; }; PHP.Parser.prototype.Node_Stmt_TryCatch = function() { return { type: "Node_Stmt_TryCatch", stmts: arguments[ 0 ], catches: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Foreach = function() { return { type: "Node_Stmt_Foreach", expr: arguments[ 0 ], valueVar: arguments[ 1 ], keyVar: arguments[ 2 ].keyVar, byRef: arguments[ 2 ].byRef, stmts: arguments[ 2 ].stmts, attributes: arguments[ 3 ] }; }; PHP.Parser.prototype.Node_Stmt_While = function() { return { type: "Node_Stmt_While", cond: arguments[ 0 ], stmts: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Do = function() { return { type: "Node_Stmt_Do", cond: arguments[ 0 ], stmts: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Break = function() { return { type: "Node_Stmt_Break", num: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_Continue = function() { return { type: "Node_Stmt_Continue", num: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_Return = function() { return { type: "Node_Stmt_Return", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_Case = function() { return { type: "Node_Stmt_Case", cond: arguments[ 0 ], stmts: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Switch = function() { return { type: "Node_Stmt_Switch", cond: arguments[ 0 ], cases: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Else = function() { return { type: "Node_Stmt_Else", stmts: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_ElseIf = function() { return { type: "Node_Stmt_ElseIf", cond: arguments[ 0 ], stmts: arguments[ 1 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_InlineHTML = function() { return { type: "Node_Stmt_InlineHTML", value: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_StaticVar = function() { return { type: "Node_Stmt_StaticVar", name: arguments[ 0 ], def: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Static = function() { return { type: "Node_Stmt_Static", vars: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_Global = function() { return { type: "Node_Stmt_Global", vars: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Stmt_PropertyProperty = function() { return { type: "Node_Stmt_PropertyProperty", name: arguments[ 0 ], def: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Property = function() { return { type: "Node_Stmt_Property", Type: arguments[ 0 ], props: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Stmt_Unset = function() { return { type: "Node_Stmt_Unset", variables: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Variable = function( a ) { return { type: "Node_Expr_Variable", name: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_FuncCall = function() { return { type: "Node_Expr_FuncCall", func: arguments[ 0 ], args: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_MethodCall = function() { return { type: "Node_Expr_MethodCall", variable: arguments[ 0 ], name: arguments[ 1 ], args: arguments[ 2 ], attributes: arguments[ 3 ] }; }; PHP.Parser.prototype.Node_Expr_StaticCall = function() { return { type: "Node_Expr_StaticCall", Class: arguments[ 0 ], func: arguments[ 1 ], args: arguments[ 2 ], attributes: arguments[ 3 ] }; }; PHP.Parser.prototype.Node_Expr_Ternary = function() { return { type: "Node_Expr_Ternary", cond: arguments[ 0 ], If: arguments[ 1 ], Else: arguments[ 2 ], attributes: arguments[ 3 ] }; }; PHP.Parser.prototype.Node_Expr_AssignList = function() { return { type: "Node_Expr_AssignList", assignList: arguments[ 0 ], expr: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Assign = function() { return { type: "Node_Expr_Assign", variable: arguments[ 0 ], expr: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_AssignConcat = function() { return { type: "Node_Expr_AssignConcat", variable: arguments[ 0 ], expr: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_AssignMinus = function() { return { type: "Node_Expr_AssignMinus", variable: arguments[ 0 ], expr: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_AssignPlus = function() { return { type: "Node_Expr_AssignPlus", variable: arguments[ 0 ], expr: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_AssignDiv = function() { return { type: "Node_Expr_AssignDiv", variable: arguments[ 0 ], expr: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_AssignRef = function() { return { type: "Node_Expr_AssignRef", variable: arguments[ 0 ], refVar: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_AssignMul = function() { return { type: "Node_Expr_AssignMul", variable: arguments[ 0 ], expr: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_AssignMod = function() { return { type: "Node_Expr_AssignMod", variable: arguments[ 0 ], expr: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Plus = function() { return { type: "Node_Expr_Plus", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Minus = function() { return { type: "Node_Expr_Minus", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Mul = function() { return { type: "Node_Expr_Mul", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Div = function() { return { type: "Node_Expr_Div", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Mod = function() { return { type: "Node_Expr_Mod", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Greater = function() { return { type: "Node_Expr_Greater", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Equal = function() { return { type: "Node_Expr_Equal", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_NotEqual = function() { return { type: "Node_Expr_NotEqual", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Identical = function() { return { type: "Node_Expr_Identical", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_NotIdentical = function() { return { type: "Node_Expr_NotIdentical", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_GreaterOrEqual = function() { return { type: "Node_Expr_GreaterOrEqual", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_SmallerOrEqual = function() { return { type: "Node_Expr_SmallerOrEqual", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Concat = function() { return { type: "Node_Expr_Concat", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Smaller = function() { return { type: "Node_Expr_Smaller", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_PostInc = function() { return { type: "Node_Expr_PostInc", variable: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_PostDec = function() { return { type: "Node_Expr_PostDec", variable: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_PreInc = function() { return { type: "Node_Expr_PreInc", variable: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_PreDec = function() { return { type: "Node_Expr_PreDec", variable: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Include = function() { return { expr: arguments[ 0 ], type: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_ArrayDimFetch = function() { return { type: "Node_Expr_ArrayDimFetch", variable: arguments[ 0 ], dim: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_StaticPropertyFetch = function() { return { type: "Node_Expr_StaticPropertyFetch", Class: arguments[ 0 ], name: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_ClassConstFetch = function() { return { type: "Node_Expr_ClassConstFetch", Class: arguments[ 0 ], name: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_StaticPropertyFetch = function() { return { type: "Node_Expr_StaticPropertyFetch", Class: arguments[ 0 ], name: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_ConstFetch = function() { return { type: "Node_Expr_ConstFetch", name: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_ArrayItem = function() { return { type: "Node_Expr_ArrayItem", value: arguments[ 0 ], key: arguments[ 1 ], byRef: arguments[ 2 ], attributes: arguments[ 3 ] }; }; PHP.Parser.prototype.Node_Expr_Array = function() { return { type: "Node_Expr_Array", items: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_PropertyFetch = function() { return { type: "Node_Expr_PropertyFetch", variable: arguments[ 0 ], name: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_New = function() { return { type: "Node_Expr_New", Class: arguments[ 0 ], args: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Print = function() { return { type: "Node_Expr_Print", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Exit = function() { return { type: "Node_Expr_Exit", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Cast_Bool = function() { return { type: "Node_Expr_Cast_Bool", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Cast_Int = function() { return { type: "Node_Expr_Cast_Int", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Cast_String = function() { return { type: "Node_Expr_Cast_String", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Cast_Double = function() { return { type: "Node_Expr_Cast_Double", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Cast_Array = function() { return { type: "Node_Expr_Cast_Array", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Cast_Object = function() { return { type: "Node_Expr_Cast_Object", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_ErrorSuppress = function() { return { type: "Node_Expr_ErrorSuppress", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Isset = function() { return { type: "Node_Expr_Isset", variables: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_UnaryMinus = function() { return { type: "Node_Expr_UnaryMinus", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_UnaryPlus = function() { return { type: "Node_Expr_UnaryPlus", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_Empty = function() { return { type: "Node_Expr_Empty", variable: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_BooleanOr = function() { return { type: "Node_Expr_BooleanOr", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_LogicalOr = function() { return { type: "Node_Expr_LogicalOr", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_LogicalAnd = function() { return { type: "Node_Expr_LogicalAnd", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_LogicalXor = function() { return { type: "Node_Expr_LogicalXor", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_BitwiseAnd = function() { return { type: "Node_Expr_BitwiseAnd", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_BitwiseOr = function() { return { type: "Node_Expr_BitwiseOr", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_BitwiseXor = function() { return { type: "Node_Expr_BitwiseXor", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_BitwiseNot = function() { return { type: "Node_Expr_BitwiseNot", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_BooleanNot = function() { return { type: "Node_Expr_BooleanNot", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Expr_BooleanAnd = function() { return { type: "Node_Expr_BooleanAnd", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Instanceof = function() { return { type: "Node_Expr_Instanceof", left: arguments[ 0 ], right: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Expr_Clone = function() { return { type: "Node_Expr_Clone", expr: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Scalar_LNumber_parse = function( a ) { return a; }; PHP.Parser.prototype.Scalar_DNumber_parse = function( a ) { return a; }; PHP.Parser.prototype.Scalar_String_parseDocString = function() { return '"' + arguments[ 1 ].replace(/([^"\\]*(?:\\.[^"\\]*)*)"/g, '$1\\"') + '"'; }; PHP.Parser.prototype.Node_Scalar_String = function( ) { return { type: "Node_Scalar_String", value: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Scalar_String_create = function( ) { return { type: "Node_Scalar_String", value: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Scalar_LNumber = function() { return { type: "Node_Scalar_LNumber", value: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Scalar_DNumber = function() { return { type: "Node_Scalar_DNumber", value: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Scalar_Encapsed = function() { return { type: "Node_Scalar_Encapsed", parts: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Name = function() { return { type: "Node_Name", parts: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Name_FullyQualified = function() { return { type: "Node_Name_FullyQualified", parts: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Name_Relative = function() { return { type: "Node_Name_Relative", parts: arguments[ 0 ], attributes: arguments[ 1 ] }; }; PHP.Parser.prototype.Node_Param = function() { return { type: "Node_Param", name: arguments[ 0 ], def: arguments[ 1 ], Type: arguments[ 2 ], byRef: arguments[ 3 ], attributes: arguments[ 4 ] }; }; PHP.Parser.prototype.Node_Arg = function() { return { type: "Node_Name", value: arguments[ 0 ], byRef: arguments[ 1 ], attributes: arguments[ 2 ] }; }; PHP.Parser.prototype.Node_Const = function() { return { type: "Node_Const", name: arguments[ 0 ], value: arguments[ 1 ], attributes: arguments[ 2 ] }; }; exports.PHP = PHP; }); ace.define("ace/mode/php_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/php/php"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var PHP = require("./php/php").PHP; var PhpWorker = exports.PhpWorker = function(sender) { Mirror.call(this, sender); this.setTimeout(500); }; oop.inherits(PhpWorker, Mirror); (function() { this.setOptions = function(opts) { this.inlinePhp = opts && opts.inline; }; this.onUpdate = function() { var value = this.doc.getValue(); var errors = []; if (this.inlinePhp) value = "<?" + value + "?>"; var tokens = PHP.Lexer(value, {short_open_tag: 1}); try { new PHP.Parser(tokens); } catch(e) { errors.push({ row: e.line - 1, column: null, text: e.message.charAt(0).toUpperCase() + e.message.substring(1), type: "error" }); } this.sender.emit("annotate", errors); }; }).call(PhpWorker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/mode-luapage.js
2,924
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|async|await|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode "[0-2][0-7]{0,2}|" + // oct "3[0-7][0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ DocCommentHighlightRules.getStartRule("doc-start"), comments("no_regex"), { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "punctuation.operator", regex : /[.](?![.])/, next : "property" }, { token : "keyword.operator", regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], property: [{ token : "text", regex : "\\s+" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", next: "function_arguments" }, { token : "punctuation.operator", regex : /[.](?![.])/ }, { token : "support.function", regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : "support.function.dom", regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : "support.constant", regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : "identifier", regex : identifierRe }, { regex: "", token: "empty", next: "no_regex" } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("start"), { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); } else if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); if (!options || options.jsx != false) JSX.call(this); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); function JSX() { var tagRegex = identifierRe.replace("\\d", "\\d\\-"); var jsxTag = { onMatch : function(val, state, stack) { var offset = val.charAt(1) == "/" ? 2 : 1; if (offset == 1) { if (state != this.nextState) stack.unshift(this.next, this.nextState, 0); else stack.unshift(this.next); stack[2]++; } else if (offset == 2) { if (state == this.nextState) { stack[1]--; if (!stack[1] || stack[1] < 0) { stack.shift(); stack.shift(); } } } return [{ type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", value: val.slice(0, offset) }, { type: "meta.tag.tag-name.xml", value: val.substr(offset) }]; }, regex : "</?" + tagRegex + "", next: "jsxAttributes", nextState: "jsx" }; this.$rules.start.unshift(jsxTag); var jsxJsRule = { regex: "{", token: "paren.quasi.start", push: "start" }; this.$rules.jsx = [ jsxJsRule, jsxTag, {include : "reference"}, {defaultToken: "string"} ]; this.$rules.jsxAttributes = [{ token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", onMatch : function(value, currentState, stack) { if (currentState == stack[0]) stack.shift(); if (value.length == 2) { if (stack[0] == this.nextState) stack[1]--; if (!stack[1] || stack[1] < 0) { stack.splice(0, 2); } } this.next = stack[0] || "start"; return [{type: this.token, value: value}]; }, nextState: "jsx" }, jsxJsRule, comments("jsxAttributes"), { token : "entity.other.attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { token : "text.tag-whitespace.xml", regex : "\\s+" }, { token : "string.attribute-value.xml", regex : "'", stateName : "jsx_attr_q", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', stateName : "jsx_attr_qq", push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, jsxTag ]; this.$rules.reference = [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }]; } function comments(next) { return [ { token : "comment", // multi line comment regex : /\/\*/, next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] }, { token : "comment", regex : "\\/\\/", next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] } ]; } exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/css_completions",["require","exports","module"], function(require, exports, module) { "use strict"; var propertyMap = { "background": {"#$0": 1}, "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, "background-image": {"url('/$0')": 1}, "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, "background-attachment": {"scroll": 1, "fixed": 1}, "background-size": {"cover": 1, "contain": 1}, "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, "border-color": {"#$0": 1}, "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, "border-collapse": {"collapse": 1, "separate": 1}, "bottom": {"px": 1, "em": 1, "%": 1}, "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, "empty-cells": {"show": 1, "hide": 1}, "float": {"left": 1, "right": 1, "none": 1}, "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, "font-size": {"px": 1, "em": 1, "%": 1}, "font-weight": {"bold": 1, "normal": 1}, "font-style": {"italic": 1, "normal": 1}, "font-variant": {"normal": 1, "small-caps": 1}, "height": {"px": 1, "em": 1, "%": 1}, "left": {"px": 1, "em": 1, "%": 1}, "letter-spacing": {"normal": 1}, "line-height": {"normal": 1}, "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, "margin": {"px": 1, "em": 1, "%": 1}, "margin-right": {"px": 1, "em": 1, "%": 1}, "margin-left": {"px": 1, "em": 1, "%": 1}, "margin-top": {"px": 1, "em": 1, "%": 1}, "margin-bottom": {"px": 1, "em": 1, "%": 1}, "max-height": {"px": 1, "em": 1, "%": 1}, "max-width": {"px": 1, "em": 1, "%": 1}, "min-height": {"px": 1, "em": 1, "%": 1}, "min-width": {"px": 1, "em": 1, "%": 1}, "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "padding": {"px": 1, "em": 1, "%": 1}, "padding-top": {"px": 1, "em": 1, "%": 1}, "padding-right": {"px": 1, "em": 1, "%": 1}, "padding-bottom": {"px": 1, "em": 1, "%": 1}, "padding-left": {"px": 1, "em": 1, "%": 1}, "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, "right": {"px": 1, "em": 1, "%": 1}, "table-layout": {"fixed": 1, "auto": 1}, "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, "top": {"px": 1, "em": 1, "%": 1}, "vertical-align": {"top": 1, "bottom": 1}, "visibility": {"hidden": 1, "visible": 1}, "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, "width": {"px": 1, "em": 1, "%": 1}, "word-spacing": {"normal": 1}, "filter": {"alpha(opacity=$0100)": 1}, "text-shadow": {"$02px 2px 2px #777": 1}, "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, "-moz-border-radius": 1, "-moz-border-radius-topright": 1, "-moz-border-radius-bottomright": 1, "-moz-border-radius-topleft": 1, "-moz-border-radius-bottomleft": 1, "-webkit-border-radius": 1, "-webkit-border-top-right-radius": 1, "-webkit-border-top-left-radius": 1, "-webkit-border-bottom-right-radius": 1, "-webkit-border-bottom-left-radius": 1, "-moz-box-shadow": 1, "-webkit-box-shadow": 1, "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } }; var CssCompletions = function() { }; (function() { this.completionsDefined = false; this.defineCompletions = function() { if (document) { var style = document.createElement('c').style; for (var i in style) { if (typeof style[i] !== 'string') continue; var name = i.replace(/[A-Z]/g, function(x) { return '-' + x.toLowerCase(); }); if (!propertyMap.hasOwnProperty(name)) propertyMap[name] = 1; } } this.completionsDefined = true; } this.getCompletions = function(state, session, pos, prefix) { if (!this.completionsDefined) { this.defineCompletions(); } var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (state==='ruleset'){ var line = session.getLine(pos.row).substr(0, pos.column); if (/:[^;]+$/.test(line)) { /([\w\-]+):[^:]*$/.test(line); return this.getPropertyValueCompletions(state, session, pos, prefix); } else { return this.getPropertyCompletions(state, session, pos, prefix); } } return []; }; this.getPropertyCompletions = function(state, session, pos, prefix) { var properties = Object.keys(propertyMap); return properties.map(function(property){ return { caption: property, snippet: property + ': $0', meta: "property", score: Number.MAX_VALUE }; }); }; this.getPropertyValueCompletions = function(state, session, pos, prefix) { var line = session.getLine(pos.row).substr(0, pos.column); var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; if (!property) return []; var values = []; if (property in propertyMap && typeof propertyMap[property] === "object") { values = Object.keys(propertyMap[property]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "property value", score: Number.MAX_VALUE }; }); }; }).call(CssCompletions.prototype); exports.CssCompletions = CssCompletions; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssCompletions = require("./css_completions").CssCompletions; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.$completer = new CssCompletions(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": {"manifest": 1}, "head": {}, "title": {}, "base": {"href": 1, "target": 1}, "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, "noscript": {"href": 1}, "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, "section": {}, "nav": {}, "article": {"pubdate": 1}, "aside": {}, "h1": {}, "h2": {}, "h3": {}, "h4": {}, "h5": {}, "h6": {}, "header": {}, "footer": {}, "address": {}, "main": {}, "p": {}, "hr": {}, "pre": {}, "blockquote": {"cite": 1}, "ol": {"start": 1, "reversed": 1}, "ul": {}, "li": {"value": 1}, "dl": {}, "dt": {}, "dd": {}, "figure": {}, "figcaption": {}, "div": {}, "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, "em": {}, "strong": {}, "small": {}, "s": {}, "cite": {}, "q": {"cite": 1}, "dfn": {}, "abbr": {}, "data": {}, "time": {"datetime": 1}, "code": {}, "var": {}, "samp": {}, "kbd": {}, "sub": {}, "sup": {}, "i": {}, "b": {}, "u": {}, "mark": {}, "ruby": {}, "rt": {}, "rp": {}, "bdi": {}, "bdo": {}, "span": {}, "br": {}, "wbr": {}, "ins": {"cite": 1, "datetime": 1}, "del": {"cite": 1, "datetime": 1}, "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, "param": {"name": 1, "value": 1}, "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, "source": {"src": 1, "type": 1, "media": 1}, "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, "canvas": {"width": 1, "height": 1}, "map": {"name": 1}, "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, "svg": {}, "math": {}, "table": {"summary": 1}, "caption": {}, "colgroup": {"span": 1}, "col": {"span": 1}, "tbody": {}, "thead": {}, "tfoot": {}, "tr": {}, "td": {"headers": 1, "rowspan": 1, "colspan": 1}, "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, "fieldset": {"disabled": 1, "form": 1, "name": 1}, "legend": {}, "label": {"form": 1, "for": 1}, "input": { "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, "datalist": {}, "optgroup": {"disabled": 1, "label": 1}, "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, "output": {"for": 1, "form": 1, "name": 1}, "progress": {"value": 1, "max": 1}, "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, "details": {"open": 1}, "summary": {}, "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, "menu": {"type": 1, "label": 1}, "dialog": {"open": 1} }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } function findAttributeName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "attribute-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompletions(state, session, pos, prefix); if (is(token, "attribute-value")) return this.getAttributeValueCompletions(state, session, pos, prefix); var line = session.getLine(pos.row).substr(0, pos.column); if (/&[A-z]*$/i.test(line)) return this.getHTMLEntityCompletions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(Object.keys(attributeMap[tagName])); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; this.getAttributeValueCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); var attributeName = findAttributeName(session, pos); if (!tagName) return []; var values = []; if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { values = Object.keys(attributeMap[tagName][attributeName]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "attribute value", score: Number.MAX_VALUE }; }); }; this.getHTMLEntityCompletions = function(state, session, pos, prefix) { var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; return values.map(function(value){ return { caption: value, snippet: value, meta: "html entity", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/lua_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LuaHighlightRules = function() { var keywords = ( "break|do|else|elseif|end|for|function|if|in|local|repeat|"+ "return|then|until|while|or|and|not" ); var builtinConstants = ("true|false|nil|_G|_VERSION"); var functions = ( "string|xpcall|package|tostring|print|os|unpack|require|"+ "getfenv|setmetatable|next|assert|tonumber|io|rawequal|"+ "collectgarbage|getmetatable|module|rawset|math|debug|"+ "pcall|table|newproxy|type|coroutine|_G|select|gcinfo|"+ "pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|"+ "load|error|loadfile|"+ "sub|upper|len|gfind|rep|find|match|char|dump|gmatch|"+ "reverse|byte|format|gsub|lower|preload|loadlib|loaded|"+ "loaders|cpath|config|path|seeall|exit|setlocale|date|"+ "getenv|difftime|remove|time|clock|tmpname|rename|execute|"+ "lines|write|close|flush|open|output|type|read|stderr|"+ "stdin|input|stdout|popen|tmpfile|log|max|acos|huge|"+ "ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|"+ "frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|"+ "atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|"+ "gethook|setmetatable|setlocal|traceback|setfenv|getinfo|"+ "setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|"+ "foreachi|maxn|foreach|concat|sort|remove|resume|yield|"+ "status|wrap|create|running|"+ "__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|"+ "__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber" ); var stdLibaries = ("string|package|os|io|math|debug|table|coroutine"); var deprecatedIn5152 = ("setn|foreach|foreachi|gcinfo|log10|maxn"); var keywordMapper = this.createKeywordMapper({ "keyword": keywords, "support.function": functions, "keyword.deprecated": deprecatedIn5152, "constant.library": stdLibaries, "constant.language": builtinConstants, "variable.language": "self" }, "identifier"); var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var integer = "(?:" + decimalInteger + "|" + hexInteger + ")"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var floatNumber = "(?:" + pointFloat + ")"; this.$rules = { "start" : [{ stateName: "bracketedComment", onMatch : function(value, currentState, stack){ stack.unshift(this.next, value.length - 2, currentState); return "comment"; }, regex : /\-\-\[=*\[/, next : [ { onMatch : function(value, currentState, stack) { if (value.length == stack[1]) { stack.shift(); stack.shift(); this.next = stack.shift(); } else { this.next = ""; } return "comment"; }, regex : /\]=*\]/, next : "start" }, { defaultToken : "comment" } ] }, { token : "comment", regex : "\\-\\-.*$" }, { stateName: "bracketedString", onMatch : function(value, currentState, stack){ stack.unshift(this.next, value.length, currentState); return "comment"; }, regex : /\[=*\[/, next : [ { onMatch : function(value, currentState, stack) { if (value.length == stack[1]) { stack.shift(); stack.shift(); this.next = stack.shift(); } else { this.next = ""; } return "comment"; }, regex : /\]=*\]/, next : "start" }, { defaultToken : "comment" } ] }, { token : "string", // " string regex : '"(?:[^\\\\]|\\\\.)*?"' }, { token : "string", // ' string regex : "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\*|\\/|%|\\#|\\^|~|<|>|<=|=>|==|~=|=|\\:|\\.\\.\\.|\\.\\." }, { token : "paren.lparen", regex : "[\\[\\(\\{]" }, { token : "paren.rparen", regex : "[\\]\\)\\}]" }, { token : "text", regex : "\\s+|\\w+" } ] }; this.normalizeRules(); } oop.inherits(LuaHighlightRules, TextHighlightRules); exports.LuaHighlightRules = LuaHighlightRules; }); ace.define("ace/mode/folding/lua",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /\b(function|then|do|repeat)\b|{\s*$|(\[=*\[)/; this.foldingStopMarker = /\bend\b|^\s*}|\]=*\]/; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var isStart = this.foldingStartMarker.test(line); var isEnd = this.foldingStopMarker.test(line); if (isStart && !isEnd) { var match = line.match(this.foldingStartMarker); if (match[1] == "then" && /\belseif\b/.test(line)) return; if (match[1]) { if (session.getTokenAt(row, match.index + 1).type === "keyword") return "start"; } else if (match[2]) { var type = session.bgTokenizer.getState(row) || ""; if (type[0] == "bracketedComment" || type[0] == "bracketedString") return "start"; } else { return "start"; } } if (foldStyle != "markbeginend" || !isEnd || isStart && isEnd) return ""; var match = line.match(this.foldingStopMarker); if (match[0] === "end") { if (session.getTokenAt(row, match.index + 1).type === "keyword") return "end"; } else if (match[0][0] === "]") { var type = session.bgTokenizer.getState(row - 1) || ""; if (type[0] == "bracketedComment" || type[0] == "bracketedString") return "end"; } else return "end"; }; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.doc.getLine(row); var match = this.foldingStartMarker.exec(line); if (match) { if (match[1]) return this.luaBlock(session, row, match.index + 1); if (match[2]) return session.getCommentFoldRange(row, match.index + 1); return this.openingBracketBlock(session, "{", row, match.index); } var match = this.foldingStopMarker.exec(line); if (match) { if (match[0] === "end") { if (session.getTokenAt(row, match.index + 1).type === "keyword") return this.luaBlock(session, row, match.index + 1); } if (match[0][0] === "]") return session.getCommentFoldRange(row, match.index + 1); return this.closingBracketBlock(session, "}", row, match.index + match[0].length); } }; this.luaBlock = function(session, row, column) { var stream = new TokenIterator(session, row, column); var indentKeywords = { "function": 1, "do": 1, "then": 1, "elseif": -1, "end": -1, "repeat": 1, "until": -1 }; var token = stream.getCurrentToken(); if (!token || token.type != "keyword") return; var val = token.value; var stack = [val]; var dir = indentKeywords[val]; if (!dir) return; var startColumn = dir === -1 ? stream.getCurrentTokenColumn() : session.getLine(row).length; var startRow = row; stream.step = dir === -1 ? stream.stepBackward : stream.stepForward; while(token = stream.step()) { if (token.type !== "keyword") continue; var level = dir * indentKeywords[token.value]; if (level > 0) { stack.unshift(token.value); } else if (level <= 0) { stack.shift(); if (!stack.length && token.value != "elseif") break; if (level === 0) stack.unshift(token.value); } } var row = stream.getCurrentTokenRow(); if (dir === -1) return new Range(row, session.getLine(row).length, startRow, startColumn); else return new Range(startRow, startColumn, row, stream.getCurrentTokenColumn()); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/lua",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/lua_highlight_rules","ace/mode/folding/lua","ace/range","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules; var LuaFoldMode = require("./folding/lua").FoldMode; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.HighlightRules = LuaHighlightRules; this.foldingRules = new LuaFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "--"; this.blockComment = {start: "--[", end: "]--"}; var indentKeywords = { "function": 1, "then": 1, "do": 1, "else": 1, "elseif": 1, "repeat": 1, "end": -1, "until": -1 }; var outdentKeywords = [ "else", "elseif", "end", "until" ]; function getNetIndentLevel(tokens) { var level = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type == "keyword") { if (token.value in indentKeywords) { level += indentKeywords[token.value]; } } else if (token.type == "paren.lparen") { level += token.value.length; } else if (token.type == "paren.rparen") { level -= token.value.length; } } if (level < 0) { return -1; } else if (level > 0) { return 1; } else { return 0; } } this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var level = 0; var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (state == "start") { level = getNetIndentLevel(tokens); } if (level > 0) { return indent + tab; } else if (level < 0 && indent.substr(indent.length - tab.length) == tab) { if (!this.checkOutdent(state, line, "\n")) { return indent.substr(0, indent.length - tab.length); } } return indent; }; this.checkOutdent = function(state, line, input) { if (input != "\n" && input != "\r" && input != "\r\n") return false; if (line.match(/^\s*[\)\}\]]$/)) return true; var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens; if (!tokens || !tokens.length) return false; return (tokens[0].type == "keyword" && outdentKeywords.indexOf(tokens[0].value) != -1); }; this.autoOutdent = function(state, session, row) { var prevLine = session.getLine(row - 1); var prevIndent = this.$getIndent(prevLine).length; var prevTokens = this.getTokenizer().getLineTokens(prevLine, "start").tokens; var tabLength = session.getTabString().length; var expectedIndent = prevIndent + tabLength * getNetIndentLevel(prevTokens); var curIndent = this.$getIndent(session.getLine(row)).length; if (curIndent < expectedIndent) { return; } session.outdentRows(new Range(row, 0, row + 2, 0)); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/lua_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/lua"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/luapage_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/html_highlight_rules","ace/mode/lua_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules; var LuaPageHighlightRules = function() { HtmlHighlightRules.call(this); var startRules = [ { token: "keyword", regex: "<\\%\\=?", push: "lua-start" }, { token: "keyword", regex: "<\\?lua\\=?", push: "lua-start" } ]; var endRules = [ { token: "keyword", regex: "\\%>", next: "pop" }, { token: "keyword", regex: "\\?>", next: "pop" } ]; this.embedRules(LuaHighlightRules, "lua-", endRules, ["start"]); for (var key in this.$rules) this.$rules[key].unshift.apply(this.$rules[key], startRules); this.normalizeRules(); }; oop.inherits(LuaPageHighlightRules, HtmlHighlightRules); exports.LuaPageHighlightRules = LuaPageHighlightRules; }); ace.define("ace/mode/luapage",["require","exports","module","ace/lib/oop","ace/mode/html","ace/mode/lua","ace/mode/luapage_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlMode = require("./html").Mode; var LuaMode = require("./lua").Mode; var LuaPageHighlightRules = require("./luapage_highlight_rules").LuaPageHighlightRules; var Mode = function() { HtmlMode.call(this); this.HighlightRules = LuaPageHighlightRules; this.createModeDelegates({ "lua-": LuaMode }); }; oop.inherits(Mode, HtmlMode); (function() { this.$id = "ace/mode/luapage"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/worker-latex.js
3,204
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; if (!window.console) { window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; } window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); } } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!(range instanceof Range)) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject(array[i]); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } if (Object.prototype.toString.call(obj) !== "[object Object]") return obj; copy = {}; for (var key in obj) copy[key] = deepCopy(obj[key]); return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/latex_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var LatexWorker = exports.LatexWorker = function(sender) { Mirror.call(this, sender); this.setTimeout(250); }; oop.inherits(LatexWorker, Mirror); var Tokenise = function (text) { var Tokens = []; var Comments = []; var pos = -1; var SPECIAL = /[\\\{\}\$\&\#\^\_\~\%]/g; // match TeX special characters var NEXTCS = /[^a-zA-Z]/g; // match characters which aren't part of a TeX control sequence var idx = 0; var lineNumber = 0; // current line number when parsing tokens (zero-based) var linePosition = []; // mapping from line number to absolute offset of line in text[] linePosition[0] = 0; var checkingDisabled = false; var count = 0; // number of tokens parses var MAX_TOKENS = 100000; while (true) { count++; if (count > MAX_TOKENS) { throw new Error("exceed max token count of " + MAX_TOKENS); break; }; var result = SPECIAL.exec(text); if (result == null) { if (idx < text.length) { Tokens.push([lineNumber, "Text", idx, text.length]); } break; } if (result && result.index <= pos) { throw new Error("infinite loop in parsing"); break; }; pos = result.index; if (pos > idx) { Tokens.push([lineNumber, "Text", idx, pos]); } for (var i = idx; i < pos; i++) { if (text[i] === "\n") { lineNumber++; linePosition[lineNumber] = i+1; } } var newIdx = SPECIAL.lastIndex; idx = newIdx; var code = result[0]; if (code === "%") { // comment character var newLinePos = text.indexOf("\n", idx); if (newLinePos === -1) { newLinePos = text.length; }; var commentString = text.substring(idx, newLinePos); if (commentString.indexOf("%novalidate") === 0) { return []; } else if(!checkingDisabled && commentString.indexOf("%begin novalidate") === 0) { checkingDisabled = true; } else if (checkingDisabled && commentString.indexOf("%end novalidate") === 0) { checkingDisabled = false; }; idx = SPECIAL.lastIndex = newLinePos + 1; Comments.push([lineNumber, idx, newLinePos]); lineNumber++; linePosition[lineNumber] = idx; } else if (checkingDisabled) { continue; } else if (code === '\\') { // escape character NEXTCS.lastIndex = idx; var controlSequence = NEXTCS.exec(text); var nextSpecialPos = controlSequence === null ? idx : controlSequence.index; if (nextSpecialPos === idx) { Tokens.push([lineNumber, code, pos, idx + 1, text[idx], "control-symbol"]); idx = SPECIAL.lastIndex = idx + 1; char = text[nextSpecialPos]; if (char === '\n') { lineNumber++; linePosition[lineNumber] = nextSpecialPos;}; } else { Tokens.push([lineNumber, code, pos, nextSpecialPos, text.slice(idx, nextSpecialPos)]); var char; while ((char = text[nextSpecialPos]) === ' ' || char === '\t' || char === '\r' || char === '\n') { nextSpecialPos++; if (char === '\n') { lineNumber++; linePosition[lineNumber] = nextSpecialPos;}; } idx = SPECIAL.lastIndex = nextSpecialPos; } } else if (code === "{") { // open group Tokens.push([lineNumber, code, pos]); } else if (code === "}") { // close group Tokens.push([lineNumber, code, pos]); } else if (code === "$") { // math mode Tokens.push([lineNumber, code, pos]); } else if (code === "&") { // tabalign Tokens.push([lineNumber, code, pos]); } else if (code === "#") { // macro parameter Tokens.push([lineNumber, code, pos]); } else if (code === "^") { // superscript Tokens.push([lineNumber, code, pos]); } else if (code === "_") { // subscript Tokens.push([lineNumber, code, pos]); } else if (code === "~") { // active character (space) Tokens.push([lineNumber, code, pos]); } else { throw "unrecognised character " + code; } } return {tokens: Tokens, comments: Comments, linePosition: linePosition, lineNumber: lineNumber, text: text}; }; var read1arg = function (TokeniseResult, k, options) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; if (options && options.allowStar) { var optional = Tokens[k+1]; if (optional && optional[1] === "Text") { var optionalstr = text.substring(optional[2], optional[3]); if (optionalstr === "*") { k++;} }; }; var open = Tokens[k+1]; var env = Tokens[k+2]; var close = Tokens[k+3]; var envName; if(open && open[1] === "\\") { envName = open[4]; // array element 4 is command sequence return k + 1; } else if(open && open[1] === "{" && env && env[1] === "\\" && close && close[1] === "}") { envName = env[4]; // NOTE: if we were actually using this, keep track of * above return k + 3; // array element 4 is command sequence } else { return null; } }; var readLetDefinition = function (TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var first = Tokens[k+1]; var second = Tokens[k+2]; var third = Tokens[k+3]; if(first && first[1] === "\\" && second && second[1] === "\\") { return k + 2; } else if(first && first[1] === "\\" && second && second[1] === "Text" && text.substring(second[2], second[3]) === "=" && third && third[1] === "\\") { return k + 3; } else { return null; } }; var read1name = function (TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var open = Tokens[k+1]; var env = Tokens[k+2]; var close = Tokens[k+3]; if(open && open[1] === "{" && env && env[1] === "Text" && close && close[1] === "}") { var envName = text.substring(env[2], env[3]); return k + 3; } else if (open && open[1] === "{" && env && env[1] === "Text") { envName = ""; for (var j = k + 2, tok; (tok = Tokens[j]); j++) { if (tok[1] === "Text") { var str = text.substring(tok[2], tok[3]); if (!str.match(/^\S*$/)) { break; } envName = envName + str; } else if (tok[1] === "_") { envName = envName + "_"; } else { break; } } if (tok && tok[1] === "}") { return j; // advance past these tokens } else { return null; } } else { return null; } }; var read1filename = function (TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var fileName = ""; for (var j = k + 1, tok; (tok = Tokens[j]); j++) { if (tok[1] === "Text") { var str = text.substring(tok[2], tok[3]); if (!str.match(/^\S*$/)) { break; } fileName = fileName + str; } else if (tok[1] === "_") { fileName = fileName + "_"; } else { break; } } if (fileName.length > 0) { return j; // advance past these tokens } else { return null; } }; var readOptionalParams = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var params = Tokens[k+1]; if(params && params[1] === "Text") { var paramNum = text.substring(params[2], params[3]); if (paramNum.match(/^\[\d+\](\[[^\]]*\])*\s*$/)) { return k + 1; // got it }; }; var count = 0; var nextToken = Tokens[k+1]; var pos = nextToken[2]; for (var i = pos, end = text.length; i < end; i++) { var char = text[i]; if (nextToken && i >= nextToken[2]) { k++; nextToken = Tokens[k+1];}; if (char === "[") { count++; } if (char === "]") { count--; } if (count === 0 && char === "{") { return k - 1; } if (count > 0 && (char === '\r' || char === '\n')) { return null; } }; return null; }; var readOptionalGeneric = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var params = Tokens[k+1]; if(params && params[1] === "Text") { var paramNum = text.substring(params[2], params[3]); if (paramNum.match(/^(\[[^\]]*\])+\s*$/)) { return k + 1; // got it }; }; return null; }; var readOptionalDef = function (TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var defToken = Tokens[k]; var pos = defToken[3]; var openBrace = "{"; var nextToken = Tokens[k+1]; for (var i = pos, end = text.length; i < end; i++) { var char = text[i]; if (nextToken && i >= nextToken[2]) { k++; nextToken = Tokens[k+1];}; if (char === openBrace) { return k - 1; }; // move back to the last token of the optional arguments if (char === '\r' || char === '\n') { return null; } }; return null; }; var readDefinition = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; k = k + 1; var count = 0; var nextToken = Tokens[k]; while (nextToken && nextToken[1] === "Text") { var start = nextToken[2], end = nextToken[3]; for (var i = start; i < end; i++) { var char = text[i]; if (char === ' ' || char === '\t' || char === '\r' || char === '\n') { continue; } return null; // bail out, should begin with a { } k++; nextToken = Tokens[k]; } if (nextToken && nextToken[1] === "{") { count++; while (count>0) { k++; nextToken = Tokens[k]; if(!nextToken) { break; }; if (nextToken[1] === "}") { count--; } if (nextToken[1] === "{") { count++; } } return k; } return null; }; var readVerb = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var verbToken = Tokens[k]; var verbStr = text.substring(verbToken[2], verbToken[3]); var pos = verbToken[3]; if (text[pos] === "*") { pos++; } // \verb* form of command var delimiter = text[pos]; pos++; var nextToken = Tokens[k+1]; for (var i = pos, end = text.length; i < end; i++) { var char = text[i]; if (nextToken && i >= nextToken[2]) { k++; nextToken = Tokens[k+1];}; if (char === delimiter) { return k; }; if (char === '\r' || char === '\n') { return null; } }; return null; }; var readUrl = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var urlToken = Tokens[k]; var urlStr = text.substring(urlToken[2], urlToken[3]); var pos = urlToken[3]; var openDelimiter = text[pos]; var closeDelimiter = (openDelimiter === "{") ? "}" : openDelimiter; var nextToken = Tokens[k+1]; if (nextToken && pos === nextToken[2]) { k++; nextToken = Tokens[k+1]; }; pos++; var count = 1; for (var i = pos, end = text.length; count > 0 && i < end; i++) { var char = text[i]; if (nextToken && i >= nextToken[2]) { k++; nextToken = Tokens[k+1];}; if (char === closeDelimiter) { count--; } else if (char === openDelimiter) { count++; }; if (count === 0) { return k; }; if (char === '\r' || char === '\n') { return null; } }; return null; }; var InterpretTokens = function (TokeniseResult, ErrorReporter) { var Tokens = TokeniseResult.tokens; var linePosition = TokeniseResult.linePosition; var lineNumber = TokeniseResult.lineNumber; var text = TokeniseResult.text; var TokenErrorFromTo = ErrorReporter.TokenErrorFromTo; var TokenError = ErrorReporter.TokenError; var Environments = new EnvHandler(ErrorReporter); var nextGroupMathMode = null; // if the next group should have var nextGroupMathModeStack = [] ; // tracking all nextGroupMathModes var seenUserDefinedBeginEquation = false; // if we have seen macros like \beq var seenUserDefinedEndEquation = false; // if we have seen macros like \eeq for (var i = 0, len = Tokens.length; i < len; i++) { var token = Tokens[i]; var line = token[0], type = token[1], start = token[2], end = token[3], seq = token[4]; if (type === "{") { Environments.push({command:"{", token:token, mathMode: nextGroupMathMode}); nextGroupMathModeStack.push(nextGroupMathMode); nextGroupMathMode = null; continue; } else if (type === "}") { Environments.push({command:"}", token:token}); nextGroupMathMode = nextGroupMathModeStack.pop(); continue; } else { nextGroupMathMode = null; }; if (type === "\\") { if (seq === "begin" || seq === "end") { var open = Tokens[i+1]; var env = Tokens[i+2]; var close = Tokens[i+3]; if(open && open[1] === "{" && env && env[1] === "Text" && close && close[1] === "}") { var envName = text.substring(env[2], env[3]); Environments.push({command: seq, name: envName, token: token, closeToken: close}); i = i + 3; // advance past these tokens } else { if (open && open[1] === "{" && env && env[1] === "Text") { envName = ""; for (var j = i + 2, tok; (tok = Tokens[j]); j++) { if (tok[1] === "Text") { var str = text.substring(tok[2], tok[3]); if (!str.match(/^\S*$/)) { break; } envName = envName + str; } else if (tok[1] === "_") { envName = envName + "_"; } else { break; } } if (tok && tok[1] === "}") { Environments.push({command: seq, name: envName, token: token, closeToken: close}); i = j; // advance past these tokens continue; } } var endToken = null; if (open && open[1] === "{") { endToken = open; // we've got a { if (env && env[1] === "Text") { endToken = env.slice(); // we've got some text following the { start = endToken[2]; end = endToken[3]; for (j = start; j < end; j++) { var char = text[j]; if (char === ' ' || char === '\t' || char === '\r' || char === '\n') { break; } } endToken[3] = j; // the end of partial token is as far as we got looking ahead }; }; if (endToken) { TokenErrorFromTo(token, endToken, "invalid environment command " + text.substring(token[2], endToken[3] || endToken[2])); } else { TokenError(token, "invalid environment command"); }; } } else if (typeof seq === "string" && seq.match(/^(be|beq|beqa|bea)$/i)) { seenUserDefinedBeginEquation = true; } else if (typeof seq === "string" && seq.match(/^(ee|eeq|eeqn|eeqa|eeqan|eea)$/i)) { seenUserDefinedEndEquation = true; } else if (seq === "newcommand" || seq === "renewcommand" || seq === "DeclareRobustCommand") { var newPos = read1arg(TokeniseResult, i, {allowStar: true}); if (newPos === null) { continue; } else {i = newPos;}; newPos = readOptionalParams(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "def") { newPos = read1arg(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; newPos = readOptionalDef(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "let") { newPos = readLetDefinition(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; } else if (seq === "newcolumntype") { newPos = read1name(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; newPos = readOptionalParams(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "newenvironment" || seq === "renewenvironment") { newPos = read1name(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; newPos = readOptionalParams(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "verb") { newPos = readVerb(TokeniseResult, i); if (newPos === null) { TokenError(token, "invalid verbatim command"); } else {i = newPos;}; } else if (seq === "url") { newPos = readUrl(TokeniseResult, i); if (newPos === null) { TokenError(token, "invalid url command"); } else {i = newPos;}; } else if (seq === "left" || seq === "right") { var nextToken = Tokens[i+1]; char = ""; if (nextToken && nextToken[1] === "Text") { char = text.substring(nextToken[2], nextToken[2] + 1); } else if (nextToken && nextToken[1] === "\\" && nextToken[5] == "control-symbol") { char = nextToken[4]; } else if (nextToken && nextToken[1] === "\\") { char = "unknown"; } if (char === "" || (char !== "unknown" && "(){}[]<>/|\\.".indexOf(char) === -1)) { TokenError(token, "invalid bracket command"); } else { i = i + 1; Environments.push({command:seq, token:token}); }; } else if (seq === "(" || seq === ")" || seq === "[" || seq === "]") { Environments.push({command:seq, token:token}); } else if (seq === "input") { newPos = read1filename(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; } else if (seq === "hbox" || seq === "text" || seq === "mbox" || seq === "footnote" || seq === "intertext" || seq === "shortintertext" || seq === "textnormal" || seq === "tag" || seq === "reflectbox" || seq === "textrm") { nextGroupMathMode = false; } else if (seq === "rotatebox" || seq === "scalebox") { newPos = readOptionalGeneric(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; nextGroupMathMode = false; } else if (seq === "resizebox") { newPos = readOptionalGeneric(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; nextGroupMathMode = false; } else if (seq === "DeclareMathOperator") { newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "DeclarePairedDelimiter") { newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (typeof seq === "string" && seq.match(/^(alpha|beta|gamma|delta|epsilon|varepsilon|zeta|eta|theta|vartheta|iota|kappa|lambda|mu|nu|xi|pi|varpi|rho|varrho|sigma|varsigma|tau|upsilon|phi|varphi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)$/)) { var currentMathMode = Environments.getMathMode() ; // returns null / $(inline) / $$(display) if (currentMathMode === null) { TokenError(token, type + seq + " must be inside math mode", {mathMode:true}); }; } else if (typeof seq === "string" && seq.match(/^(chapter|section|subsection|subsubsection)$/)) { currentMathMode = Environments.getMathMode() ; // returns null / $(inline) / $$(display) if (currentMathMode) { TokenError(token, type + seq + " used inside math mode", {mathMode:true}); Environments.resetMathMode(); }; } else if (typeof seq === "string" && seq.match(/^[a-z]+$/)) { nextGroupMathMode = undefined; }; } else if (type === "$") { var lookAhead = Tokens[i+1]; var nextIsDollar = lookAhead && lookAhead[1] === "$"; currentMathMode = Environments.getMathMode() ; // returns null / $(inline) / $$(display) if (nextIsDollar && (!currentMathMode || currentMathMode.command == "$$")) { Environments.push({command:"$$", token:token}); i = i + 1; } else { Environments.push({command:"$", token:token}); } } else if (type === "^" || type === "_") { currentMathMode = Environments.getMathMode() ; // returns null / $(inline) / $$(display) var insideGroup = Environments.insideGroup(); // true if inside {....} if (currentMathMode === null && !insideGroup) { TokenError(token, type + " must be inside math mode", {mathMode:true}); }; } }; if (seenUserDefinedBeginEquation && seenUserDefinedEndEquation) { ErrorReporter.filterMath = true; }; return Environments; }; var EnvHandler = function (ErrorReporter) { var ErrorTo = ErrorReporter.EnvErrorTo; var ErrorFromTo = ErrorReporter.EnvErrorFromTo; var ErrorFrom = ErrorReporter.EnvErrorFrom; var envs = []; var state = []; var documentClosed = null; var inVerbatim = false; var verbatimRanges = []; this.Environments = envs; this.push = function (newEnv) { this.setEnvProps(newEnv); this.checkAndUpdateState(newEnv); envs.push(newEnv); }; this._endVerbatim = function (thisEnv) { var lastEnv = state.pop(); if (lastEnv && lastEnv.name === thisEnv.name) { inVerbatim = false; verbatimRanges.push({start: lastEnv.token[2], end: thisEnv.token[2]}); } else { if(lastEnv) { state.push(lastEnv); } ; } }; var invalidEnvs = []; this._end = function (thisEnv) { do { var lastEnv = state.pop(); var retry = false; var i; if (closedBy(lastEnv, thisEnv)) { if (thisEnv.command === "end" && thisEnv.name === "document" && !documentClosed) { documentClosed = thisEnv; }; return; } else if (!lastEnv) { if (documentClosed) { ErrorFromTo(documentClosed, thisEnv, "\\end{" + documentClosed.name + "} is followed by unexpected content",{errorAtStart: true, type: "info"}); } else { ErrorTo(thisEnv, "unexpected " + getName(thisEnv)); } } else if (invalidEnvs.length > 0 && (i = indexOfClosingEnvInArray(invalidEnvs, thisEnv) > -1)) { invalidEnvs.splice(i, 1); if (lastEnv) { state.push(lastEnv); } ; return; } else { var status = reportError(lastEnv, thisEnv); if (envPrecedence(lastEnv) < envPrecedence(thisEnv)) { invalidEnvs.push(lastEnv); retry = true; } else { var prevLastEnv = state.pop(); if(prevLastEnv) { if (thisEnv.name === prevLastEnv.name) { return; } else { state.push(prevLastEnv); } } invalidEnvs.push(lastEnv); } } } while (retry === true); }; var CLOSING_DELIMITER = { "{" : "}", "left" : "right", "[" : "]", "(" : ")", "$" : "$", "$$": "$$" }; var closedBy = function (lastEnv, thisEnv) { if (!lastEnv) { return false ; } else if (thisEnv.command === "end") { return lastEnv.command === "begin" && lastEnv.name === thisEnv.name; } else if (thisEnv.command === CLOSING_DELIMITER[lastEnv.command]) { return true; } else { return false; } }; var indexOfClosingEnvInArray = function (envs, thisEnv) { for (var i = 0, n = envs.length; i < n ; i++) { if (closedBy(envs[i], thisEnv)) { return i; } } return -1; }; var envPrecedence = function (env) { var openScore = { "{" : 1, "left" : 2, "$" : 3, "$$" : 4, "begin": 4 }; var closeScore = { "}" : 1, "right" : 2, "$" : 3, "$$" : 5, "end": 4 }; if (env.command) { return openScore[env.command] || closeScore[env.command]; } else { return 0; } }; var getName = function(env) { var description = { "{" : "open group {", "}" : "close group }", "[" : "open display math \\[", "]" : "close display math \\]", "(" : "open inline math \\(", ")" : "close inline math \\)", "$" : "$", "$$" : "$$", "left" : "\\left", "right" : "\\right" }; if (env.command === "begin" || env.command === "end") { return "\\" + env.command + "{" + env.name + "}"; } else if (env.command in description) { return description[env.command]; } else { return env.command; } }; var EXTRA_CLOSE = 1; var UNCLOSED_GROUP = 2; var UNCLOSED_ENV = 3; var reportError = function(lastEnv, thisEnv) { if (!lastEnv) { // unexpected close, nothing was open! if (documentClosed) { ErrorFromTo(documentClosed, thisEnv, "\\end{" + documentClosed.name + "} is followed by unexpected end group }",{errorAtStart: true, type: "info"}); } else { ErrorTo(thisEnv, "unexpected " + getName(thisEnv)); }; return EXTRA_CLOSE; } else if (lastEnv.command === "{" && thisEnv.command === "end") { ErrorFromTo(lastEnv, thisEnv, "unclosed " + getName(lastEnv) + " found at " + getName(thisEnv), {suppressIfEditing:true, errorAtStart: true, type:"warning"}); return UNCLOSED_GROUP; } else { var pLast = envPrecedence(lastEnv); var pThis = envPrecedence(thisEnv); if (pThis > pLast) { ErrorFromTo(lastEnv, thisEnv, "unclosed " + getName(lastEnv) + " found at " + getName(thisEnv), {suppressIfEditing:true, errorAtStart: true}); } else { ErrorFromTo(lastEnv, thisEnv, "unexpected " + getName(thisEnv) + " after " + getName(lastEnv)); } return UNCLOSED_ENV; }; }; this._beginMathMode = function (thisEnv) { var currentMathMode = this.getMathMode(); // undefined, null, $, $$, name of mathmode env if (currentMathMode) { ErrorFrom(thisEnv, thisEnv.name + " used inside existing math mode " + getName(currentMathMode), {suppressIfEditing:true, errorAtStart: true, mathMode:true}); }; thisEnv.mathMode = thisEnv; state.push(thisEnv); }; this._toggleMathMode = function (thisEnv) { var lastEnv = state.pop(); if (closedBy(lastEnv, thisEnv)) { return; } else { if (lastEnv) {state.push(lastEnv);} if (lastEnv && lastEnv.mathMode) { this._end(thisEnv); } else { thisEnv.mathMode = thisEnv; state.push(thisEnv); } }; }; this.getMathMode = function () { var n = state.length; if (n > 0) { return state[n-1].mathMode; } else { return null; } }; this.insideGroup = function () { var n = state.length; if (n > 0) { return (state[n-1].command === "{"); } else { return null; } }; var resetMathMode = function () { var n = state.length; if (n > 0) { var lastMathMode = state[n-1].mathMode; do { var lastEnv = state.pop(); } while (lastEnv && lastEnv !== lastMathMode); } else { return; } }; this.resetMathMode = resetMathMode; var getNewMathMode = function (currentMathMode, thisEnv) { var newMathMode = null; if (thisEnv.command === "{") { if (thisEnv.mathMode !== null) { newMathMode = thisEnv.mathMode; } else { newMathMode = currentMathMode; } } else if (thisEnv.command === "left") { if (currentMathMode === null) { ErrorFrom(thisEnv, "\\left can only be used in math mode", {mathMode: true}); }; newMathMode = currentMathMode; } else if (thisEnv.command === "begin") { var name = thisEnv.name; if (name) { if (name.match(/^(document|figure|center|enumerate|itemize|table|abstract|proof|lemma|theorem|definition|proposition|corollary|remark|notation|thebibliography)$/)) { if (currentMathMode) { ErrorFromTo(currentMathMode, thisEnv, thisEnv.name + " used inside " + getName(currentMathMode), {suppressIfEditing:true, errorAtStart: true, mathMode: true}); resetMathMode(); }; newMathMode = null; } else if (name.match(/^(array|gathered|split|aligned|alignedat)\*?$/)) { if (currentMathMode === null) { ErrorFrom(thisEnv, thisEnv.name + " not inside math mode", {mathMode: true}); }; newMathMode = currentMathMode; } else if (name.match(/^(math|displaymath|equation|eqnarray|multline|align|gather|flalign|alignat)\*?$/)) { if (currentMathMode) { ErrorFromTo(currentMathMode, thisEnv, thisEnv.name + " used inside " + getName(currentMathMode), {suppressIfEditing:true, errorAtStart: true, mathMode: true}); resetMathMode(); }; newMathMode = thisEnv; } else { newMathMode = undefined; // undefined means we don't know if we are in math mode or not } } }; return newMathMode; }; this.checkAndUpdateState = function (thisEnv) { if (inVerbatim) { if (thisEnv.command === "end") { this._endVerbatim(thisEnv); } else { return; // ignore anything in verbatim environments } } else if(thisEnv.command === "begin" || thisEnv.command === "{" || thisEnv.command === "left") { if (thisEnv.verbatim) {inVerbatim = true;}; var currentMathMode = this.getMathMode(); // undefined, null, $, $$, name of mathmode env var newMathMode = getNewMathMode(currentMathMode, thisEnv); thisEnv.mathMode = newMathMode; state.push(thisEnv); } else if (thisEnv.command === "end") { this._end(thisEnv); } else if (thisEnv.command === "(" || thisEnv.command === "[") { this._beginMathMode(thisEnv); } else if (thisEnv.command === ")" || thisEnv.command === "]") { this._end(thisEnv); } else if (thisEnv.command === "}") { this._end(thisEnv); } else if (thisEnv.command === "right") { this._end(thisEnv); } else if (thisEnv.command === "$" || thisEnv.command === "$$") { this._toggleMathMode(thisEnv); } }; this.close = function () { while (state.length > 0) { var thisEnv = state.pop(); if (thisEnv.command === "{") { ErrorFrom(thisEnv, "unclosed group {", {type:"warning"}); } else { ErrorFrom(thisEnv, "unclosed " + getName(thisEnv)); } } var vlen = verbatimRanges.length; var len = ErrorReporter.tokenErrors.length; if (vlen >0 && len > 0) { for (var i = 0; i < len; i++) { var tokenError = ErrorReporter.tokenErrors[i]; var startPos = tokenError.startPos; var endPos = tokenError.endPos; for (var j = 0; j < vlen; j++) { if (startPos > verbatimRanges[j].start && startPos < verbatimRanges[j].end) { tokenError.ignore = true; break; } } } } }; this.setEnvProps = function (env) { var name = env.name ; if (name && name.match(/^(verbatim|boxedverbatim|lstlisting|minted|Verbatim)$/)) { env.verbatim = true; } }; }; var ErrorReporter = function (TokeniseResult) { var text = TokeniseResult.text; var linePosition = TokeniseResult.linePosition; var lineNumber = TokeniseResult.lineNumber; var errors = [], tokenErrors = []; this.errors = errors; this.tokenErrors = tokenErrors; this.filterMath = false; this.getErrors = function () { var returnedErrors = []; for (var i = 0, len = tokenErrors.length; i < len; i++) { if (!tokenErrors[i].ignore) { returnedErrors.push(tokenErrors[i]); } } var allErrors = returnedErrors.concat(errors); var result = []; var mathErrorCount = 0; for (i = 0, len = allErrors.length; i < len; i++) { if (allErrors[i].mathMode) { mathErrorCount++; } if (mathErrorCount > 10) { return []; } } if (this.filterMath && mathErrorCount > 0) { for (i = 0, len = allErrors.length; i < len; i++) { if (!allErrors[i].mathMode) { result.push(allErrors[i]); } } return result; } else { return allErrors; } }; this.TokenError = function (token, message, options) { if(!options) { options = { suppressIfEditing:true } ; }; var line = token[0], type = token[1], start = token[2], end = token[3]; var start_col = start - linePosition[line]; if (!end) { end = start + 1; } ; var end_col = end - linePosition[line]; tokenErrors.push({row: line, column: start_col, start_row:line, start_col: start_col, end_row:line, end_col: end_col, type:"error", text:message, startPos: start, endPos: end, suppressIfEditing:options.suppressIfEditing, mathMode: options.mathMode}); }; this.TokenErrorFromTo = function (fromToken, toToken, message, options) { if(!options) { options = {suppressIfEditing:true } ; }; var fromLine = fromToken[0], fromStart = fromToken[2], fromEnd = fromToken[3]; var toLine = toToken[0], toStart = toToken[2], toEnd = toToken[3]; if (!toEnd) { toEnd = toStart + 1;}; var start_col = fromStart - linePosition[fromLine]; var end_col = toEnd - linePosition[toLine]; tokenErrors.push({row: fromLine, column: start_col, start_row: fromLine, start_col: start_col, end_row: toLine, end_col: end_col, type:"error", text:message, startPos: fromStart, endPos: toEnd, suppressIfEditing:options.suppressIfEditing, mathMode: options.mathMode}); }; this.EnvErrorFromTo = function (fromEnv, toEnv, message, options) { if(!options) { options = {} ; }; var fromToken = fromEnv.token, toToken = toEnv.closeToken || toEnv.token; var fromLine = fromToken[0], fromStart = fromToken[2], fromEnd = fromToken[3]; if (!toToken) {toToken = fromToken;}; var toLine = toToken[0], toStart = toToken[2], toEnd = toToken[3]; if (!toEnd) { toEnd = toStart + 1;}; var start_col = fromStart - linePosition[fromLine]; var end_col = toEnd - linePosition[toLine]; errors.push({row: options.errorAtStart ? fromLine : toLine, column: options.errorAtStart ? start_col: end_col, start_row:fromLine, start_col: start_col, end_row:toLine, end_col: end_col, type: options.type ? options.type : "error", text:message, suppressIfEditing:options.suppressIfEditing, mathMode: options.mathMode}); }; this.EnvErrorTo = function (toEnv, message, options) { if(!options) { options = {} ; }; var token = toEnv.closeToken || toEnv.token; var line = token[0], type = token[1], start = token[2], end = token[3]; if (!end) { end = start + 1; }; var end_col = end - linePosition[line]; var err = {row: line, column: end_col, start_row:0, start_col: 0, end_row: line, end_col: end_col, type: options.type ? options.type : "error", text:message, mathMode: options.mathMode}; errors.push(err); }; this.EnvErrorFrom = function (env, message, options) { if(!options) { options = {} ; }; var token = env.token; var line = token[0], type = token[1], start = token[2], end = token[3]; var start_col = start - linePosition[line]; var end_col = Infinity; errors.push({row: line, column: start_col, start_row:line, start_col: start_col, end_row: lineNumber, end_col: end_col, type: options.type ? options.type : "error", text:message, mathMode: options.mathMode}); }; }; var Parse = function (text) { var TokeniseResult = Tokenise(text); var Reporter = new ErrorReporter(TokeniseResult); var Environments = InterpretTokens(TokeniseResult, Reporter); Environments.close(); return Reporter.getErrors(); }; (function() { var disabled = false; this.onUpdate = function() { if (disabled) { return ; }; var value = this.doc.getValue(); var errors = []; try { if (value) errors = Parse(value); } catch (e) { disabled = true; errors = []; } this.sender.emit("lint", errors); }; }).call(LatexWorker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/libs/sigma-master/sigma.require.js
12,184
;(function(undefined) { 'use strict'; var __instances = {}; /** * This is the sigma instances constructor. One instance of sigma represent * one graph. It is possible to represent this grapĥ with several renderers * at the same time. By default, the default renderer (WebGL + Canvas * polyfill) will be used as the only renderer, with the container specified * in the configuration. * * @param {?*} conf The configuration of the instance. There are a lot of * different recognized forms to instantiate sigma, check * example files, documentation in this file and unit * tests to know more. * @return {sigma} The fresh new sigma instance. * * Instanciating sigma: * ******************** * If no parameter is given to the constructor, the instance will be created * without any renderer or camera. It will just instantiate the graph, and * other modules will have to be instantiated through the public methods, * like "addRenderer" etc: * * > s0 = new sigma(); * > s0.addRenderer({ * > type: 'canvas', * > container: 'my-container-id' * > }); * * In most of the cases, sigma will simply be used with the default renderer. * Then, since the only required parameter is the DOM container, there are * some simpler way to call the constructor. The four following calls do the * exact same things: * * > s1 = new sigma('my-container-id'); * > s2 = new sigma(document.getElementById('my-container-id')); * > s3 = new sigma({ * > container: document.getElementById('my-container-id') * > }); * > s4 = new sigma({ * > renderers: [{ * > container: document.getElementById('my-container-id') * > }] * > }); * * Recognized parameters: * ********************** * Here is the exhaustive list of every accepted parameters, when calling the * constructor with to top level configuration object (fourth case in the * previous examples): * * {?string} id The id of the instance. It will be generated * automatically if not specified. * {?array} renderers An array containing objects describing renderers. * {?object} graph An object containing an array of nodes and an array * of edges, to avoid having to add them by hand later. * {?object} settings An object containing instance specific settings that * will override the default ones defined in the object * sigma.settings. */ var sigma = function(conf) { // Local variables: // **************** var i, l, a, c, o, id; sigma.classes.dispatcher.extend(this); // Private attributes: // ******************* var _self = this, _conf = conf || {}; // Little shortcut: // **************** // The configuration is supposed to have a list of the configuration // objects for each renderer. // - If there are no configuration at all, then nothing is done. // - If there are no renderer list, the given configuration object will be // considered as describing the first and only renderer. // - If there are no renderer list nor "container" object, it will be // considered as the container itself (a DOM element). // - If the argument passed to sigma() is a string, it will be considered // as the ID of the DOM container. if ( typeof _conf === 'string' || _conf instanceof HTMLElement ) _conf = { renderers: [_conf] }; else if (Object.prototype.toString.call(_conf) === '[object Array]') _conf = { renderers: _conf }; // Also check "renderer" and "container" keys: o = _conf.renderers || _conf.renderer || _conf.container; if (!_conf.renderers || _conf.renderers.length === 0) if ( typeof o === 'string' || o instanceof HTMLElement || (typeof o === 'object' && 'container' in o) ) _conf.renderers = [o]; // Recense the instance: if (_conf.id) { if (__instances[_conf.id]) throw 'sigma: Instance "' + _conf.id + '" already exists.'; Object.defineProperty(this, 'id', { value: _conf.id }); } else { id = 0; while (__instances[id]) id++; Object.defineProperty(this, 'id', { value: '' + id }); } __instances[this.id] = this; // Initialize settings function: this.settings = new sigma.classes.configurable( sigma.settings, _conf.settings || {} ); // Initialize locked attributes: Object.defineProperty(this, 'graph', { value: new sigma.classes.graph(this.settings), configurable: true }); Object.defineProperty(this, 'middlewares', { value: [], configurable: true }); Object.defineProperty(this, 'cameras', { value: {}, configurable: true }); Object.defineProperty(this, 'renderers', { value: {}, configurable: true }); Object.defineProperty(this, 'renderersPerCamera', { value: {}, configurable: true }); Object.defineProperty(this, 'cameraFrames', { value: {}, configurable: true }); Object.defineProperty(this, 'camera', { get: function() { return this.cameras[0]; } }); Object.defineProperty(this, 'events', { value: [ 'click', 'rightClick', 'clickStage', 'doubleClickStage', 'rightClickStage', 'clickNode', 'clickNodes', 'doubleClickNode', 'doubleClickNodes', 'rightClickNode', 'rightClickNodes', 'overNode', 'overNodes', 'outNode', 'outNodes', 'downNode', 'downNodes', 'upNode', 'upNodes' ], configurable: true }); // Add a custom handler, to redispatch events from renderers: this._handler = (function(e) { var k, data = {}; for (k in e.data) data[k] = e.data[k]; data.renderer = e.target; this.dispatchEvent(e.type, data); }).bind(this); // Initialize renderers: a = _conf.renderers || []; for (i = 0, l = a.length; i < l; i++) this.addRenderer(a[i]); // Initialize middlewares: a = _conf.middlewares || []; for (i = 0, l = a.length; i < l; i++) this.middlewares.push( typeof a[i] === 'string' ? sigma.middlewares[a[i]] : a[i] ); // Check if there is already a graph to fill in: if (typeof _conf.graph === 'object' && _conf.graph) { this.graph.read(_conf.graph); // If a graph is given to the to the instance, the "refresh" method is // directly called: this.refresh(); } // Deal with resize: window.addEventListener('resize', function() { if (_self.settings) _self.refresh(); }); }; /** * This methods will instantiate and reference a new camera. If no id is * specified, then an automatic id will be generated. * * @param {?string} id Eventually the camera id. * @return {sigma.classes.camera} The fresh new camera instance. */ sigma.prototype.addCamera = function(id) { var self = this, camera; if (!arguments.length) { id = 0; while (this.cameras['' + id]) id++; id = '' + id; } if (this.cameras[id]) throw 'sigma.addCamera: The camera "' + id + '" already exists.'; camera = new sigma.classes.camera(id, this.graph, this.settings); this.cameras[id] = camera; // Add a quadtree to the camera: camera.quadtree = new sigma.classes.quad(); // Add an edgequadtree to the camera: if (sigma.classes.edgequad !== undefined) { camera.edgequadtree = new sigma.classes.edgequad(); } camera.bind('coordinatesUpdated', function(e) { self.renderCamera(camera, camera.isAnimated); }); this.renderersPerCamera[id] = []; return camera; }; /** * This method kills a camera, and every renderer attached to it. * * @param {string|camera} v The camera to kill or its ID. * @return {sigma} Returns the instance. */ sigma.prototype.killCamera = function(v) { v = typeof v === 'string' ? this.cameras[v] : v; if (!v) throw 'sigma.killCamera: The camera is undefined.'; var i, l, a = this.renderersPerCamera[v.id]; for (l = a.length, i = l - 1; i >= 0; i--) this.killRenderer(a[i]); delete this.renderersPerCamera[v.id]; delete this.cameraFrames[v.id]; delete this.cameras[v.id]; if (v.kill) v.kill(); return this; }; /** * This methods will instantiate and reference a new renderer. The "type" * argument can be the constructor or its name in the "sigma.renderers" * package. If no type is specified, then "sigma.renderers.def" will be used. * If no id is specified, then an automatic id will be generated. * * @param {?object} options Eventually some options to give to the renderer * constructor. * @return {renderer} The fresh new renderer instance. * * Recognized parameters: * ********************** * Here is the exhaustive list of every accepted parameters in the "options" * object: * * {?string} id Eventually the renderer id. * {?(function|string)} type Eventually the renderer constructor or its * name in the "sigma.renderers" package. * {?(camera|string)} camera Eventually the renderer camera or its * id. */ sigma.prototype.addRenderer = function(options) { var id, fn, camera, renderer, o = options || {}; // Polymorphism: if (typeof o === 'string') o = { container: document.getElementById(o) }; else if (o instanceof HTMLElement) o = { container: o }; // If the container still is a string, we get it by id if (typeof o.container === 'string') o.container = document.getElementById(o.container); // Reference the new renderer: if (!('id' in o)) { id = 0; while (this.renderers['' + id]) id++; id = '' + id; } else id = o.id; if (this.renderers[id]) throw 'sigma.addRenderer: The renderer "' + id + '" already exists.'; // Find the good constructor: fn = typeof o.type === 'function' ? o.type : sigma.renderers[o.type]; fn = fn || sigma.renderers.def; // Find the good camera: camera = 'camera' in o ? ( o.camera instanceof sigma.classes.camera ? o.camera : this.cameras[o.camera] || this.addCamera(o.camera) ) : this.addCamera(); if (this.cameras[camera.id] !== camera) throw 'sigma.addRenderer: The camera is not properly referenced.'; // Instantiate: renderer = new fn(this.graph, camera, this.settings, o); this.renderers[id] = renderer; Object.defineProperty(renderer, 'id', { value: id }); // Bind events: if (renderer.bind) renderer.bind( [ 'click', 'rightClick', 'clickStage', 'doubleClickStage', 'rightClickStage', 'clickNode', 'clickNodes', 'clickEdge', 'clickEdges', 'doubleClickNode', 'doubleClickNodes', 'doubleClickEdge', 'doubleClickEdges', 'rightClickNode', 'rightClickNodes', 'rightClickEdge', 'rightClickEdges', 'overNode', 'overNodes', 'overEdge', 'overEdges', 'outNode', 'outNodes', 'outEdge', 'outEdges', 'downNode', 'downNodes', 'downEdge', 'downEdges', 'upNode', 'upNodes', 'upEdge', 'upEdges' ], this._handler ); // Reference the renderer by its camera: this.renderersPerCamera[camera.id].push(renderer); return renderer; }; /** * This method kills a renderer. * * @param {string|renderer} v The renderer to kill or its ID. * @return {sigma} Returns the instance. */ sigma.prototype.killRenderer = function(v) { v = typeof v === 'string' ? this.renderers[v] : v; if (!v) throw 'sigma.killRenderer: The renderer is undefined.'; var a = this.renderersPerCamera[v.camera.id], i = a.indexOf(v); if (i >= 0) a.splice(i, 1); if (v.kill) v.kill(); delete this.renderers[v.id]; return this; }; /** * This method calls the "render" method of each renderer, with the same * arguments than the "render" method, but will also check if the renderer * has a "process" method, and call it if it exists. * * It is useful for quadtrees or WebGL processing, for instance. * * @param {?object} options Eventually some options to give to the refresh * method. * @return {sigma} Returns the instance itself. * * Recognized parameters: * ********************** * Here is the exhaustive list of every accepted parameters in the "options" * object: * * {?boolean} skipIndexation A flag specifying wether or not the refresh * function should reindex the graph in the * quadtrees or not (default: false). */ sigma.prototype.refresh = function(options) { var i, l, k, a, c, bounds, prefix = 0; options = options || {}; // Call each middleware: a = this.middlewares || []; for (i = 0, l = a.length; i < l; i++) a[i].call( this, (i === 0) ? '' : 'tmp' + prefix + ':', (i === l - 1) ? 'ready:' : ('tmp' + (++prefix) + ':') ); // Then, for each camera, call the "rescale" middleware, unless the // settings specify not to: for (k in this.cameras) { c = this.cameras[k]; if ( c.settings('autoRescale') && this.renderersPerCamera[c.id] && this.renderersPerCamera[c.id].length ) sigma.middlewares.rescale.call( this, a.length ? 'ready:' : '', c.readPrefix, { width: this.renderersPerCamera[c.id][0].width, height: this.renderersPerCamera[c.id][0].height } ); else sigma.middlewares.copy.call( this, a.length ? 'ready:' : '', c.readPrefix ); if (!options.skipIndexation) { // Find graph boundaries: bounds = sigma.utils.getBoundaries( this.graph, c.readPrefix ); // Refresh quadtree: c.quadtree.index(this.graph.nodes(), { prefix: c.readPrefix, bounds: { x: bounds.minX, y: bounds.minY, width: bounds.maxX - bounds.minX, height: bounds.maxY - bounds.minY } }); // Refresh edgequadtree: if ( c.edgequadtree !== undefined && c.settings('drawEdges') && c.settings('enableEdgeHovering') ) { c.edgequadtree.index(this.graph, { prefix: c.readPrefix, bounds: { x: bounds.minX, y: bounds.minY, width: bounds.maxX - bounds.minX, height: bounds.maxY - bounds.minY } }); } } } // Call each renderer: a = Object.keys(this.renderers); for (i = 0, l = a.length; i < l; i++) if (this.renderers[a[i]].process) { if (this.settings('skipErrors')) try { this.renderers[a[i]].process(); } catch (e) { console.log( 'Warning: The renderer "' + a[i] + '" crashed on ".process()"' ); } else this.renderers[a[i]].process(); } this.render(); return this; }; /** * This method calls the "render" method of each renderer. * * @return {sigma} Returns the instance itself. */ sigma.prototype.render = function() { var i, l, a, prefix = 0; // Call each renderer: a = Object.keys(this.renderers); for (i = 0, l = a.length; i < l; i++) if (this.settings('skipErrors')) try { this.renderers[a[i]].render(); } catch (e) { if (this.settings('verbose')) console.log( 'Warning: The renderer "' + a[i] + '" crashed on ".render()"' ); } else this.renderers[a[i]].render(); return this; }; /** * This method calls the "render" method of each renderer that is bound to * the specified camera. To improve the performances, if this method is * called too often, the number of effective renderings is limitated to one * per frame, unless you are using the "force" flag. * * @param {sigma.classes.camera} camera The camera to render. * @param {?boolean} force If true, will render the camera * directly. * @return {sigma} Returns the instance itself. */ sigma.prototype.renderCamera = function(camera, force) { var i, l, a, self = this; if (force) { a = this.renderersPerCamera[camera.id]; for (i = 0, l = a.length; i < l; i++) if (this.settings('skipErrors')) try { a[i].render(); } catch (e) { if (this.settings('verbose')) console.log( 'Warning: The renderer "' + a[i].id + '" crashed on ".render()"' ); } else a[i].render(); } else { if (!this.cameraFrames[camera.id]) { a = this.renderersPerCamera[camera.id]; for (i = 0, l = a.length; i < l; i++) if (this.settings('skipErrors')) try { a[i].render(); } catch (e) { if (this.settings('verbose')) console.log( 'Warning: The renderer "' + a[i].id + '" crashed on ".render()"' ); } else a[i].render(); this.cameraFrames[camera.id] = requestAnimationFrame(function() { delete self.cameraFrames[camera.id]; }); } } return this; }; /** * This method calls the "kill" method of each module and destroys any * reference from the instance. */ sigma.prototype.kill = function() { var k; // Dispatching event this.dispatchEvent('kill'); // Kill graph: this.graph.kill(); // Kill middlewares: delete this.middlewares; // Kill each renderer: for (k in this.renderers) this.killRenderer(this.renderers[k]); // Kill each camera: for (k in this.cameras) this.killCamera(this.cameras[k]); delete this.renderers; delete this.cameras; // Kill everything else: for (k in this) if (this.hasOwnProperty(k)) delete this[k]; delete __instances[this.id]; }; /** * Returns a clone of the instances object or a specific running instance. * * @param {?string} id Eventually an instance ID. * @return {object} The related instance or a clone of the instances * object. */ sigma.instances = function(id) { return arguments.length ? __instances[id] : sigma.utils.extend({}, __instances); }; /** * The current version of sigma: */ sigma.version = '1.0.3'; /** * EXPORT: * ******* */ if (typeof this.sigma !== 'undefined') throw 'An object called sigma is already in the global scope.'; this.sigma = sigma; }).call(this); /** * conrad.js is a tiny JavaScript jobs scheduler, * * Version: 0.1.0 * Sources: http://github.com/jacomyal/conrad.js * Doc: http://github.com/jacomyal/conrad.js#readme * * License: * -------- * Copyright © 2013 Alexis Jacomy, Sciences-Po médialab * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to * deal in the Software without restriction, including without limitation the * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or * sell copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * The Software is provided "as is", without warranty of any kind, express or * implied, including but not limited to the warranties of merchantability, * fitness for a particular purpose and noninfringement. In no event shall the * authors or copyright holders be liable for any claim, damages or other * liability, whether in an action of contract, tort or otherwise, arising * from, out of or in connection with the software or the use or other dealings * in the Software. */ (function(global) { 'use strict'; // Check that conrad.js has not been loaded yet: if (global.conrad) throw new Error('conrad already exists'); /** * PRIVATE VARIABLES: * ****************** */ /** * A flag indicating whether conrad is running or not. * * @type {Number} */ var _lastFrameTime; /** * A flag indicating whether conrad is running or not. * * @type {Boolean} */ var _isRunning = false; /** * The hash of registered jobs. Each job must at least have a unique ID * under the key "id" and a function under the key "job". This hash * contains each running job and each waiting job. * * @type {Object} */ var _jobs = {}; /** * The hash of currently running jobs. * * @type {Object} */ var _runningJobs = {}; /** * The array of currently running jobs, sorted by priority. * * @type {Array} */ var _sortedByPriorityJobs = []; /** * The array of currently waiting jobs. * * @type {Object} */ var _waitingJobs = {}; /** * The array of finished jobs. They are stored in an array, since two jobs * with the same "id" can happen at two different times. * * @type {Array} */ var _doneJobs = []; /** * A dirty flag to keep conrad from starting: Indeed, when addJob() is called * with several jobs, conrad must be started only at the end. This flag keeps * me from duplicating the code that effectively adds a job. * * @type {Boolean} */ var _noStart = false; /** * An hash containing some global settings about how conrad.js should * behave. * * @type {Object} */ var _parameters = { frameDuration: 20, history: true }; /** * This object contains every handlers bound to conrad events. It does not * requirea any DOM implementation, since the events are all JavaScript. * * @type {Object} */ var _handlers = Object.create(null); /** * PRIVATE FUNCTIONS: * ****************** */ /** * Will execute the handler everytime that the indicated event (or the * indicated events) will be triggered. * * @param {string|array|object} events The name of the event (or the events * separated by spaces). * @param {function(Object)} handler The handler to bind. * @return {Object} Returns conrad. */ function _bind(events, handler) { var i, i_end, event, eArray; if (!arguments.length) return; else if ( arguments.length === 1 && Object(arguments[0]) === arguments[0] ) for (events in arguments[0]) _bind(events, arguments[0][events]); else if (arguments.length > 1) { eArray = Array.isArray(events) ? events : events.split(/ /); for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { event = eArray[i]; if (!_handlers[event]) _handlers[event] = []; // Using an object instead of directly the handler will make possible // later to add flags _handlers[event].push({ handler: handler }); } } } /** * Removes the handler from a specified event (or specified events). * * @param {?string} events The name of the event (or the events * separated by spaces). If undefined, * then all handlers are removed. * @param {?function(Object)} handler The handler to unbind. If undefined, * each handler bound to the event or the * events will be removed. * @return {Object} Returns conrad. */ function _unbind(events, handler) { var i, i_end, j, j_end, a, event, eArray = Array.isArray(events) ? events : events.split(/ /); if (!arguments.length) _handlers = Object.create(null); else if (handler) { for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { event = eArray[i]; if (_handlers[event]) { a = []; for (j = 0, j_end = _handlers[event].length; j !== j_end; j += 1) if (_handlers[event][j].handler !== handler) a.push(_handlers[event][j]); _handlers[event] = a; } if (_handlers[event] && _handlers[event].length === 0) delete _handlers[event]; } } else for (i = 0, i_end = eArray.length; i !== i_end; i += 1) delete _handlers[eArray[i]]; } /** * Executes each handler bound to the event. * * @param {string} events The name of the event (or the events separated * by spaces). * @param {?Object} data The content of the event (optional). * @return {Object} Returns conrad. */ function _dispatch(events, data) { var i, j, i_end, j_end, event, eventName, eArray = Array.isArray(events) ? events : events.split(/ /); data = data === undefined ? {} : data; for (i = 0, i_end = eArray.length; i !== i_end; i += 1) { eventName = eArray[i]; if (_handlers[eventName]) { event = { type: eventName, data: data || {} }; for (j = 0, j_end = _handlers[eventName].length; j !== j_end; j += 1) try { _handlers[eventName][j].handler(event); } catch (e) {} } } } /** * Executes the most prioritary job once, and deals with filling the stats * (done, time, averageTime, currentTime, etc...). * * @return {?Object} Returns the job object if it has to be killed, null else. */ function _executeFirstJob() { var i, l, test, kill, pushed = false, time = __dateNow(), job = _sortedByPriorityJobs.shift(); // Execute the job and look at the result: test = job.job(); // Deal with stats: time = __dateNow() - time; job.done++; job.time += time; job.currentTime += time; job.weightTime = job.currentTime / (job.weight || 1); job.averageTime = job.time / job.done; // Check if the job has to be killed: kill = job.count ? (job.count <= job.done) : !test; // Reset priorities: if (!kill) { for (i = 0, l = _sortedByPriorityJobs.length; i < l; i++) if (_sortedByPriorityJobs[i].weightTime > job.weightTime) { _sortedByPriorityJobs.splice(i, 0, job); pushed = true; break; } if (!pushed) _sortedByPriorityJobs.push(job); } return kill ? job : null; } /** * Activates a job, by adding it to the _runningJobs object and the * _sortedByPriorityJobs array. It also initializes its currentTime value. * * @param {Object} job The job to activate. */ function _activateJob(job) { var l = _sortedByPriorityJobs.length; // Add the job to the running jobs: _runningJobs[job.id] = job; job.status = 'running'; // Add the job to the priorities: if (l) { job.weightTime = _sortedByPriorityJobs[l - 1].weightTime; job.currentTime = job.weightTime * (job.weight || 1); } // Initialize the job and dispatch: job.startTime = __dateNow(); _dispatch('jobStarted', __clone(job)); _sortedByPriorityJobs.push(job); } /** * The main loop of conrad.js: * . It executes job such that they all occupate the same processing time. * . It stops jobs that do not need to be executed anymore. * . It triggers callbacks when it is relevant. * . It starts waiting jobs when they need to be started. * . It injects frames to keep a constant frapes per second ratio. * . It stops itself when there are no more jobs to execute. */ function _loop() { var k, o, l, job, time, deadJob; // Deal with the newly added jobs (the _jobs object): for (k in _jobs) { job = _jobs[k]; if (job.after) _waitingJobs[k] = job; else _activateJob(job); delete _jobs[k]; } // Set the _isRunning flag to false if there are no running job: _isRunning = !!_sortedByPriorityJobs.length; // Deal with the running jobs (the _runningJobs object): while ( _sortedByPriorityJobs.length && __dateNow() - _lastFrameTime < _parameters.frameDuration ) { deadJob = _executeFirstJob(); // Deal with the case where the job has ended: if (deadJob) { _killJob(deadJob.id); // Check for waiting jobs: for (k in _waitingJobs) if (_waitingJobs[k].after === deadJob.id) { _activateJob(_waitingJobs[k]); delete _waitingJobs[k]; } } } // Check if conrad still has jobs to deal with, and kill it if not: if (_isRunning) { // Update the _lastFrameTime: _lastFrameTime = __dateNow(); _dispatch('enterFrame'); setTimeout(_loop, 0); } else _dispatch('stop'); } /** * Adds one or more jobs, and starts the loop if no job was running before. A * job is at least a unique string "id" and a function, and there are some * parameters that you can specify for each job to modify the way conrad will * execute it. If a job is added with the "id" of another job that is waiting * or still running, an error will be thrown. * * When a job is added, it is referenced in the _jobs object, by its id. * Then, if it has to be executed right now, it will be also referenced in * the _runningJobs object. If it has to wait, then it will be added into the * _waitingJobs object, until it can start. * * Keep reading this documentation to see how to call this method. * * @return {Object} Returns conrad. * * Adding one job: * *************** * Basically, a job is defined by its string id and a function (the job). It * is also possible to add some parameters: * * > conrad.addJob('myJobId', myJobFunction); * > conrad.addJob('myJobId', { * > job: myJobFunction, * > someParameter: someValue * > }); * > conrad.addJob({ * > id: 'myJobId', * > job: myJobFunction, * > someParameter: someValue * > }); * * Adding several jobs: * ******************** * When adding several jobs at the same time, it is possible to specify * parameters for each one individually or for all: * * > conrad.addJob([ * > { * > id: 'myJobId1', * > job: myJobFunction1, * > someParameter1: someValue1 * > }, * > { * > id: 'myJobId2', * > job: myJobFunction2, * > someParameter2: someValue2 * > } * > ], { * > someCommonParameter: someCommonValue * > }); * > conrad.addJob({ * > myJobId1: {, * > job: myJobFunction1, * > someParameter1: someValue1 * > }, * > myJobId2: {, * > job: myJobFunction2, * > someParameter2: someValue2 * > } * > }, { * > someCommonParameter: someCommonValue * > }); * > conrad.addJob({ * > myJobId1: myJobFunction1, * > myJobId2: myJobFunction2 * > }, { * > someCommonParameter: someCommonValue * > }); * * Recognized parameters: * ********************** * Here is the exhaustive list of every accepted parameters: * * {?Function} end A callback to execute when the job is ended. It is * not executed if the job is killed instead of ended * "naturally". * {?Integer} count The number of time the job has to be executed. * {?Number} weight If specified, the job will be executed as it was * added "weight" times. * {?String} after The id of another job (eventually not added yet). * If specified, this job will start only when the * specified "after" job is ended. */ function _addJob(v1, v2) { var i, l, o; // Array of jobs: if (Array.isArray(v1)) { // Keep conrad to start until the last job is added: _noStart = true; for (i = 0, l = v1.length; i < l; i++) _addJob(v1[i].id, __extend(v1[i], v2)); _noStart = false; if (!_isRunning) { // Update the _lastFrameTime: _lastFrameTime = __dateNow(); _dispatch('start'); _loop(); } } else if (typeof v1 === 'object') { // One job (object): if (typeof v1.id === 'string') _addJob(v1.id, v1); // Hash of jobs: else { // Keep conrad to start until the last job is added: _noStart = true; for (i in v1) if (typeof v1[i] === 'function') _addJob(i, __extend({ job: v1[i] }, v2)); else _addJob(i, __extend(v1[i], v2)); _noStart = false; if (!_isRunning) { // Update the _lastFrameTime: _lastFrameTime = __dateNow(); _dispatch('start'); _loop(); } } // One job (string, *): } else if (typeof v1 === 'string') { if (_hasJob(v1)) throw new Error( '[conrad.addJob] Job with id "' + v1 + '" already exists.' ); // One job (string, function): if (typeof v2 === 'function') { o = { id: v1, done: 0, time: 0, status: 'waiting', currentTime: 0, averageTime: 0, weightTime: 0, job: v2 }; // One job (string, object): } else if (typeof v2 === 'object') { o = __extend( { id: v1, done: 0, time: 0, status: 'waiting', currentTime: 0, averageTime: 0, weightTime: 0 }, v2 ); // If none of those cases, throw an error: } else throw new Error('[conrad.addJob] Wrong arguments.'); // Effectively add the job: _jobs[v1] = o; _dispatch('jobAdded', __clone(o)); // Check if the loop has to be started: if (!_isRunning && !_noStart) { // Update the _lastFrameTime: _lastFrameTime = __dateNow(); _dispatch('start'); _loop(); } // If none of those cases, throw an error: } else throw new Error('[conrad.addJob] Wrong arguments.'); return this; } /** * Kills one or more jobs, indicated by their ids. It is only possible to * kill running jobs or waiting jobs. If you try to kill a job that does not * exists or that is already killed, a warning will be thrown. * * @param {Array|String} v1 A string job id or an array of job ids. * @return {Object} Returns conrad. */ function _killJob(v1) { var i, l, k, a, job, found = false; // Array of job ids: if (Array.isArray(v1)) for (i = 0, l = v1.length; i < l; i++) _killJob(v1[i]); // One job's id: else if (typeof v1 === 'string') { a = [_runningJobs, _waitingJobs, _jobs]; // Remove the job from the hashes: for (i = 0, l = a.length; i < l; i++) if (v1 in a[i]) { job = a[i][v1]; if (_parameters.history) { job.status = 'done'; _doneJobs.push(job); } _dispatch('jobEnded', __clone(job)); delete a[i][v1]; if (typeof job.end === 'function') job.end(); found = true; } // Remove the priorities array: a = _sortedByPriorityJobs; for (i = 0, l = a.length; i < l; i++) if (a[i].id === v1) { a.splice(i, 1); break; } if (!found) throw new Error('[conrad.killJob] Job "' + v1 + '" not found.'); // If none of those cases, throw an error: } else throw new Error('[conrad.killJob] Wrong arguments.'); return this; } /** * Kills every running, waiting, and just added jobs. * * @return {Object} Returns conrad. */ function _killAll() { var k, jobs = __extend(_jobs, _runningJobs, _waitingJobs); // Take every jobs and push them into the _doneJobs object: if (_parameters.history) for (k in jobs) { jobs[k].status = 'done'; _doneJobs.push(jobs[k]); if (typeof jobs[k].end === 'function') jobs[k].end(); } // Reinitialize the different jobs lists: _jobs = {}; _waitingJobs = {}; _runningJobs = {}; _sortedByPriorityJobs = []; // In case some jobs are added right after the kill: _isRunning = false; return this; } /** * Returns true if a job with the specified id is currently running or * waiting, and false else. * * @param {String} id The id of the job. * @return {?Object} Returns the job object if it exists. */ function _hasJob(id) { var job = _jobs[id] || _runningJobs[id] || _waitingJobs[id]; return job ? __extend(job) : null; } /** * This method will set the setting specified by "v1" to the value specified * by "v2" if both are given, and else return the current value of the * settings "v1". * * @param {String} v1 The name of the property. * @param {?*} v2 Eventually, a value to set to the specified * property. * @return {Object|*} Returns the specified settings value if "v2" is not * given, and conrad else. */ function _settings(v1, v2) { var o; if (typeof a1 === 'string' && arguments.length === 1) return _parameters[a1]; else { o = (typeof a1 === 'object' && arguments.length === 1) ? a1 || {} : {}; if (typeof a1 === 'string') o[a1] = a2; for (var k in o) if (o[k] !== undefined) _parameters[k] = o[k]; else delete _parameters[k]; return this; } } /** * Returns true if conrad is currently running, and false else. * * @return {Boolean} Returns _isRunning. */ function _getIsRunning() { return _isRunning; } /** * Unreference every jobs that are stored in the _doneJobs object. It will * not be possible anymore to get stats about these jobs, but it will release * the memory. * * @return {Object} Returns conrad. */ function _clearHistory() { _doneJobs = []; return this; } /** * Returns a snapshot of every data about jobs that wait to be started, are * currently running or are done. * * It is possible to get only running, waiting or done jobs by giving * "running", "waiting" or "done" as fist argument. * * It is also possible to get every job with a specified id by giving it as * first argument. Also, using a RegExp instead of an id will return every * jobs whose ids match the RegExp. And these two last use cases work as well * by giving before "running", "waiting" or "done". * * @return {Array} The array of the matching jobs. * * Some call examples: * ******************* * > conrad.getStats('running') * > conrad.getStats('waiting') * > conrad.getStats('done') * > conrad.getStats('myJob') * > conrad.getStats(/test/) * > conrad.getStats('running', 'myRunningJob') * > conrad.getStats('running', /test/) */ function _getStats(v1, v2) { var a, k, i, l, stats, pattern, isPatternString; if (!arguments.length) { stats = []; for (k in _jobs) stats.push(_jobs[k]); for (k in _waitingJobs) stats.push(_waitingJobs[k]); for (k in _runningJobs) stats.push(_runningJobs[k]); stats = stats.concat(_doneJobs); } if (typeof v1 === 'string') switch (v1) { case 'waiting': stats = __objectValues(_waitingJobs); break; case 'running': stats = __objectValues(_runningJobs); break; case 'done': stats = _doneJobs; break; default: pattern = v1; } if (v1 instanceof RegExp) pattern = v1; if (!pattern && (typeof v2 === 'string' || v2 instanceof RegExp)) pattern = v2; // Filter jobs if a pattern is given: if (pattern) { isPatternString = typeof pattern === 'string'; if (stats instanceof Array) { a = stats; } else if (typeof stats === 'object') { a = []; for (k in stats) a = a.concat(stats[k]); } else { a = []; for (k in _jobs) a.push(_jobs[k]); for (k in _waitingJobs) a.push(_waitingJobs[k]); for (k in _runningJobs) a.push(_runningJobs[k]); a = a.concat(_doneJobs); } stats = []; for (i = 0, l = a.length; i < l; i++) if (isPatternString ? a[i].id === pattern : a[i].id.match(pattern)) stats.push(a[i]); } return __clone(stats); } /** * TOOLS FUNCTIONS: * **************** */ /** * This function takes any number of objects as arguments, copies from each * of these objects each pair key/value into a new object, and finally * returns this object. * * The arguments are parsed from the last one to the first one, such that * when two objects have keys in common, the "earliest" object wins. * * Example: * ******** * > var o1 = { * > a: 1, * > b: 2, * > c: '3' * > }, * > o2 = { * > c: '4', * > d: [ 5 ] * > }; * > __extend(o1, o2); * > // Returns: { * > // a: 1, * > // b: 2, * > // c: '3', * > // d: [ 5 ] * > // }; * * @param {Object+} Any number of objects. * @return {Object} The merged object. */ function __extend() { var i, k, res = {}, l = arguments.length; for (i = l - 1; i >= 0; i--) for (k in arguments[i]) res[k] = arguments[i][k]; return res; } /** * This function simply clones an object. This object must contain only * objects, arrays and immutable values. Since it is not public, it does not * deal with cyclic references, DOM elements and instantiated objects - so * use it carefully. * * @param {Object} The object to clone. * @return {Object} The clone. */ function __clone(item) { var result, i, k, l; if (!item) return item; if (Array.isArray(item)) { result = []; for (i = 0, l = item.length; i < l; i++) result.push(__clone(item[i])); } else if (typeof item === 'object') { result = {}; for (i in item) result[i] = __clone(item[i]); } else result = item; return result; } /** * Returns an array containing the values of an object. * * @param {Object} The object. * @return {Array} The array of values. */ function __objectValues(o) { var k, a = []; for (k in o) a.push(o[k]); return a; } /** * A short "Date.now()" polyfill. * * @return {Number} The current time (in ms). */ function __dateNow() { return Date.now ? Date.now() : new Date().getTime(); } /** * Polyfill for the Array.isArray function: */ if (!Array.isArray) Array.isArray = function(v) { return Object.prototype.toString.call(v) === '[object Array]'; }; /** * EXPORT PUBLIC API: * ****************** */ var conrad = { hasJob: _hasJob, addJob: _addJob, killJob: _killJob, killAll: _killAll, settings: _settings, getStats: _getStats, isRunning: _getIsRunning, clearHistory: _clearHistory, // Events management: bind: _bind, unbind: _unbind, // Version: version: '0.1.0' }; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) exports = module.exports = conrad; exports.conrad = conrad; } global.conrad = conrad; })(this); // Hardcoded export for the node.js version: var sigma = this.sigma, conrad = this.conrad; sigma.conrad = conrad; // Dirty polyfills to permit sigma usage in node if (HTMLElement === undefined) var HTMLElement = function() {}; if (window === undefined) var window = { addEventListener: function() {} }; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) exports = module.exports = sigma; exports.sigma = sigma; } ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; var _root = this; // Initialize packages: sigma.utils = sigma.utils || {}; /** * MISC UTILS: */ /** * This function takes any number of objects as arguments, copies from each * of these objects each pair key/value into a new object, and finally * returns this object. * * The arguments are parsed from the last one to the first one, such that * when several objects have keys in common, the "earliest" object wins. * * Example: * ******** * > var o1 = { * > a: 1, * > b: 2, * > c: '3' * > }, * > o2 = { * > c: '4', * > d: [ 5 ] * > }; * > sigma.utils.extend(o1, o2); * > // Returns: { * > // a: 1, * > // b: 2, * > // c: '3', * > // d: [ 5 ] * > // }; * * @param {object+} Any number of objects. * @return {object} The merged object. */ sigma.utils.extend = function() { var i, k, res = {}, l = arguments.length; for (i = l - 1; i >= 0; i--) for (k in arguments[i]) res[k] = arguments[i][k]; return res; }; /** * A short "Date.now()" polyfill. * * @return {Number} The current time (in ms). */ sigma.utils.dateNow = function() { return Date.now ? Date.now() : new Date().getTime(); }; /** * Takes a package name as parameter and checks at each lebel if it exists, * and if it does not, creates it. * * Example: * ******** * > sigma.utils.pkg('a.b.c'); * > a.b.c; * > // Object {}; * > * > sigma.utils.pkg('a.b.d'); * > a.b; * > // Object { c: {}, d: {} }; * * @param {string} pkgName The name of the package to create/find. * @return {object} The related package. */ sigma.utils.pkg = function(pkgName) { return (pkgName || '').split('.').reduce(function(context, objName) { return (objName in context) ? context[objName] : (context[objName] = {}); }, _root); }; /** * Returns a unique incremental number ID. * * Example: * ******** * > sigma.utils.id(); * > // 1; * > * > sigma.utils.id(); * > // 2; * > * > sigma.utils.id(); * > // 3; * * @param {string} pkgName The name of the package to create/find. * @return {object} The related package. */ sigma.utils.id = (function() { var i = 0; return function() { return ++i; }; })(); /** * This function takes an hexa color (for instance "#ffcc00" or "#fc0") or a * rgb / rgba color (like "rgb(255,255,12)" or "rgba(255,255,12,1)") and * returns an integer equal to "r * 255 * 255 + g * 255 + b", to gain some * memory in the data given to WebGL shaders. * * @param {string} val The hexa or rgba color. * @return {number} The number value. */ sigma.utils.floatColor = function(val) { var result = [0, 0, 0]; if (val.match(/^#/)) { val = (val || '').replace(/^#/, ''); result = (val.length === 3) ? [ parseInt(val.charAt(0) + val.charAt(0), 16), parseInt(val.charAt(1) + val.charAt(1), 16), parseInt(val.charAt(2) + val.charAt(2), 16) ] : [ parseInt(val.charAt(0) + val.charAt(1), 16), parseInt(val.charAt(2) + val.charAt(3), 16), parseInt(val.charAt(4) + val.charAt(5), 16) ]; } else if (val.match(/^ *rgba? *\(/)) { val = val.match( /^ *rgba? *\( *([0-9]*) *, *([0-9]*) *, *([0-9]*) *(,.*)?\) *$/ ); result = [ +val[1], +val[2], +val[3] ]; } return ( result[0] * 256 * 256 + result[1] * 256 + result[2] ); }; /** * Perform a zoom into a camera, with or without animation, to the * coordinates indicated using a specified ratio. * * Recognized parameters: * ********************** * Here is the exhaustive list of every accepted parameters in the animation * object: * * {?number} duration An amount of time that means the duration of the * animation. If this parameter doesn't exist the * zoom will be performed without animation. * {?function} onComplete A function to perform it after the animation. It * will be performed even if there is no duration. * * @param {camera} The camera where perform the zoom. * @param {x} The X coordiantion where the zoom goes. * @param {y} The Y coordiantion where the zoom goes. * @param {ratio} The ratio to apply it to the current camera ratio. * @param {?animation} A dictionary with options for a possible animation. */ sigma.utils.zoomTo = function(camera, x, y, ratio, animation) { var settings = camera.settings, count, newRatio, animationSettings, coordinates; // Create the newRatio dealing with min / max: newRatio = Math.max( settings('zoomMin'), Math.min( settings('zoomMax'), camera.ratio * ratio ) ); // Check that the new ratio is different from the initial one: if (newRatio !== camera.ratio) { // Create the coordinates variable: ratio = newRatio / camera.ratio; coordinates = { x: x * (1 - ratio) + camera.x, y: y * (1 - ratio) + camera.y, ratio: newRatio }; if (animation && animation.duration) { // Complete the animation setings: count = sigma.misc.animation.killAll(camera); animation = sigma.utils.extend( animation, { easing: count ? 'quadraticOut' : 'quadraticInOut' } ); sigma.misc.animation.camera(camera, coordinates, animation); } else { camera.goTo(coordinates); if (animation && animation.onComplete) animation.onComplete(); } } }; /** * Return the control point coordinates for a quadratic bezier curve. * * @param {number} x1 The X coordinate of the start point. * @param {number} y1 The Y coordinate of the start point. * @param {number} x2 The X coordinate of the end point. * @param {number} y2 The Y coordinate of the end point. * @return {x,y} The control point coordinates. */ sigma.utils.getQuadraticControlPoint = function(x1, y1, x2, y2) { return { x: (x1 + x2) / 2 + (y2 - y1) / 4, y: (y1 + y2) / 2 + (x1 - x2) / 4 }; }; /** * Compute the coordinates of the point positioned * at length t in the quadratic bezier curve. * * @param {number} t In [0,1] the step percentage to reach * the point in the curve from the context point. * @param {number} x1 The X coordinate of the context point. * @param {number} y1 The Y coordinate of the context point. * @param {number} x2 The X coordinate of the ending point. * @param {number} y2 The Y coordinate of the ending point. * @param {number} xi The X coordinate of the control point. * @param {number} yi The Y coordinate of the control point. * @return {object} {x,y}. */ sigma.utils.getPointOnQuadraticCurve = function(t, x1, y1, x2, y2, xi, yi) { // http://stackoverflow.com/a/5634528 return { x: Math.pow(1 - t, 2) * x1 + 2 * (1 - t) * t * xi + Math.pow(t, 2) * x2, y: Math.pow(1 - t, 2) * y1 + 2 * (1 - t) * t * yi + Math.pow(t, 2) * y2 }; }; /** * Compute the coordinates of the point positioned * at length t in the cubic bezier curve. * * @param {number} t In [0,1] the step percentage to reach * the point in the curve from the context point. * @param {number} x1 The X coordinate of the context point. * @param {number} y1 The Y coordinate of the context point. * @param {number} x2 The X coordinate of the end point. * @param {number} y2 The Y coordinate of the end point. * @param {number} cx The X coordinate of the first control point. * @param {number} cy The Y coordinate of the first control point. * @param {number} dx The X coordinate of the second control point. * @param {number} dy The Y coordinate of the second control point. * @return {object} {x,y} The point at t. */ sigma.utils.getPointOnBezierCurve = function(t, x1, y1, x2, y2, cx, cy, dx, dy) { // http://stackoverflow.com/a/15397596 // Blending functions: var B0_t = Math.pow(1 - t, 3), B1_t = 3 * t * Math.pow(1 - t, 2), B2_t = 3 * Math.pow(t, 2) * (1 - t), B3_t = Math.pow(t, 3); return { x: (B0_t * x1) + (B1_t * cx) + (B2_t * dx) + (B3_t * x2), y: (B0_t * y1) + (B1_t * cy) + (B2_t * dy) + (B3_t * y2) }; }; /** * Return the coordinates of the two control points for a self loop (i.e. * where the start point is also the end point) computed as a cubic bezier * curve. * * @param {number} x The X coordinate of the node. * @param {number} y The Y coordinate of the node. * @param {number} size The node size. * @return {x1,y1,x2,y2} The coordinates of the two control points. */ sigma.utils.getSelfLoopControlPoints = function(x , y, size) { return { x1: x - size * 7, y1: y, x2: x, y2: y + size * 7 }; }; /** * Return the euclidian distance between two points of a plane * with an orthonormal basis. * * @param {number} x1 The X coordinate of the first point. * @param {number} y1 The Y coordinate of the first point. * @param {number} x2 The X coordinate of the second point. * @param {number} y2 The Y coordinate of the second point. * @return {number} The euclidian distance. */ sigma.utils.getDistance = function(x0, y0, x1, y1) { return Math.sqrt(Math.pow(x1 - x0, 2) + Math.pow(y1 - y0, 2)); }; /** * Return the coordinates of the intersection points of two circles. * * @param {number} x0 The X coordinate of center location of the first * circle. * @param {number} y0 The Y coordinate of center location of the first * circle. * @param {number} r0 The radius of the first circle. * @param {number} x1 The X coordinate of center location of the second * circle. * @param {number} y1 The Y coordinate of center location of the second * circle. * @param {number} r1 The radius of the second circle. * @return {xi,yi} The coordinates of the intersection points. */ sigma.utils.getCircleIntersection = function(x0, y0, r0, x1, y1, r1) { // http://stackoverflow.com/a/12219802 var a, dx, dy, d, h, rx, ry, x2, y2; // dx and dy are the vertical and horizontal distances between the circle // centers: dx = x1 - x0; dy = y1 - y0; // Determine the straight-line distance between the centers: d = Math.sqrt((dy * dy) + (dx * dx)); // Check for solvability: if (d > (r0 + r1)) { // No solution. circles do not intersect. return false; } if (d < Math.abs(r0 - r1)) { // No solution. one circle is contained in the other. return false; } //'point 2' is the point where the line through the circle intersection // points crosses the line between the circle centers. // Determine the distance from point 0 to point 2: a = ((r0 * r0) - (r1 * r1) + (d * d)) / (2.0 * d); // Determine the coordinates of point 2: x2 = x0 + (dx * a / d); y2 = y0 + (dy * a / d); // Determine the distance from point 2 to either of the intersection // points: h = Math.sqrt((r0 * r0) - (a * a)); // Determine the offsets of the intersection points from point 2: rx = -dy * (h / d); ry = dx * (h / d); // Determine the absolute intersection points: var xi = x2 + rx; var xi_prime = x2 - rx; var yi = y2 + ry; var yi_prime = y2 - ry; return {xi: xi, xi_prime: xi_prime, yi: yi, yi_prime: yi_prime}; }; /** * Check if a point is on a line segment. * * @param {number} x The X coordinate of the point to check. * @param {number} y The Y coordinate of the point to check. * @param {number} x1 The X coordinate of the line start point. * @param {number} y1 The Y coordinate of the line start point. * @param {number} x2 The X coordinate of the line end point. * @param {number} y2 The Y coordinate of the line end point. * @param {number} epsilon The precision (consider the line thickness). * @return {boolean} True if point is "close to" the line * segment, false otherwise. */ sigma.utils.isPointOnSegment = function(x, y, x1, y1, x2, y2, epsilon) { // http://stackoverflow.com/a/328122 var crossProduct = Math.abs((y - y1) * (x2 - x1) - (x - x1) * (y2 - y1)), d = sigma.utils.getDistance(x1, y1, x2, y2), nCrossProduct = crossProduct / d; // normalized cross product return (nCrossProduct < epsilon && Math.min(x1, x2) <= x && x <= Math.max(x1, x2) && Math.min(y1, y2) <= y && y <= Math.max(y1, y2)); }; /** * Check if a point is on a quadratic bezier curve segment with a thickness. * * @param {number} x The X coordinate of the point to check. * @param {number} y The Y coordinate of the point to check. * @param {number} x1 The X coordinate of the curve start point. * @param {number} y1 The Y coordinate of the curve start point. * @param {number} x2 The X coordinate of the curve end point. * @param {number} y2 The Y coordinate of the curve end point. * @param {number} cpx The X coordinate of the curve control point. * @param {number} cpy The Y coordinate of the curve control point. * @param {number} epsilon The precision (consider the line thickness). * @return {boolean} True if (x,y) is on the curve segment, * false otherwise. */ sigma.utils.isPointOnQuadraticCurve = function(x, y, x1, y1, x2, y2, cpx, cpy, epsilon) { // Fails if the point is too far from the extremities of the segment, // preventing for more costly computation: var dP1P2 = sigma.utils.getDistance(x1, y1, x2, y2); if (Math.abs(x - x1) > dP1P2 || Math.abs(y - y1) > dP1P2) { return false; } var dP1 = sigma.utils.getDistance(x, y, x1, y1), dP2 = sigma.utils.getDistance(x, y, x2, y2), t = 0.5, r = (dP1 < dP2) ? -0.01 : 0.01, rThreshold = 0.001, i = 100, pt = sigma.utils.getPointOnQuadraticCurve(t, x1, y1, x2, y2, cpx, cpy), dt = sigma.utils.getDistance(x, y, pt.x, pt.y), old_dt; // This algorithm minimizes the distance from the point to the curve. It // find the optimal t value where t=0 is the start point and t=1 is the end // point of the curve, starting from t=0.5. // It terminates because it runs a maximum of i interations. while (i-- > 0 && t >= 0 && t <= 1 && (dt > epsilon) && (r > rThreshold || r < -rThreshold)) { old_dt = dt; pt = sigma.utils.getPointOnQuadraticCurve(t, x1, y1, x2, y2, cpx, cpy); dt = sigma.utils.getDistance(x, y, pt.x, pt.y); if (dt > old_dt) { // not the right direction: // halfstep in the opposite direction r = -r / 2; t += r; } else if (t + r < 0 || t + r > 1) { // oops, we've gone too far: // revert with a halfstep r = r / 2; dt = old_dt; } else { // progress: t += r; } } return dt < epsilon; }; /** * Check if a point is on a cubic bezier curve segment with a thickness. * * @param {number} x The X coordinate of the point to check. * @param {number} y The Y coordinate of the point to check. * @param {number} x1 The X coordinate of the curve start point. * @param {number} y1 The Y coordinate of the curve start point. * @param {number} x2 The X coordinate of the curve end point. * @param {number} y2 The Y coordinate of the curve end point. * @param {number} cpx1 The X coordinate of the 1st curve control point. * @param {number} cpy1 The Y coordinate of the 1st curve control point. * @param {number} cpx2 The X coordinate of the 2nd curve control point. * @param {number} cpy2 The Y coordinate of the 2nd curve control point. * @param {number} epsilon The precision (consider the line thickness). * @return {boolean} True if (x,y) is on the curve segment, * false otherwise. */ sigma.utils.isPointOnBezierCurve = function(x, y, x1, y1, x2, y2, cpx1, cpy1, cpx2, cpy2, epsilon) { // Fails if the point is too far from the extremities of the segment, // preventing for more costly computation: var dP1CP1 = sigma.utils.getDistance(x1, y1, cpx1, cpy1); if (Math.abs(x - x1) > dP1CP1 || Math.abs(y - y1) > dP1CP1) { return false; } var dP1 = sigma.utils.getDistance(x, y, x1, y1), dP2 = sigma.utils.getDistance(x, y, x2, y2), t = 0.5, r = (dP1 < dP2) ? -0.01 : 0.01, rThreshold = 0.001, i = 100, pt = sigma.utils.getPointOnBezierCurve( t, x1, y1, x2, y2, cpx1, cpy1, cpx2, cpy2), dt = sigma.utils.getDistance(x, y, pt.x, pt.y), old_dt; // This algorithm minimizes the distance from the point to the curve. It // find the optimal t value where t=0 is the start point and t=1 is the end // point of the curve, starting from t=0.5. // It terminates because it runs a maximum of i interations. while (i-- > 0 && t >= 0 && t <= 1 && (dt > epsilon) && (r > rThreshold || r < -rThreshold)) { old_dt = dt; pt = sigma.utils.getPointOnBezierCurve( t, x1, y1, x2, y2, cpx1, cpy1, cpx2, cpy2); dt = sigma.utils.getDistance(x, y, pt.x, pt.y); if (dt > old_dt) { // not the right direction: // halfstep in the opposite direction r = -r / 2; t += r; } else if (t + r < 0 || t + r > 1) { // oops, we've gone too far: // revert with a halfstep r = r / 2; dt = old_dt; } else { // progress: t += r; } } return dt < epsilon; }; /** * ************ * EVENTS UTILS: * ************ */ /** * Here are some useful functions to unify extraction of the information we * need with mouse events and touch events, from different browsers: */ /** * Extract the local X position from a mouse or touch event. * * @param {event} e A mouse or touch event. * @return {number} The local X value of the mouse. */ sigma.utils.getX = function(e) { return ( (e.offsetX !== undefined && e.offsetX) || (e.layerX !== undefined && e.layerX) || (e.clientX !== undefined && e.clientX) ); }; /** * Extract the local Y position from a mouse or touch event. * * @param {event} e A mouse or touch event. * @return {number} The local Y value of the mouse. */ sigma.utils.getY = function(e) { return ( (e.offsetY !== undefined && e.offsetY) || (e.layerY !== undefined && e.layerY) || (e.clientY !== undefined && e.clientY) ); }; /** * Extract the width from a mouse or touch event. * * @param {event} e A mouse or touch event. * @return {number} The width of the event's target. */ sigma.utils.getWidth = function(e) { var w = (!e.target.ownerSVGElement) ? e.target.width : e.target.ownerSVGElement.width; return ( (typeof w === 'number' && w) || (w !== undefined && w.baseVal !== undefined && w.baseVal.value) ); }; /** * Extract the height from a mouse or touch event. * * @param {event} e A mouse or touch event. * @return {number} The height of the event's target. */ sigma.utils.getHeight = function(e) { var h = (!e.target.ownerSVGElement) ? e.target.height : e.target.ownerSVGElement.height; return ( (typeof h === 'number' && h) || (h !== undefined && h.baseVal !== undefined && h.baseVal.value) ); }; /** * Extract the wheel delta from a mouse or touch event. * * @param {event} e A mouse or touch event. * @return {number} The wheel delta of the mouse. */ sigma.utils.getDelta = function(e) { return ( (e.wheelDelta !== undefined && e.wheelDelta) || (e.detail !== undefined && -e.detail) ); }; /** * Returns the offset of a DOM element. * * @param {DOMElement} dom The element to retrieve the position. * @return {object} The offset of the DOM element (top, left). */ sigma.utils.getOffset = function(dom) { var left = 0, top = 0; while (dom) { top = top + parseInt(dom.offsetTop); left = left + parseInt(dom.offsetLeft); dom = dom.offsetParent; } return { top: top, left: left }; }; /** * Simulates a "double click" event. * * @param {HTMLElement} target The event target. * @param {string} type The event type. * @param {function} callback The callback to execute. */ sigma.utils.doubleClick = function(target, type, callback) { var clicks = 0, self = this, handlers; target._doubleClickHandler = target._doubleClickHandler || {}; target._doubleClickHandler[type] = target._doubleClickHandler[type] || []; handlers = target._doubleClickHandler[type]; handlers.push(function(e) { clicks++; if (clicks === 2) { clicks = 0; return callback(e); } else if (clicks === 1) { setTimeout(function() { clicks = 0; }, sigma.settings.doubleClickTimeout); } }); target.addEventListener(type, handlers[handlers.length - 1], false); }; /** * Unbind simulated "double click" events. * * @param {HTMLElement} target The event target. * @param {string} type The event type. */ sigma.utils.unbindDoubleClick = function(target, type) { var handler, handlers = (target._doubleClickHandler || {})[type] || []; while ((handler = handlers.pop())) { target.removeEventListener(type, handler); } delete (target._doubleClickHandler || {})[type]; }; /** * Here are just some of the most basic easing functions, used for the * animated camera "goTo" calls. * * If you need some more easings functions, don't hesitate to add them to * sigma.utils.easings. But I will not add some more here or merge PRs * containing, because I do not want sigma sources full of overkill and never * used stuff... */ sigma.utils.easings = sigma.utils.easings || {}; sigma.utils.easings.linearNone = function(k) { return k; }; sigma.utils.easings.quadraticIn = function(k) { return k * k; }; sigma.utils.easings.quadraticOut = function(k) { return k * (2 - k); }; sigma.utils.easings.quadraticInOut = function(k) { if ((k *= 2) < 1) return 0.5 * k * k; return - 0.5 * (--k * (k - 2) - 1); }; sigma.utils.easings.cubicIn = function(k) { return k * k * k; }; sigma.utils.easings.cubicOut = function(k) { return --k * k * k + 1; }; sigma.utils.easings.cubicInOut = function(k) { if ((k *= 2) < 1) return 0.5 * k * k * k; return 0.5 * ((k -= 2) * k * k + 2); }; /** * ************ * WEBGL UTILS: * ************ */ /** * Loads a WebGL shader and returns it. * * @param {WebGLContext} gl The WebGLContext to use. * @param {string} shaderSource The shader source. * @param {number} shaderType The type of shader. * @param {function(string): void} error Callback for errors. * @return {WebGLShader} The created shader. */ sigma.utils.loadShader = function(gl, shaderSource, shaderType, error) { var compiled, shader = gl.createShader(shaderType); // Load the shader source gl.shaderSource(shader, shaderSource); // Compile the shader gl.compileShader(shader); // Check the compile status compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); // If something went wrong: if (!compiled) { if (error) { error( 'Error compiling shader "' + shader + '":' + gl.getShaderInfoLog(shader) ); } gl.deleteShader(shader); return null; } return shader; }; /** * Creates a program, attaches shaders, binds attrib locations, links the * program and calls useProgram. * * @param {Array.<WebGLShader>} shaders The shaders to attach. * @param {Array.<string>} attribs The attribs names. * @param {Array.<number>} locations The locations for the attribs. * @param {function(string): void} error Callback for errors. * @return {WebGLProgram} The created program. */ sigma.utils.loadProgram = function(gl, shaders, attribs, loc, error) { var i, linked, program = gl.createProgram(); for (i = 0; i < shaders.length; ++i) gl.attachShader(program, shaders[i]); if (attribs) for (i = 0; i < attribs.length; ++i) gl.bindAttribLocation( program, locations ? locations[i] : i, opt_attribs[i] ); gl.linkProgram(program); // Check the link status linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { if (error) error('Error in program linking: ' + gl.getProgramInfoLog(program)); gl.deleteProgram(program); return null; } return program; }; /** * ********* * MATRICES: * ********* * The following utils are just here to help generating the transformation * matrices for the WebGL renderers. */ sigma.utils.pkg('sigma.utils.matrices'); /** * The returns a 3x3 translation matrix. * * @param {number} dx The X translation. * @param {number} dy The Y translation. * @return {array} Returns the matrix. */ sigma.utils.matrices.translation = function(dx, dy) { return [ 1, 0, 0, 0, 1, 0, dx, dy, 1 ]; }; /** * The returns a 3x3 or 2x2 rotation matrix. * * @param {number} angle The rotation angle. * @param {boolean} m2 If true, the function will return a 2x2 matrix. * @return {array} Returns the matrix. */ sigma.utils.matrices.rotation = function(angle, m2) { var cos = Math.cos(angle), sin = Math.sin(angle); return m2 ? [ cos, -sin, sin, cos ] : [ cos, -sin, 0, sin, cos, 0, 0, 0, 1 ]; }; /** * The returns a 3x3 or 2x2 homothetic transformation matrix. * * @param {number} ratio The scaling ratio. * @param {boolean} m2 If true, the function will return a 2x2 matrix. * @return {array} Returns the matrix. */ sigma.utils.matrices.scale = function(ratio, m2) { return m2 ? [ ratio, 0, 0, ratio ] : [ ratio, 0, 0, 0, ratio, 0, 0, 0, 1 ]; }; /** * The returns a 3x3 or 2x2 homothetic transformation matrix. * * @param {array} a The first matrix. * @param {array} b The second matrix. * @param {boolean} m2 If true, the function will assume both matrices are * 2x2. * @return {array} Returns the matrix. */ sigma.utils.matrices.multiply = function(a, b, m2) { var l = m2 ? 2 : 3, a00 = a[0 * l + 0], a01 = a[0 * l + 1], a02 = a[0 * l + 2], a10 = a[1 * l + 0], a11 = a[1 * l + 1], a12 = a[1 * l + 2], a20 = a[2 * l + 0], a21 = a[2 * l + 1], a22 = a[2 * l + 2], b00 = b[0 * l + 0], b01 = b[0 * l + 1], b02 = b[0 * l + 2], b10 = b[1 * l + 0], b11 = b[1 * l + 1], b12 = b[1 * l + 2], b20 = b[2 * l + 0], b21 = b[2 * l + 1], b22 = b[2 * l + 2]; return m2 ? [ a00 * b00 + a01 * b10, a00 * b01 + a01 * b11, a10 * b00 + a11 * b10, a10 * b01 + a11 * b11 ] : [ a00 * b00 + a01 * b10 + a02 * b20, a00 * b01 + a01 * b11 + a02 * b21, a00 * b02 + a01 * b12 + a02 * b22, a10 * b00 + a11 * b10 + a12 * b20, a10 * b01 + a11 * b11 + a12 * b21, a10 * b02 + a11 * b12 + a12 * b22, a20 * b00 + a21 * b10 + a22 * b20, a20 * b01 + a21 * b11 + a22 * b21, a20 * b02 + a21 * b12 + a22 * b22 ]; }; }).call(this); ;(function(global) { 'use strict'; /** * http://paulirish.com/2011/requestanimationframe-for-smart-animating/ * http://my.opera.com/emoller/blog/2011/12/20/requestanimationframe-for-smart-er-animating * requestAnimationFrame polyfill by Erik Möller. * fixes from Paul Irish and Tino Zijdel * MIT license */ var x, lastTime = 0, vendors = ['ms', 'moz', 'webkit', 'o']; for (x = 0; x < vendors.length && !global.requestAnimationFrame; x++) { global.requestAnimationFrame = global[vendors[x] + 'RequestAnimationFrame']; global.cancelAnimationFrame = global[vendors[x] + 'CancelAnimationFrame'] || global[vendors[x] + 'CancelRequestAnimationFrame']; } if (!global.requestAnimationFrame) global.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(), timeToCall = Math.max(0, 16 - (currTime - lastTime)), id = global.setTimeout( function() { callback(currTime + timeToCall); }, timeToCall ); lastTime = currTime + timeToCall; return id; }; if (!global.cancelAnimationFrame) global.cancelAnimationFrame = function(id) { clearTimeout(id); }; /** * Function.prototype.bind polyfill found on MDN. * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Compatibility * Public domain */ if (!Function.prototype.bind) Function.prototype.bind = function(oThis) { if (typeof this !== 'function') // Closest thing possible to the ECMAScript 5 internal IsCallable // function: throw new TypeError( 'Function.prototype.bind - what is trying to be bound is not callable' ); var aArgs = Array.prototype.slice.call(arguments, 1), fToBind = this, fNOP, fBound; fNOP = function() {}; fBound = function() { return fToBind.apply( this instanceof fNOP && oThis ? this : oThis, aArgs.concat(Array.prototype.slice.call(arguments)) ); }; fNOP.prototype = this.prototype; fBound.prototype = new fNOP(); return fBound; }; })(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Packages initialization: sigma.utils.pkg('sigma.settings'); var settings = { /** * GRAPH SETTINGS: * *************** */ // {boolean} Indicates if the data have to be cloned in methods to add // nodes or edges. clone: true, // {boolean} Indicates if nodes "id" values and edges "id", "source" and // "target" values must be set as immutable. immutable: true, // {boolean} Indicates if sigma can log its errors and warnings. verbose: false, /** * RENDERERS SETTINGS: * ******************* */ // {string} classPrefix: 'sigma', // {string} defaultNodeType: 'def', // {string} defaultEdgeType: 'def', // {string} defaultLabelColor: '#000', // {string} defaultEdgeColor: '#000', // {string} defaultNodeColor: '#000', // {string} defaultLabelSize: 14, // {string} Indicates how to choose the edges color. Available values: // "source", "target", "default" edgeColor: 'source', // {number} Defines the minimal edge's arrow display size. minArrowSize: 0, // {string} font: 'arial', // {string} Example: 'bold' fontStyle: '', // {string} Indicates how to choose the labels color. Available values: // "node", "default" labelColor: 'default', // {string} Indicates how to choose the labels size. Available values: // "fixed", "proportional" labelSize: 'fixed', // {string} The ratio between the font size of the label and the node size. labelSizeRatio: 1, // {number} The minimum size a node must have to see its label displayed. labelThreshold: 8, // {number} The oversampling factor used in WebGL renderer. webglOversamplingRatio: 2, // {number} The size of the border of hovered nodes. borderSize: 0, // {number} The default hovered node border's color. defaultNodeBorderColor: '#000', // {number} The hovered node's label font. If not specified, will heritate // the "font" value. hoverFont: '', // {boolean} If true, then only one node can be hovered at a time. singleHover: true, // {string} Example: 'bold' hoverFontStyle: '', // {string} Indicates how to choose the hovered nodes shadow color. // Available values: "node", "default" labelHoverShadow: 'default', // {string} labelHoverShadowColor: '#000', // {string} Indicates how to choose the hovered nodes color. // Available values: "node", "default" nodeHoverColor: 'node', // {string} defaultNodeHoverColor: '#000', // {string} Indicates how to choose the hovered nodes background color. // Available values: "node", "default" labelHoverBGColor: 'default', // {string} defaultHoverLabelBGColor: '#fff', // {string} Indicates how to choose the hovered labels color. // Available values: "node", "default" labelHoverColor: 'default', // {string} defaultLabelHoverColor: '#000', // {string} Indicates how to choose the edges hover color. Available values: // "edge", "default" edgeHoverColor: 'edge', // {number} The size multiplicator of hovered edges. edgeHoverSizeRatio: 1, // {string} defaultEdgeHoverColor: '#000', // {boolean} Indicates if the edge extremities must be hovered when the // edge is hovered. edgeHoverExtremities: false, // {booleans} The different drawing modes: // false: Layered not displayed. // true: Layered displayed. drawEdges: true, drawNodes: true, drawLabels: true, drawEdgeLabels: false, // {boolean} Indicates if the edges must be drawn in several frames or in // one frame, as the nodes and labels are drawn. batchEdgesDrawing: false, // {boolean} Indicates if the edges must be hidden during dragging and // animations. hideEdgesOnMove: false, // {numbers} The different batch sizes, when elements are displayed in // several frames. canvasEdgesBatchSize: 500, webglEdgesBatchSize: 1000, /** * RESCALE SETTINGS: * ***************** */ // {string} Indicates of to scale the graph relatively to its container. // Available values: "inside", "outside" scalingMode: 'inside', // {number} The margin to keep around the graph. sideMargin: 0, // {number} Determine the size of the smallest and the biggest node / edges // on the screen. This mapping makes easier to display the graph, // avoiding too big nodes that take half of the screen, or too // small ones that are not readable. If the two parameters are // equals, then the minimal display size will be 0. And if they // are both equal to 0, then there is no mapping, and the radius // of the nodes will be their size. minEdgeSize: 0.5, maxEdgeSize: 1, minNodeSize: 1, maxNodeSize: 8, /** * CAPTORS SETTINGS: * ***************** */ // {boolean} touchEnabled: true, // {boolean} mouseEnabled: true, // {boolean} mouseWheelEnabled: true, // {boolean} doubleClickEnabled: true, // {boolean} Defines whether the custom events such as "clickNode" can be // used. eventsEnabled: true, // {number} Defines by how much multiplicating the zooming level when the // user zooms with the mouse-wheel. zoomingRatio: 1.7, // {number} Defines by how much multiplicating the zooming level when the // user zooms by double clicking. doubleClickZoomingRatio: 2.2, // {number} The minimum zooming level. zoomMin: 0.0625, // {number} The maximum zooming level. zoomMax: 2, // {number} The duration of animations following a mouse scrolling. mouseZoomDuration: 200, // {number} The duration of animations following a mouse double click. doubleClickZoomDuration: 200, // {number} The duration of animations following a mouse dropping. mouseInertiaDuration: 200, // {number} The inertia power (mouse captor). mouseInertiaRatio: 3, // {number} The duration of animations following a touch dropping. touchInertiaDuration: 200, // {number} The inertia power (touch captor). touchInertiaRatio: 3, // {number} The maximum time between two clicks to make it a double click. doubleClickTimeout: 300, // {number} The maximum time between two taps to make it a double tap. doubleTapTimeout: 300, // {number} The maximum time of dragging to trigger intertia. dragTimeout: 200, /** * GLOBAL SETTINGS: * **************** */ // {boolean} Determines whether the instance has to refresh itself // automatically when a "resize" event is dispatched from the // window object. autoResize: true, // {boolean} Determines whether the "rescale" middleware has to be called // automatically for each camera on refresh. autoRescale: true, // {boolean} If set to false, the camera method "goTo" will basically do // nothing. enableCamera: true, // {boolean} If set to false, the nodes cannot be hovered. enableHovering: true, // {boolean} If set to true, the edges can be hovered. enableEdgeHovering: false, // {number} The size of the area around the edges to activate hovering. edgeHoverPrecision: 5, // {boolean} If set to true, the rescale middleware will ignore node sizes // to determine the graphs boundings. rescaleIgnoreSize: false, // {boolean} Determines if the core has to try to catch errors on // rendering. skipErrors: false, /** * CAMERA SETTINGS: * **************** */ // {number} The power degrees applied to the nodes/edges size relatively to // the zooming level. Basically: // > onScreenR = Math.pow(zoom, nodesPowRatio) * R // > onScreenT = Math.pow(zoom, edgesPowRatio) * T nodesPowRatio: 0.5, edgesPowRatio: 0.5, /** * ANIMATIONS SETTINGS: * ******************** */ // {number} The default animation time. animationsTime: 200 }; // Export the previously designed settings: sigma.settings = sigma.utils.extend(sigma.settings || {}, settings); }).call(this); ;(function() { 'use strict'; /** * Dispatcher constructor. * * @return {dispatcher} The new dispatcher instance. */ var dispatcher = function() { Object.defineProperty(this, '_handlers', { value: {} }); }; /** * Will execute the handler everytime that the indicated event (or the * indicated events) will be triggered. * * @param {string} events The name of the event (or the events * separated by spaces). * @param {function(Object)} handler The handler to bind. * @return {dispatcher} Returns the instance itself. */ dispatcher.prototype.bind = function(events, handler) { var i, l, event, eArray; if ( arguments.length === 1 && typeof arguments[0] === 'object' ) for (events in arguments[0]) this.bind(events, arguments[0][events]); else if ( arguments.length === 2 && typeof arguments[1] === 'function' ) { eArray = typeof events === 'string' ? events.split(' ') : events; for (i = 0, l = eArray.length; i !== l; i += 1) { event = eArray[i]; // Check that event is not '': if (!event) continue; if (!this._handlers[event]) this._handlers[event] = []; // Using an object instead of directly the handler will make possible // later to add flags this._handlers[event].push({ handler: handler }); } } else throw 'bind: Wrong arguments.'; return this; }; /** * Removes the handler from a specified event (or specified events). * * @param {?string} events The name of the event (or the events * separated by spaces). If undefined, * then all handlers are removed. * @param {?function(object)} handler The handler to unbind. If undefined, * each handler bound to the event or the * events will be removed. * @return {dispatcher} Returns the instance itself. */ dispatcher.prototype.unbind = function(events, handler) { var i, n, j, m, k, a, event, eArray = typeof events === 'string' ? events.split(' ') : events; if (!arguments.length) { for (k in this._handlers) delete this._handlers[k]; return this; } if (handler) { for (i = 0, n = eArray.length; i !== n; i += 1) { event = eArray[i]; if (this._handlers[event]) { a = []; for (j = 0, m = this._handlers[event].length; j !== m; j += 1) if (this._handlers[event][j].handler !== handler) a.push(this._handlers[event][j]); this._handlers[event] = a; } if (this._handlers[event] && this._handlers[event].length === 0) delete this._handlers[event]; } } else for (i = 0, n = eArray.length; i !== n; i += 1) delete this._handlers[eArray[i]]; return this; }; /** * Executes each handler bound to the event * * @param {string} events The name of the event (or the events separated * by spaces). * @param {?object} data The content of the event (optional). * @return {dispatcher} Returns the instance itself. */ dispatcher.prototype.dispatchEvent = function(events, data) { var i, n, j, m, a, event, eventName, self = this, eArray = typeof events === 'string' ? events.split(' ') : events; data = data === undefined ? {} : data; for (i = 0, n = eArray.length; i !== n; i += 1) { eventName = eArray[i]; if (this._handlers[eventName]) { event = self.getEvent(eventName, data); a = []; for (j = 0, m = this._handlers[eventName].length; j !== m; j += 1) { this._handlers[eventName][j].handler(event); if (!this._handlers[eventName][j].one) a.push(this._handlers[eventName][j]); } this._handlers[eventName] = a; } } return this; }; /** * Return an event object. * * @param {string} events The name of the event. * @param {?object} data The content of the event (optional). * @return {object} Returns the instance itself. */ dispatcher.prototype.getEvent = function(event, data) { return { type: event, data: data || {}, target: this }; }; /** * A useful function to deal with inheritance. It will make the target * inherit the prototype of the class dispatcher as well as its constructor. * * @param {object} target The target. */ dispatcher.extend = function(target, args) { var k; for (k in dispatcher.prototype) if (dispatcher.prototype.hasOwnProperty(k)) target[k] = dispatcher.prototype[k]; dispatcher.apply(target, args); }; /** * EXPORT: * ******* */ if (typeof this.sigma !== 'undefined') { this.sigma.classes = this.sigma.classes || {}; this.sigma.classes.dispatcher = dispatcher; } else if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) exports = module.exports = dispatcher; exports.dispatcher = dispatcher; } else this.dispatcher = dispatcher; }).call(this); ;(function() { 'use strict'; /** * This utils aims to facilitate the manipulation of each instance setting. * Using a function instead of an object brings two main advantages: First, * it will be easier in the future to catch settings updates through a * function than an object. Second, giving it a full object will "merge" it * to the settings object properly, keeping us to have to always add a loop. * * @return {configurable} The "settings" function. */ var configurable = function() { var i, l, data = {}, datas = Array.prototype.slice.call(arguments, 0); /** * The method to use to set or get any property of this instance. * * @param {string|object} a1 If it is a string and if a2 is undefined, * then it will return the corresponding * property. If it is a string and if a2 is * set, then it will set a2 as the property * corresponding to a1, and return this. If * it is an object, then each pair string + * object(or any other type) will be set as a * property. * @param {*?} a2 The new property corresponding to a1 if a1 * is a string. * @return {*|configurable} Returns itself or the corresponding * property. * * Polymorphism: * ************* * Here are some basic use examples: * * > settings = new configurable(); * > settings('mySetting', 42); * > settings('mySetting'); // Logs: 42 * > settings('mySetting', 123); * > settings('mySetting'); // Logs: 123 * > settings({mySetting: 456}); * > settings('mySetting'); // Logs: 456 * * Also, it is possible to use the function as a fallback: * > settings({mySetting: 'abc'}, 'mySetting'); // Logs: 'abc' * > settings({hisSetting: 'abc'}, 'mySetting'); // Logs: 456 */ var settings = function(a1, a2) { var o, i, l, k; if (arguments.length === 1 && typeof a1 === 'string') { if (data[a1] !== undefined) return data[a1]; for (i = 0, l = datas.length; i < l; i++) if (datas[i][a1] !== undefined) return datas[i][a1]; return undefined; } else if (typeof a1 === 'object' && typeof a2 === 'string') { return (a1 || {})[a2] !== undefined ? a1[a2] : settings(a2); } else { o = (typeof a1 === 'object' && a2 === undefined) ? a1 : {}; if (typeof a1 === 'string') o[a1] = a2; for (i = 0, k = Object.keys(o), l = k.length; i < l; i++) data[k[i]] = o[k[i]]; return this; } }; /** * This method returns a new configurable function, with new objects * * @param {object*} Any number of objects to search in. * @return {function} Returns the function. Check its documentation to know * more about how it works. */ settings.embedObjects = function() { var args = datas.concat( data ).concat( Array.prototype.splice.call(arguments, 0) ); return configurable.apply({}, args); }; // Initialize for (i = 0, l = arguments.length; i < l; i++) settings(arguments[i]); return settings; }; /** * EXPORT: * ******* */ if (typeof this.sigma !== 'undefined') { this.sigma.classes = this.sigma.classes || {}; this.sigma.classes.configurable = configurable; } else if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) exports = module.exports = configurable; exports.configurable = configurable; } else this.configurable = configurable; }).call(this); ;(function(undefined) { 'use strict'; var _methods = Object.create(null), _indexes = Object.create(null), _initBindings = Object.create(null), _methodBindings = Object.create(null), _methodBeforeBindings = Object.create(null), _defaultSettings = { immutable: true, clone: true }, _defaultSettingsFunction = function(key) { return _defaultSettings[key]; }; /** * The graph constructor. It initializes the data and the indexes, and binds * the custom indexes and methods to its own scope. * * Recognized parameters: * ********************** * Here is the exhaustive list of every accepted parameters in the settings * object: * * {boolean} clone Indicates if the data have to be cloned in methods * to add nodes or edges. * {boolean} immutable Indicates if nodes "id" values and edges "id", * "source" and "target" values must be set as * immutable. * * @param {?configurable} settings Eventually a settings function. * @return {graph} The new graph instance. */ var graph = function(settings) { var k, fn, data; /** * DATA: * ***** * Every data that is callable from graph methods are stored in this "data" * object. This object will be served as context for all these methods, * and it is possible to add other type of data in it. */ data = { /** * SETTINGS FUNCTION: * ****************** */ settings: settings || _defaultSettingsFunction, /** * MAIN DATA: * ********** */ nodesArray: [], edgesArray: [], /** * GLOBAL INDEXES: * *************** * These indexes just index data by ids. */ nodesIndex: Object.create(null), edgesIndex: Object.create(null), /** * LOCAL INDEXES: * ************** * These indexes refer from node to nodes. Each key is an id, and each * value is the array of the ids of related nodes. */ inNeighborsIndex: Object.create(null), outNeighborsIndex: Object.create(null), allNeighborsIndex: Object.create(null), inNeighborsCount: Object.create(null), outNeighborsCount: Object.create(null), allNeighborsCount: Object.create(null) }; // Execute bindings: for (k in _initBindings) _initBindings[k].call(data); // Add methods to both the scope and the data objects: for (k in _methods) { fn = __bindGraphMethod(k, data, _methods[k]); this[k] = fn; data[k] = fn; } }; /** * A custom tool to bind methods such that function that are bound to it will * be executed anytime the method is called. * * @param {string} methodName The name of the method to bind. * @param {object} scope The scope where the method must be executed. * @param {function} fn The method itself. * @return {function} The new method. */ function __bindGraphMethod(methodName, scope, fn) { var result = function() { var k, res; // Execute "before" bound functions: for (k in _methodBeforeBindings[methodName]) _methodBeforeBindings[methodName][k].apply(scope, arguments); // Apply the method: res = fn.apply(scope, arguments); // Execute bound functions: for (k in _methodBindings[methodName]) _methodBindings[methodName][k].apply(scope, arguments); // Return res: return res; }; return result; } /** * This custom tool function removes every pair key/value from an hash. The * goal is to avoid creating a new object while some other references are * still hanging in some scopes... * * @param {object} obj The object to empty. * @return {object} The empty object. */ function __emptyObject(obj) { var k; for (k in obj) if (!('hasOwnProperty' in obj) || obj.hasOwnProperty(k)) delete obj[k]; return obj; } /** * This global method adds a method that will be bound to the futurly created * graph instances. * * Since these methods will be bound to their scope when the instances are * created, it does not use the prototype. Because of that, methods have to * be added before instances are created to make them available. * * Here is an example: * * > graph.addMethod('getNodesCount', function() { * > return this.nodesArray.length; * > }); * > * > var myGraph = new graph(); * > console.log(myGraph.getNodesCount()); // outputs 0 * * @param {string} methodName The name of the method. * @param {function} fn The method itself. * @return {object} The global graph constructor. */ graph.addMethod = function(methodName, fn) { if ( typeof methodName !== 'string' || typeof fn !== 'function' || arguments.length !== 2 ) throw 'addMethod: Wrong arguments.'; if (_methods[methodName] || graph[methodName]) throw 'The method "' + methodName + '" already exists.'; _methods[methodName] = fn; _methodBindings[methodName] = Object.create(null); _methodBeforeBindings[methodName] = Object.create(null); return this; }; /** * This global method returns true if the method has already been added, and * false else. * * Here are some examples: * * > graph.hasMethod('addNode'); // returns true * > graph.hasMethod('hasMethod'); // returns true * > graph.hasMethod('unexistingMethod'); // returns false * * @param {string} methodName The name of the method. * @return {boolean} The result. */ graph.hasMethod = function(methodName) { return !!(_methods[methodName] || graph[methodName]); }; /** * This global methods attaches a function to a method. Anytime the specified * method is called, the attached function is called right after, with the * same arguments and in the same scope. The attached function is called * right before if the last argument is true, unless the method is the graph * constructor. * * To attach a function to the graph constructor, use 'constructor' as the * method name (first argument). * * The main idea is to have a clean way to keep custom indexes up to date, * for instance: * * > var timesAddNodeCalled = 0; * > graph.attach('addNode', 'timesAddNodeCalledInc', function() { * > timesAddNodeCalled++; * > }); * > * > var myGraph = new graph(); * > console.log(timesAddNodeCalled); // outputs 0 * > * > myGraph.addNode({ id: '1' }).addNode({ id: '2' }); * > console.log(timesAddNodeCalled); // outputs 2 * * The idea for calling a function before is to provide pre-processors, for * instance: * * > var colorPalette = { Person: '#C3CBE1', Place: '#9BDEBD' }; * > graph.attach('addNode', 'applyNodeColorPalette', function(n) { * > n.color = colorPalette[n.category]; * > }, true); * > * > var myGraph = new graph(); * > myGraph.addNode({ id: 'n0', category: 'Person' }); * > console.log(myGraph.nodes('n0').color); // outputs '#C3CBE1' * * @param {string} methodName The name of the related method or * "constructor". * @param {string} key The key to identify the function to attach. * @param {function} fn The function to bind. * @param {boolean} before If true the function is called right before. * @return {object} The global graph constructor. */ graph.attach = function(methodName, key, fn, before) { if ( typeof methodName !== 'string' || typeof key !== 'string' || typeof fn !== 'function' || arguments.length < 3 || arguments.length > 4 ) throw 'attach: Wrong arguments.'; var bindings; if (methodName === 'constructor') bindings = _initBindings; else { if (before) { if (!_methodBeforeBindings[methodName]) throw 'The method "' + methodName + '" does not exist.'; bindings = _methodBeforeBindings[methodName]; } else { if (!_methodBindings[methodName]) throw 'The method "' + methodName + '" does not exist.'; bindings = _methodBindings[methodName]; } } if (bindings[key]) throw 'A function "' + key + '" is already attached ' + 'to the method "' + methodName + '".'; bindings[key] = fn; return this; }; /** * Alias of attach(methodName, key, fn, true). */ graph.attachBefore = function(methodName, key, fn) { return this.attach(methodName, key, fn, true); }; /** * This methods is just an helper to deal with custom indexes. It takes as * arguments the name of the index and an object containing all the different * functions to bind to the methods. * * Here is a basic example, that creates an index to keep the number of nodes * in the current graph. It also adds a method to provide a getter on that * new index: * * > sigma.classes.graph.addIndex('nodesCount', { * > constructor: function() { * > this.nodesCount = 0; * > }, * > addNode: function() { * > this.nodesCount++; * > }, * > dropNode: function() { * > this.nodesCount--; * > } * > }); * > * > sigma.classes.graph.addMethod('getNodesCount', function() { * > return this.nodesCount; * > }); * > * > var myGraph = new sigma.classes.graph(); * > console.log(myGraph.getNodesCount()); // outputs 0 * > * > myGraph.addNode({ id: '1' }).addNode({ id: '2' }); * > console.log(myGraph.getNodesCount()); // outputs 2 * * @param {string} name The name of the index. * @param {object} bindings The object containing the functions to bind. * @return {object} The global graph constructor. */ graph.addIndex = function(name, bindings) { if ( typeof name !== 'string' || Object(bindings) !== bindings || arguments.length !== 2 ) throw 'addIndex: Wrong arguments.'; if (_indexes[name]) throw 'The index "' + name + '" already exists.'; var k; // Store the bindings: _indexes[name] = bindings; // Attach the bindings: for (k in bindings) if (typeof bindings[k] !== 'function') throw 'The bindings must be functions.'; else graph.attach(k, name, bindings[k]); return this; }; /** * This method adds a node to the graph. The node must be an object, with a * string under the key "id". Except for this, it is possible to add any * other attribute, that will be preserved all along the manipulations. * * If the graph option "clone" has a truthy value, the node will be cloned * when added to the graph. Also, if the graph option "immutable" has a * truthy value, its id will be defined as immutable. * * @param {object} node The node to add. * @return {object} The graph instance. */ graph.addMethod('addNode', function(node) { // Check that the node is an object and has an id: if (Object(node) !== node || arguments.length !== 1) throw 'addNode: Wrong arguments.'; if (typeof node.id !== 'string' && typeof node.id !== 'number') throw 'The node must have a string or number id.'; if (this.nodesIndex[node.id]) throw 'The node "' + node.id + '" already exists.'; var k, id = node.id, validNode = Object.create(null); // Check the "clone" option: if (this.settings('clone')) { for (k in node) if (k !== 'id') validNode[k] = node[k]; } else validNode = node; // Check the "immutable" option: if (this.settings('immutable')) Object.defineProperty(validNode, 'id', { value: id, enumerable: true }); else validNode.id = id; // Add empty containers for edges indexes: this.inNeighborsIndex[id] = Object.create(null); this.outNeighborsIndex[id] = Object.create(null); this.allNeighborsIndex[id] = Object.create(null); this.inNeighborsCount[id] = 0; this.outNeighborsCount[id] = 0; this.allNeighborsCount[id] = 0; // Add the node to indexes: this.nodesArray.push(validNode); this.nodesIndex[validNode.id] = validNode; // Return the current instance: return this; }); /** * This method adds an edge to the graph. The edge must be an object, with a * string under the key "id", and strings under the keys "source" and * "target" that design existing nodes. Except for this, it is possible to * add any other attribute, that will be preserved all along the * manipulations. * * If the graph option "clone" has a truthy value, the edge will be cloned * when added to the graph. Also, if the graph option "immutable" has a * truthy value, its id, source and target will be defined as immutable. * * @param {object} edge The edge to add. * @return {object} The graph instance. */ graph.addMethod('addEdge', function(edge) { // Check that the edge is an object and has an id: if (Object(edge) !== edge || arguments.length !== 1) throw 'addEdge: Wrong arguments.'; if (typeof edge.id !== 'string' && typeof edge.id !== 'number') throw 'The edge must have a string or number id.'; if ((typeof edge.source !== 'string' && typeof edge.source !== 'number') || !this.nodesIndex[edge.source]) throw 'The edge source must have an existing node id.'; if ((typeof edge.target !== 'string' && typeof edge.target !== 'number') || !this.nodesIndex[edge.target]) throw 'The edge target must have an existing node id.'; if (this.edgesIndex[edge.id]) throw 'The edge "' + edge.id + '" already exists.'; var k, validEdge = Object.create(null); // Check the "clone" option: if (this.settings('clone')) { for (k in edge) if (k !== 'id' && k !== 'source' && k !== 'target') validEdge[k] = edge[k]; } else validEdge = edge; // Check the "immutable" option: if (this.settings('immutable')) { Object.defineProperty(validEdge, 'id', { value: edge.id, enumerable: true }); Object.defineProperty(validEdge, 'source', { value: edge.source, enumerable: true }); Object.defineProperty(validEdge, 'target', { value: edge.target, enumerable: true }); } else { validEdge.id = edge.id; validEdge.source = edge.source; validEdge.target = edge.target; } // Add the edge to indexes: this.edgesArray.push(validEdge); this.edgesIndex[validEdge.id] = validEdge; if (!this.inNeighborsIndex[validEdge.target][validEdge.source]) this.inNeighborsIndex[validEdge.target][validEdge.source] = Object.create(null); this.inNeighborsIndex[validEdge.target][validEdge.source][validEdge.id] = validEdge; if (!this.outNeighborsIndex[validEdge.source][validEdge.target]) this.outNeighborsIndex[validEdge.source][validEdge.target] = Object.create(null); this.outNeighborsIndex[validEdge.source][validEdge.target][validEdge.id] = validEdge; if (!this.allNeighborsIndex[validEdge.source][validEdge.target]) this.allNeighborsIndex[validEdge.source][validEdge.target] = Object.create(null); this.allNeighborsIndex[validEdge.source][validEdge.target][validEdge.id] = validEdge; if (validEdge.target !== validEdge.source) { if (!this.allNeighborsIndex[validEdge.target][validEdge.source]) this.allNeighborsIndex[validEdge.target][validEdge.source] = Object.create(null); this.allNeighborsIndex[validEdge.target][validEdge.source][validEdge.id] = validEdge; } // Keep counts up to date: this.inNeighborsCount[validEdge.target]++; this.outNeighborsCount[validEdge.source]++; this.allNeighborsCount[validEdge.target]++; this.allNeighborsCount[validEdge.source]++; return this; }); /** * This method drops a node from the graph. It also removes each edge that is * bound to it, through the dropEdge method. An error is thrown if the node * does not exist. * * @param {string} id The node id. * @return {object} The graph instance. */ graph.addMethod('dropNode', function(id) { // Check that the arguments are valid: if ((typeof id !== 'string' && typeof id !== 'number') || arguments.length !== 1) throw 'dropNode: Wrong arguments.'; if (!this.nodesIndex[id]) throw 'The node "' + id + '" does not exist.'; var i, k, l; // Remove the node from indexes: delete this.nodesIndex[id]; for (i = 0, l = this.nodesArray.length; i < l; i++) if (this.nodesArray[i].id === id) { this.nodesArray.splice(i, 1); break; } // Remove related edges: for (i = this.edgesArray.length - 1; i >= 0; i--) if (this.edgesArray[i].source === id || this.edgesArray[i].target === id) this.dropEdge(this.edgesArray[i].id); // Remove related edge indexes: delete this.inNeighborsIndex[id]; delete this.outNeighborsIndex[id]; delete this.allNeighborsIndex[id]; delete this.inNeighborsCount[id]; delete this.outNeighborsCount[id]; delete this.allNeighborsCount[id]; for (k in this.nodesIndex) { delete this.inNeighborsIndex[k][id]; delete this.outNeighborsIndex[k][id]; delete this.allNeighborsIndex[k][id]; } return this; }); /** * This method drops an edge from the graph. An error is thrown if the edge * does not exist. * * @param {string} id The edge id. * @return {object} The graph instance. */ graph.addMethod('dropEdge', function(id) { // Check that the arguments are valid: if ((typeof id !== 'string' && typeof id !== 'number') || arguments.length !== 1) throw 'dropEdge: Wrong arguments.'; if (!this.edgesIndex[id]) throw 'The edge "' + id + '" does not exist.'; var i, l, edge; // Remove the edge from indexes: edge = this.edgesIndex[id]; delete this.edgesIndex[id]; for (i = 0, l = this.edgesArray.length; i < l; i++) if (this.edgesArray[i].id === id) { this.edgesArray.splice(i, 1); break; } delete this.inNeighborsIndex[edge.target][edge.source][edge.id]; if (!Object.keys(this.inNeighborsIndex[edge.target][edge.source]).length) delete this.inNeighborsIndex[edge.target][edge.source]; delete this.outNeighborsIndex[edge.source][edge.target][edge.id]; if (!Object.keys(this.outNeighborsIndex[edge.source][edge.target]).length) delete this.outNeighborsIndex[edge.source][edge.target]; delete this.allNeighborsIndex[edge.source][edge.target][edge.id]; if (!Object.keys(this.allNeighborsIndex[edge.source][edge.target]).length) delete this.allNeighborsIndex[edge.source][edge.target]; if (edge.target !== edge.source) { delete this.allNeighborsIndex[edge.target][edge.source][edge.id]; if (!Object.keys(this.allNeighborsIndex[edge.target][edge.source]).length) delete this.allNeighborsIndex[edge.target][edge.source]; } this.inNeighborsCount[edge.target]--; this.outNeighborsCount[edge.source]--; this.allNeighborsCount[edge.source]--; this.allNeighborsCount[edge.target]--; return this; }); /** * This method destroys the current instance. It basically empties each index * and methods attached to the graph. */ graph.addMethod('kill', function() { // Delete arrays: this.nodesArray.length = 0; this.edgesArray.length = 0; delete this.nodesArray; delete this.edgesArray; // Delete indexes: delete this.nodesIndex; delete this.edgesIndex; delete this.inNeighborsIndex; delete this.outNeighborsIndex; delete this.allNeighborsIndex; delete this.inNeighborsCount; delete this.outNeighborsCount; delete this.allNeighborsCount; }); /** * This method empties the nodes and edges arrays, as well as the different * indexes. * * @return {object} The graph instance. */ graph.addMethod('clear', function() { this.nodesArray.length = 0; this.edgesArray.length = 0; // Due to GC issues, I prefer not to create new object. These objects are // only available from the methods and attached functions, but still, it is // better to prevent ghost references to unrelevant data... __emptyObject(this.nodesIndex); __emptyObject(this.edgesIndex); __emptyObject(this.nodesIndex); __emptyObject(this.inNeighborsIndex); __emptyObject(this.outNeighborsIndex); __emptyObject(this.allNeighborsIndex); __emptyObject(this.inNeighborsCount); __emptyObject(this.outNeighborsCount); __emptyObject(this.allNeighborsCount); return this; }); /** * This method reads an object and adds the nodes and edges, through the * proper methods "addNode" and "addEdge". * * Here is an example: * * > var myGraph = new graph(); * > myGraph.read({ * > nodes: [ * > { id: 'n0' }, * > { id: 'n1' } * > ], * > edges: [ * > { * > id: 'e0', * > source: 'n0', * > target: 'n1' * > } * > ] * > }); * > * > console.log( * > myGraph.nodes().length, * > myGraph.edges().length * > ); // outputs 2 1 * * @param {object} g The graph object. * @return {object} The graph instance. */ graph.addMethod('read', function(g) { var i, a, l; a = g.nodes || []; for (i = 0, l = a.length; i < l; i++) this.addNode(a[i]); a = g.edges || []; for (i = 0, l = a.length; i < l; i++) this.addEdge(a[i]); return this; }); /** * This methods returns one or several nodes, depending on how it is called. * * To get the array of nodes, call "nodes" without argument. To get a * specific node, call it with the id of the node. The get multiple node, * call it with an array of ids, and it will return the array of nodes, in * the same order. * * @param {?(string|array)} v Eventually one id, an array of ids. * @return {object|array} The related node or array of nodes. */ graph.addMethod('nodes', function(v) { // Clone the array of nodes and return it: if (!arguments.length) return this.nodesArray.slice(0); // Return the related node: if (arguments.length === 1 && (typeof v === 'string' || typeof v === 'number')) return this.nodesIndex[v]; // Return an array of the related node: if ( arguments.length === 1 && Object.prototype.toString.call(v) === '[object Array]' ) { var i, l, a = []; for (i = 0, l = v.length; i < l; i++) if (typeof v[i] === 'string' || typeof v[i] === 'number') a.push(this.nodesIndex[v[i]]); else throw 'nodes: Wrong arguments.'; return a; } throw 'nodes: Wrong arguments.'; }); /** * This methods returns the degree of one or several nodes, depending on how * it is called. It is also possible to get incoming or outcoming degrees * instead by specifying 'in' or 'out' as a second argument. * * @param {string|array} v One id, an array of ids. * @param {?string} which Which degree is required. Values are 'in', * 'out', and by default the normal degree. * @return {number|array} The related degree or array of degrees. */ graph.addMethod('degree', function(v, which) { // Check which degree is required: which = { 'in': this.inNeighborsCount, 'out': this.outNeighborsCount }[which || ''] || this.allNeighborsCount; // Return the related node: if (typeof v === 'string' || typeof v === 'number') return which[v]; // Return an array of the related node: if (Object.prototype.toString.call(v) === '[object Array]') { var i, l, a = []; for (i = 0, l = v.length; i < l; i++) if (typeof v[i] === 'string' || typeof v[i] === 'number') a.push(which[v[i]]); else throw 'degree: Wrong arguments.'; return a; } throw 'degree: Wrong arguments.'; }); /** * This methods returns one or several edges, depending on how it is called. * * To get the array of edges, call "edges" without argument. To get a * specific edge, call it with the id of the edge. The get multiple edge, * call it with an array of ids, and it will return the array of edges, in * the same order. * * @param {?(string|array)} v Eventually one id, an array of ids. * @return {object|array} The related edge or array of edges. */ graph.addMethod('edges', function(v) { // Clone the array of edges and return it: if (!arguments.length) return this.edgesArray.slice(0); // Return the related edge: if (arguments.length === 1 && (typeof v === 'string' || typeof v === 'number')) return this.edgesIndex[v]; // Return an array of the related edge: if ( arguments.length === 1 && Object.prototype.toString.call(v) === '[object Array]' ) { var i, l, a = []; for (i = 0, l = v.length; i < l; i++) if (typeof v[i] === 'string' || typeof v[i] === 'number') a.push(this.edgesIndex[v[i]]); else throw 'edges: Wrong arguments.'; return a; } throw 'edges: Wrong arguments.'; }); /** * EXPORT: * ******* */ if (typeof sigma !== 'undefined') { sigma.classes = sigma.classes || Object.create(null); sigma.classes.graph = graph; } else if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) exports = module.exports = graph; exports.graph = graph; } else this.graph = graph; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; sigma.utils.pkg('sigma.classes'); /** * The camera constructor. It just initializes its attributes and methods. * * @param {string} id The id. * @param {sigma.classes.graph} graph The graph. * @param {configurable} settings The settings function. * @param {?object} options Eventually some overriding options. * @return {camera} Returns the fresh new camera instance. */ sigma.classes.camera = function(id, graph, settings, options) { sigma.classes.dispatcher.extend(this); Object.defineProperty(this, 'graph', { value: graph }); Object.defineProperty(this, 'id', { value: id }); Object.defineProperty(this, 'readPrefix', { value: 'read_cam' + id + ':' }); Object.defineProperty(this, 'prefix', { value: 'cam' + id + ':' }); this.x = 0; this.y = 0; this.ratio = 1; this.angle = 0; this.isAnimated = false; this.settings = (typeof options === 'object' && options) ? settings.embedObject(options) : settings; }; /** * Updates the camera position. * * @param {object} coordinates The new coordinates object. * @return {camera} Returns the camera. */ sigma.classes.camera.prototype.goTo = function(coordinates) { if (!this.settings('enableCamera')) return this; var i, l, c = coordinates || {}, keys = ['x', 'y', 'ratio', 'angle']; for (i = 0, l = keys.length; i < l; i++) if (c[keys[i]] !== undefined) { if (typeof c[keys[i]] === 'number' && !isNaN(c[keys[i]])) this[keys[i]] = c[keys[i]]; else throw 'Value for "' + keys[i] + '" is not a number.'; } this.dispatchEvent('coordinatesUpdated'); return this; }; /** * This method takes a graph and computes for each node and edges its * coordinates relatively to the center of the camera. Basically, it will * compute the coordinates that will be used by the graphic renderers. * * Since it should be possible to use different cameras and different * renderers, it is possible to specify a prefix to put before the new * coordinates (to get something like "node.camera1_x") * * @param {?string} read The prefix of the coordinates to read. * @param {?string} write The prefix of the coordinates to write. * @param {?object} options Eventually an object of options. Those can be: * - A restricted nodes array. * - A restricted edges array. * - A width. * - A height. * @return {camera} Returns the camera. */ sigma.classes.camera.prototype.applyView = function(read, write, options) { options = options || {}; write = write !== undefined ? write : this.prefix; read = read !== undefined ? read : this.readPrefix; var nodes = options.nodes || this.graph.nodes(), edges = options.edges || this.graph.edges(); var i, l, node, cos = Math.cos(this.angle), sin = Math.sin(this.angle); for (i = 0, l = nodes.length; i < l; i++) { node = nodes[i]; node[write + 'x'] = ( ((node[read + 'x'] || 0) - this.x) * cos + ((node[read + 'y'] || 0) - this.y) * sin ) / this.ratio + (options.width || 0) / 2; node[write + 'y'] = ( ((node[read + 'y'] || 0) - this.y) * cos - ((node[read + 'x'] || 0) - this.x) * sin ) / this.ratio + (options.height || 0) / 2; node[write + 'size'] = (node[read + 'size'] || 0) / Math.pow(this.ratio, this.settings('nodesPowRatio')); } for (i = 0, l = edges.length; i < l; i++) { edges[i][write + 'size'] = (edges[i][read + 'size'] || 0) / Math.pow(this.ratio, this.settings('edgesPowRatio')); } return this; }; /** * This function converts the coordinates of a point from the frame of the * camera to the frame of the graph. * * @param {number} x The X coordinate of the point in the frame of the * camera. * @param {number} y The Y coordinate of the point in the frame of the * camera. * @return {object} The point coordinates in the frame of the graph. */ sigma.classes.camera.prototype.graphPosition = function(x, y, vector) { var X = 0, Y = 0, cos = Math.cos(this.angle), sin = Math.sin(this.angle); // Revert the origin differential vector: if (!vector) { X = - (this.x * cos + this.y * sin) / this.ratio; Y = - (this.y * cos - this.x * sin) / this.ratio; } return { x: (x * cos + y * sin) / this.ratio + X, y: (y * cos - x * sin) / this.ratio + Y }; }; /** * This function converts the coordinates of a point from the frame of the * graph to the frame of the camera. * * @param {number} x The X coordinate of the point in the frame of the * graph. * @param {number} y The Y coordinate of the point in the frame of the * graph. * @return {object} The point coordinates in the frame of the camera. */ sigma.classes.camera.prototype.cameraPosition = function(x, y, vector) { var X = 0, Y = 0, cos = Math.cos(this.angle), sin = Math.sin(this.angle); // Revert the origin differential vector: if (!vector) { X = - (this.x * cos + this.y * sin) / this.ratio; Y = - (this.y * cos - this.x * sin) / this.ratio; } return { x: ((x - X) * cos - (y - Y) * sin) * this.ratio, y: ((y - Y) * cos + (x - X) * sin) * this.ratio }; }; /** * This method returns the transformation matrix of the camera. This is * especially useful to apply the camera view directly in shaders, in case of * WebGL rendering. * * @return {array} The transformation matrix. */ sigma.classes.camera.prototype.getMatrix = function() { var scale = sigma.utils.matrices.scale(1 / this.ratio), rotation = sigma.utils.matrices.rotation(this.angle), translation = sigma.utils.matrices.translation(-this.x, -this.y), matrix = sigma.utils.matrices.multiply( translation, sigma.utils.matrices.multiply( rotation, scale ) ); return matrix; }; /** * Taking a width and a height as parameters, this method returns the * coordinates of the rectangle representing the camera on screen, in the * graph's referentiel. * * To keep displaying labels of nodes going out of the screen, the method * keeps a margin around the screen in the returned rectangle. * * @param {number} width The width of the screen. * @param {number} height The height of the screen. * @return {object} The rectangle as x1, y1, x2 and y2, representing * two opposite points. */ sigma.classes.camera.prototype.getRectangle = function(width, height) { var widthVect = this.cameraPosition(width, 0, true), heightVect = this.cameraPosition(0, height, true), centerVect = this.cameraPosition(width / 2, height / 2, true), marginX = this.cameraPosition(width / 4, 0, true).x, marginY = this.cameraPosition(0, height / 4, true).y; return { x1: this.x - centerVect.x - marginX, y1: this.y - centerVect.y - marginY, x2: this.x - centerVect.x + marginX + widthVect.x, y2: this.y - centerVect.y - marginY + widthVect.y, height: Math.sqrt( Math.pow(heightVect.x, 2) + Math.pow(heightVect.y + 2 * marginY, 2) ) }; }; }).call(this); ;(function(undefined) { 'use strict'; /** * Sigma Quadtree Module * ===================== * * Author: Guillaume Plique (Yomguithereal) * Version: 0.2 */ /** * Quad Geometric Operations * ------------------------- * * A useful batch of geometric operations used by the quadtree. */ var _geom = { /** * Transforms a graph node with x, y and size into an * axis-aligned square. * * @param {object} A graph node with at least a point (x, y) and a size. * @return {object} A square: two points (x1, y1), (x2, y2) and height. */ pointToSquare: function(n) { return { x1: n.x - n.size, y1: n.y - n.size, x2: n.x + n.size, y2: n.y - n.size, height: n.size * 2 }; }, /** * Checks whether a rectangle is axis-aligned. * * @param {object} A rectangle defined by two points * (x1, y1) and (x2, y2). * @return {boolean} True if the rectangle is axis-aligned. */ isAxisAligned: function(r) { return r.x1 === r.x2 || r.y1 === r.y2; }, /** * Compute top points of an axis-aligned rectangle. This is useful in * cases when the rectangle has been rotated (left, right or bottom up) and * later operations need to know the top points. * * @param {object} An axis-aligned rectangle defined by two points * (x1, y1), (x2, y2) and height. * @return {object} A rectangle: two points (x1, y1), (x2, y2) and height. */ axisAlignedTopPoints: function(r) { // Basic if (r.y1 === r.y2 && r.x1 < r.x2) return r; // Rotated to right if (r.x1 === r.x2 && r.y2 > r.y1) return { x1: r.x1 - r.height, y1: r.y1, x2: r.x1, y2: r.y1, height: r.height }; // Rotated to left if (r.x1 === r.x2 && r.y2 < r.y1) return { x1: r.x1, y1: r.y2, x2: r.x2 + r.height, y2: r.y2, height: r.height }; // Bottom's up return { x1: r.x2, y1: r.y1 - r.height, x2: r.x1, y2: r.y1 - r.height, height: r.height }; }, /** * Get coordinates of a rectangle's lower left corner from its top points. * * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). * @return {object} Coordinates of the corner (x, y). */ lowerLeftCoor: function(r) { var width = ( Math.sqrt( Math.pow(r.x2 - r.x1, 2) + Math.pow(r.y2 - r.y1, 2) ) ); return { x: r.x1 - (r.y2 - r.y1) * r.height / width, y: r.y1 + (r.x2 - r.x1) * r.height / width }; }, /** * Get coordinates of a rectangle's lower right corner from its top points * and its lower left corner. * * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). * @param {object} A corner's coordinates (x, y). * @return {object} Coordinates of the corner (x, y). */ lowerRightCoor: function(r, llc) { return { x: llc.x - r.x1 + r.x2, y: llc.y - r.y1 + r.y2 }; }, /** * Get the coordinates of all the corners of a rectangle from its top point. * * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). * @return {array} An array of the four corners' coordinates (x, y). */ rectangleCorners: function(r) { var llc = this.lowerLeftCoor(r), lrc = this.lowerRightCoor(r, llc); return [ {x: r.x1, y: r.y1}, {x: r.x2, y: r.y2}, {x: llc.x, y: llc.y}, {x: lrc.x, y: lrc.y} ]; }, /** * Split a square defined by its boundaries into four. * * @param {object} Boundaries of the square (x, y, width, height). * @return {array} An array containing the four new squares, themselves * defined by an array of their four corners (x, y). */ splitSquare: function(b) { return [ [ {x: b.x, y: b.y}, {x: b.x + b.width / 2, y: b.y}, {x: b.x, y: b.y + b.height / 2}, {x: b.x + b.width / 2, y: b.y + b.height / 2} ], [ {x: b.x + b.width / 2, y: b.y}, {x: b.x + b.width, y: b.y}, {x: b.x + b.width / 2, y: b.y + b.height / 2}, {x: b.x + b.width, y: b.y + b.height / 2} ], [ {x: b.x, y: b.y + b.height / 2}, {x: b.x + b.width / 2, y: b.y + b.height / 2}, {x: b.x, y: b.y + b.height}, {x: b.x + b.width / 2, y: b.y + b.height} ], [ {x: b.x + b.width / 2, y: b.y + b.height / 2}, {x: b.x + b.width, y: b.y + b.height / 2}, {x: b.x + b.width / 2, y: b.y + b.height}, {x: b.x + b.width, y: b.y + b.height} ] ]; }, /** * Compute the four axis between corners of rectangle A and corners of * rectangle B. This is needed later to check an eventual collision. * * @param {array} An array of rectangle A's four corners (x, y). * @param {array} An array of rectangle B's four corners (x, y). * @return {array} An array of four axis defined by their coordinates (x,y). */ axis: function(c1, c2) { return [ {x: c1[1].x - c1[0].x, y: c1[1].y - c1[0].y}, {x: c1[1].x - c1[3].x, y: c1[1].y - c1[3].y}, {x: c2[0].x - c2[2].x, y: c2[0].y - c2[2].y}, {x: c2[0].x - c2[1].x, y: c2[0].y - c2[1].y} ]; }, /** * Project a rectangle's corner on an axis. * * @param {object} Coordinates of a corner (x, y). * @param {object} Coordinates of an axis (x, y). * @return {object} The projection defined by coordinates (x, y). */ projection: function(c, a) { var l = ( (c.x * a.x + c.y * a.y) / (Math.pow(a.x, 2) + Math.pow(a.y, 2)) ); return { x: l * a.x, y: l * a.y }; }, /** * Check whether two rectangles collide on one particular axis. * * @param {object} An axis' coordinates (x, y). * @param {array} Rectangle A's corners. * @param {array} Rectangle B's corners. * @return {boolean} True if the rectangles collide on the axis. */ axisCollision: function(a, c1, c2) { var sc1 = [], sc2 = []; for (var ci = 0; ci < 4; ci++) { var p1 = this.projection(c1[ci], a), p2 = this.projection(c2[ci], a); sc1.push(p1.x * a.x + p1.y * a.y); sc2.push(p2.x * a.x + p2.y * a.y); } var maxc1 = Math.max.apply(Math, sc1), maxc2 = Math.max.apply(Math, sc2), minc1 = Math.min.apply(Math, sc1), minc2 = Math.min.apply(Math, sc2); return (minc2 <= maxc1 && maxc2 >= minc1); }, /** * Check whether two rectangles collide on each one of their four axis. If * all axis collide, then the two rectangles do collide on the plane. * * @param {array} Rectangle A's corners. * @param {array} Rectangle B's corners. * @return {boolean} True if the rectangles collide. */ collision: function(c1, c2) { var axis = this.axis(c1, c2), col = true; for (var i = 0; i < 4; i++) col = col && this.axisCollision(axis[i], c1, c2); return col; } }; /** * Quad Functions * ------------ * * The Quadtree functions themselves. * For each of those functions, we consider that in a splitted quad, the * index of each node is the following: * 0: top left * 1: top right * 2: bottom left * 3: bottom right * * Moreover, the hereafter quad's philosophy is to consider that if an element * collides with more than one nodes, this element belongs to each of the * nodes it collides with where other would let it lie on a higher node. */ /** * Get the index of the node containing the point in the quad * * @param {object} point A point defined by coordinates (x, y). * @param {object} quadBounds Boundaries of the quad (x, y, width, heigth). * @return {integer} The index of the node containing the point. */ function _quadIndex(point, quadBounds) { var xmp = quadBounds.x + quadBounds.width / 2, ymp = quadBounds.y + quadBounds.height / 2, top = (point.y < ymp), left = (point.x < xmp); if (top) { if (left) return 0; else return 1; } else { if (left) return 2; else return 3; } } /** * Get a list of indexes of nodes containing an axis-aligned rectangle * * @param {object} rectangle A rectangle defined by two points (x1, y1), * (x2, y2) and height. * @param {array} quadCorners An array of the quad nodes' corners. * @return {array} An array of indexes containing one to * four integers. */ function _quadIndexes(rectangle, quadCorners) { var indexes = []; // Iterating through quads for (var i = 0; i < 4; i++) if ((rectangle.x2 >= quadCorners[i][0].x) && (rectangle.x1 <= quadCorners[i][1].x) && (rectangle.y1 + rectangle.height >= quadCorners[i][0].y) && (rectangle.y1 <= quadCorners[i][2].y)) indexes.push(i); return indexes; } /** * Get a list of indexes of nodes containing a non-axis-aligned rectangle * * @param {array} corners An array containing each corner of the * rectangle defined by its coordinates (x, y). * @param {array} quadCorners An array of the quad nodes' corners. * @return {array} An array of indexes containing one to * four integers. */ function _quadCollision(corners, quadCorners) { var indexes = []; // Iterating through quads for (var i = 0; i < 4; i++) if (_geom.collision(corners, quadCorners[i])) indexes.push(i); return indexes; } /** * Subdivide a quad by creating a node at a precise index. The function does * not generate all four nodes not to potentially create unused nodes. * * @param {integer} index The index of the node to create. * @param {object} quad The quad object to subdivide. * @return {object} A new quad representing the node created. */ function _quadSubdivide(index, quad) { var next = quad.level + 1, subw = Math.round(quad.bounds.width / 2), subh = Math.round(quad.bounds.height / 2), qx = Math.round(quad.bounds.x), qy = Math.round(quad.bounds.y), x, y; switch (index) { case 0: x = qx; y = qy; break; case 1: x = qx + subw; y = qy; break; case 2: x = qx; y = qy + subh; break; case 3: x = qx + subw; y = qy + subh; break; } return _quadTree( {x: x, y: y, width: subw, height: subh}, next, quad.maxElements, quad.maxLevel ); } /** * Recursively insert an element into the quadtree. Only points * with size, i.e. axis-aligned squares, may be inserted with this * method. * * @param {object} el The element to insert in the quadtree. * @param {object} sizedPoint A sized point defined by two top points * (x1, y1), (x2, y2) and height. * @param {object} quad The quad in which to insert the element. * @return {undefined} The function does not return anything. */ function _quadInsert(el, sizedPoint, quad) { if (quad.level < quad.maxLevel) { // Searching appropriate quads var indexes = _quadIndexes(sizedPoint, quad.corners); // Iterating for (var i = 0, l = indexes.length; i < l; i++) { // Subdividing if necessary if (quad.nodes[indexes[i]] === undefined) quad.nodes[indexes[i]] = _quadSubdivide(indexes[i], quad); // Recursion _quadInsert(el, sizedPoint, quad.nodes[indexes[i]]); } } else { // Pushing the element in a leaf node quad.elements.push(el); } } /** * Recursively retrieve every elements held by the node containing the * searched point. * * @param {object} point The searched point (x, y). * @param {object} quad The searched quad. * @return {array} An array of elements contained in the relevant * node. */ function _quadRetrievePoint(point, quad) { if (quad.level < quad.maxLevel) { var index = _quadIndex(point, quad.bounds); // If node does not exist we return an empty list if (quad.nodes[index] !== undefined) { return _quadRetrievePoint(point, quad.nodes[index]); } else { return []; } } else { return quad.elements; } } /** * Recursively retrieve every elements contained within an rectangular area * that may or may not be axis-aligned. * * @param {object|array} rectData The searched area defined either by * an array of four corners (x, y) in * the case of a non-axis-aligned * rectangle or an object with two top * points (x1, y1), (x2, y2) and height. * @param {object} quad The searched quad. * @param {function} collisionFunc The collision function used to search * for node indexes. * @param {array?} els The retrieved elements. * @return {array} An array of elements contained in the * area. */ function _quadRetrieveArea(rectData, quad, collisionFunc, els) { els = els || {}; if (quad.level < quad.maxLevel) { var indexes = collisionFunc(rectData, quad.corners); for (var i = 0, l = indexes.length; i < l; i++) if (quad.nodes[indexes[i]] !== undefined) _quadRetrieveArea( rectData, quad.nodes[indexes[i]], collisionFunc, els ); } else for (var j = 0, m = quad.elements.length; j < m; j++) if (els[quad.elements[j].id] === undefined) els[quad.elements[j].id] = quad.elements[j]; return els; } /** * Creates the quadtree object itself. * * @param {object} bounds The boundaries of the quad defined by an * origin (x, y), width and heigth. * @param {integer} level The level of the quad in the tree. * @param {integer} maxElements The max number of element in a leaf node. * @param {integer} maxLevel The max recursion level of the tree. * @return {object} The quadtree object. */ function _quadTree(bounds, level, maxElements, maxLevel) { return { level: level || 0, bounds: bounds, corners: _geom.splitSquare(bounds), maxElements: maxElements || 20, maxLevel: maxLevel || 4, elements: [], nodes: [] }; } /** * Sigma Quad Constructor * ---------------------- * * The quad API as exposed to sigma. */ /** * The quad core that will become the sigma interface with the quadtree. * * property {object} _tree Property holding the quadtree object. * property {object} _geom Exposition of the _geom namespace for testing. * property {object} _cache Cache for the area method. */ var quad = function() { this._geom = _geom; this._tree = null; this._cache = { query: false, result: false }; }; /** * Index a graph by inserting its nodes into the quadtree. * * @param {array} nodes An array of nodes to index. * @param {object} params An object of parameters with at least the quad * bounds. * @return {object} The quadtree object. * * Parameters: * ---------- * bounds: {object} boundaries of the quad defined by its origin (x, y) * width and heigth. * prefix: {string?} a prefix for node geometric attributes. * maxElements: {integer?} the max number of elements in a leaf node. * maxLevel: {integer?} the max recursion level of the tree. */ quad.prototype.index = function(nodes, params) { // Enforcing presence of boundaries if (!params.bounds) throw 'sigma.classes.quad.index: bounds information not given.'; // Prefix var prefix = params.prefix || ''; // Building the tree this._tree = _quadTree( params.bounds, 0, params.maxElements, params.maxLevel ); // Inserting graph nodes into the tree for (var i = 0, l = nodes.length; i < l; i++) { // Inserting node _quadInsert( nodes[i], _geom.pointToSquare({ x: nodes[i][prefix + 'x'], y: nodes[i][prefix + 'y'], size: nodes[i][prefix + 'size'] }), this._tree ); } // Reset cache: this._cache = { query: false, result: false }; // remove? return this._tree; }; /** * Retrieve every graph nodes held by the quadtree node containing the * searched point. * * @param {number} x of the point. * @param {number} y of the point. * @return {array} An array of nodes retrieved. */ quad.prototype.point = function(x, y) { return this._tree ? _quadRetrievePoint({x: x, y: y}, this._tree) || [] : []; }; /** * Retrieve every graph nodes within a rectangular area. The methods keep the * last area queried in cache for optimization reason and will act differently * for the same reason if the area is axis-aligned or not. * * @param {object} A rectangle defined by two top points (x1, y1), (x2, y2) * and height. * @return {array} An array of nodes retrieved. */ quad.prototype.area = function(rect) { var serialized = JSON.stringify(rect), collisionFunc, rectData; // Returning cache? if (this._cache.query === serialized) return this._cache.result; // Axis aligned ? if (_geom.isAxisAligned(rect)) { collisionFunc = _quadIndexes; rectData = _geom.axisAlignedTopPoints(rect); } else { collisionFunc = _quadCollision; rectData = _geom.rectangleCorners(rect); } // Retrieving nodes var nodes = this._tree ? _quadRetrieveArea( rectData, this._tree, collisionFunc ) : []; // Object to array var nodesArray = []; for (var i in nodes) nodesArray.push(nodes[i]); // Caching this._cache.query = serialized; this._cache.result = nodesArray; return nodesArray; }; /** * EXPORT: * ******* */ if (typeof this.sigma !== 'undefined') { this.sigma.classes = this.sigma.classes || {}; this.sigma.classes.quad = quad; } else if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) exports = module.exports = quad; exports.quad = quad; } else this.quad = quad; }).call(this); ;(function(undefined) { 'use strict'; /** * Sigma Quadtree Module for edges * =============================== * * Author: Sébastien Heymann, * from the quad of Guillaume Plique (Yomguithereal) * Version: 0.2 */ /** * Quad Geometric Operations * ------------------------- * * A useful batch of geometric operations used by the quadtree. */ var _geom = { /** * Transforms a graph node with x, y and size into an * axis-aligned square. * * @param {object} A graph node with at least a point (x, y) and a size. * @return {object} A square: two points (x1, y1), (x2, y2) and height. */ pointToSquare: function(n) { return { x1: n.x - n.size, y1: n.y - n.size, x2: n.x + n.size, y2: n.y - n.size, height: n.size * 2 }; }, /** * Transforms a graph edge with x1, y1, x2, y2 and size into an * axis-aligned square. * * @param {object} A graph edge with at least two points * (x1, y1), (x2, y2) and a size. * @return {object} A square: two points (x1, y1), (x2, y2) and height. */ lineToSquare: function(e) { if (e.y1 < e.y2) { // (e.x1, e.y1) on top if (e.x1 < e.x2) { // (e.x1, e.y1) on left return { x1: e.x1 - e.size, y1: e.y1 - e.size, x2: e.x2 + e.size, y2: e.y1 - e.size, height: e.y2 - e.y1 + e.size * 2 }; } // (e.x1, e.y1) on right return { x1: e.x2 - e.size, y1: e.y1 - e.size, x2: e.x1 + e.size, y2: e.y1 - e.size, height: e.y2 - e.y1 + e.size * 2 }; } // (e.x2, e.y2) on top if (e.x1 < e.x2) { // (e.x1, e.y1) on left return { x1: e.x1 - e.size, y1: e.y2 - e.size, x2: e.x2 + e.size, y2: e.y2 - e.size, height: e.y1 - e.y2 + e.size * 2 }; } // (e.x2, e.y2) on right return { x1: e.x2 - e.size, y1: e.y2 - e.size, x2: e.x1 + e.size, y2: e.y2 - e.size, height: e.y1 - e.y2 + e.size * 2 }; }, /** * Transforms a graph edge of type 'curve' with x1, y1, x2, y2, * control point and size into an axis-aligned square. * * @param {object} e A graph edge with at least two points * (x1, y1), (x2, y2) and a size. * @param {object} cp A control point (x,y). * @return {object} A square: two points (x1, y1), (x2, y2) and height. */ quadraticCurveToSquare: function(e, cp) { var pt = sigma.utils.getPointOnQuadraticCurve( 0.5, e.x1, e.y1, e.x2, e.y2, cp.x, cp.y ); // Bounding box of the two points and the point at the middle of the // curve: var minX = Math.min(e.x1, e.x2, pt.x), maxX = Math.max(e.x1, e.x2, pt.x), minY = Math.min(e.y1, e.y2, pt.y), maxY = Math.max(e.y1, e.y2, pt.y); return { x1: minX - e.size, y1: minY - e.size, x2: maxX + e.size, y2: minY - e.size, height: maxY - minY + e.size * 2 }; }, /** * Transforms a graph self loop into an axis-aligned square. * * @param {object} n A graph node with a point (x, y) and a size. * @return {object} A square: two points (x1, y1), (x2, y2) and height. */ selfLoopToSquare: function(n) { // Fitting to the curve is too costly, we compute a larger bounding box // using the control points: var cp = sigma.utils.getSelfLoopControlPoints(n.x, n.y, n.size); // Bounding box of the point and the two control points: var minX = Math.min(n.x, cp.x1, cp.x2), maxX = Math.max(n.x, cp.x1, cp.x2), minY = Math.min(n.y, cp.y1, cp.y2), maxY = Math.max(n.y, cp.y1, cp.y2); return { x1: minX - n.size, y1: minY - n.size, x2: maxX + n.size, y2: minY - n.size, height: maxY - minY + n.size * 2 }; }, /** * Checks whether a rectangle is axis-aligned. * * @param {object} A rectangle defined by two points * (x1, y1) and (x2, y2). * @return {boolean} True if the rectangle is axis-aligned. */ isAxisAligned: function(r) { return r.x1 === r.x2 || r.y1 === r.y2; }, /** * Compute top points of an axis-aligned rectangle. This is useful in * cases when the rectangle has been rotated (left, right or bottom up) and * later operations need to know the top points. * * @param {object} An axis-aligned rectangle defined by two points * (x1, y1), (x2, y2) and height. * @return {object} A rectangle: two points (x1, y1), (x2, y2) and height. */ axisAlignedTopPoints: function(r) { // Basic if (r.y1 === r.y2 && r.x1 < r.x2) return r; // Rotated to right if (r.x1 === r.x2 && r.y2 > r.y1) return { x1: r.x1 - r.height, y1: r.y1, x2: r.x1, y2: r.y1, height: r.height }; // Rotated to left if (r.x1 === r.x2 && r.y2 < r.y1) return { x1: r.x1, y1: r.y2, x2: r.x2 + r.height, y2: r.y2, height: r.height }; // Bottom's up return { x1: r.x2, y1: r.y1 - r.height, x2: r.x1, y2: r.y1 - r.height, height: r.height }; }, /** * Get coordinates of a rectangle's lower left corner from its top points. * * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). * @return {object} Coordinates of the corner (x, y). */ lowerLeftCoor: function(r) { var width = ( Math.sqrt( Math.pow(r.x2 - r.x1, 2) + Math.pow(r.y2 - r.y1, 2) ) ); return { x: r.x1 - (r.y2 - r.y1) * r.height / width, y: r.y1 + (r.x2 - r.x1) * r.height / width }; }, /** * Get coordinates of a rectangle's lower right corner from its top points * and its lower left corner. * * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). * @param {object} A corner's coordinates (x, y). * @return {object} Coordinates of the corner (x, y). */ lowerRightCoor: function(r, llc) { return { x: llc.x - r.x1 + r.x2, y: llc.y - r.y1 + r.y2 }; }, /** * Get the coordinates of all the corners of a rectangle from its top point. * * @param {object} A rectangle defined by two points (x1, y1) and (x2, y2). * @return {array} An array of the four corners' coordinates (x, y). */ rectangleCorners: function(r) { var llc = this.lowerLeftCoor(r), lrc = this.lowerRightCoor(r, llc); return [ {x: r.x1, y: r.y1}, {x: r.x2, y: r.y2}, {x: llc.x, y: llc.y}, {x: lrc.x, y: lrc.y} ]; }, /** * Split a square defined by its boundaries into four. * * @param {object} Boundaries of the square (x, y, width, height). * @return {array} An array containing the four new squares, themselves * defined by an array of their four corners (x, y). */ splitSquare: function(b) { return [ [ {x: b.x, y: b.y}, {x: b.x + b.width / 2, y: b.y}, {x: b.x, y: b.y + b.height / 2}, {x: b.x + b.width / 2, y: b.y + b.height / 2} ], [ {x: b.x + b.width / 2, y: b.y}, {x: b.x + b.width, y: b.y}, {x: b.x + b.width / 2, y: b.y + b.height / 2}, {x: b.x + b.width, y: b.y + b.height / 2} ], [ {x: b.x, y: b.y + b.height / 2}, {x: b.x + b.width / 2, y: b.y + b.height / 2}, {x: b.x, y: b.y + b.height}, {x: b.x + b.width / 2, y: b.y + b.height} ], [ {x: b.x + b.width / 2, y: b.y + b.height / 2}, {x: b.x + b.width, y: b.y + b.height / 2}, {x: b.x + b.width / 2, y: b.y + b.height}, {x: b.x + b.width, y: b.y + b.height} ] ]; }, /** * Compute the four axis between corners of rectangle A and corners of * rectangle B. This is needed later to check an eventual collision. * * @param {array} An array of rectangle A's four corners (x, y). * @param {array} An array of rectangle B's four corners (x, y). * @return {array} An array of four axis defined by their coordinates (x,y). */ axis: function(c1, c2) { return [ {x: c1[1].x - c1[0].x, y: c1[1].y - c1[0].y}, {x: c1[1].x - c1[3].x, y: c1[1].y - c1[3].y}, {x: c2[0].x - c2[2].x, y: c2[0].y - c2[2].y}, {x: c2[0].x - c2[1].x, y: c2[0].y - c2[1].y} ]; }, /** * Project a rectangle's corner on an axis. * * @param {object} Coordinates of a corner (x, y). * @param {object} Coordinates of an axis (x, y). * @return {object} The projection defined by coordinates (x, y). */ projection: function(c, a) { var l = ( (c.x * a.x + c.y * a.y) / (Math.pow(a.x, 2) + Math.pow(a.y, 2)) ); return { x: l * a.x, y: l * a.y }; }, /** * Check whether two rectangles collide on one particular axis. * * @param {object} An axis' coordinates (x, y). * @param {array} Rectangle A's corners. * @param {array} Rectangle B's corners. * @return {boolean} True if the rectangles collide on the axis. */ axisCollision: function(a, c1, c2) { var sc1 = [], sc2 = []; for (var ci = 0; ci < 4; ci++) { var p1 = this.projection(c1[ci], a), p2 = this.projection(c2[ci], a); sc1.push(p1.x * a.x + p1.y * a.y); sc2.push(p2.x * a.x + p2.y * a.y); } var maxc1 = Math.max.apply(Math, sc1), maxc2 = Math.max.apply(Math, sc2), minc1 = Math.min.apply(Math, sc1), minc2 = Math.min.apply(Math, sc2); return (minc2 <= maxc1 && maxc2 >= minc1); }, /** * Check whether two rectangles collide on each one of their four axis. If * all axis collide, then the two rectangles do collide on the plane. * * @param {array} Rectangle A's corners. * @param {array} Rectangle B's corners. * @return {boolean} True if the rectangles collide. */ collision: function(c1, c2) { var axis = this.axis(c1, c2), col = true; for (var i = 0; i < 4; i++) col = col && this.axisCollision(axis[i], c1, c2); return col; } }; /** * Quad Functions * ------------ * * The Quadtree functions themselves. * For each of those functions, we consider that in a splitted quad, the * index of each node is the following: * 0: top left * 1: top right * 2: bottom left * 3: bottom right * * Moreover, the hereafter quad's philosophy is to consider that if an element * collides with more than one nodes, this element belongs to each of the * nodes it collides with where other would let it lie on a higher node. */ /** * Get the index of the node containing the point in the quad * * @param {object} point A point defined by coordinates (x, y). * @param {object} quadBounds Boundaries of the quad (x, y, width, heigth). * @return {integer} The index of the node containing the point. */ function _quadIndex(point, quadBounds) { var xmp = quadBounds.x + quadBounds.width / 2, ymp = quadBounds.y + quadBounds.height / 2, top = (point.y < ymp), left = (point.x < xmp); if (top) { if (left) return 0; else return 1; } else { if (left) return 2; else return 3; } } /** * Get a list of indexes of nodes containing an axis-aligned rectangle * * @param {object} rectangle A rectangle defined by two points (x1, y1), * (x2, y2) and height. * @param {array} quadCorners An array of the quad nodes' corners. * @return {array} An array of indexes containing one to * four integers. */ function _quadIndexes(rectangle, quadCorners) { var indexes = []; // Iterating through quads for (var i = 0; i < 4; i++) if ((rectangle.x2 >= quadCorners[i][0].x) && (rectangle.x1 <= quadCorners[i][1].x) && (rectangle.y1 + rectangle.height >= quadCorners[i][0].y) && (rectangle.y1 <= quadCorners[i][2].y)) indexes.push(i); return indexes; } /** * Get a list of indexes of nodes containing a non-axis-aligned rectangle * * @param {array} corners An array containing each corner of the * rectangle defined by its coordinates (x, y). * @param {array} quadCorners An array of the quad nodes' corners. * @return {array} An array of indexes containing one to * four integers. */ function _quadCollision(corners, quadCorners) { var indexes = []; // Iterating through quads for (var i = 0; i < 4; i++) if (_geom.collision(corners, quadCorners[i])) indexes.push(i); return indexes; } /** * Subdivide a quad by creating a node at a precise index. The function does * not generate all four nodes not to potentially create unused nodes. * * @param {integer} index The index of the node to create. * @param {object} quad The quad object to subdivide. * @return {object} A new quad representing the node created. */ function _quadSubdivide(index, quad) { var next = quad.level + 1, subw = Math.round(quad.bounds.width / 2), subh = Math.round(quad.bounds.height / 2), qx = Math.round(quad.bounds.x), qy = Math.round(quad.bounds.y), x, y; switch (index) { case 0: x = qx; y = qy; break; case 1: x = qx + subw; y = qy; break; case 2: x = qx; y = qy + subh; break; case 3: x = qx + subw; y = qy + subh; break; } return _quadTree( {x: x, y: y, width: subw, height: subh}, next, quad.maxElements, quad.maxLevel ); } /** * Recursively insert an element into the quadtree. Only points * with size, i.e. axis-aligned squares, may be inserted with this * method. * * @param {object} el The element to insert in the quadtree. * @param {object} sizedPoint A sized point defined by two top points * (x1, y1), (x2, y2) and height. * @param {object} quad The quad in which to insert the element. * @return {undefined} The function does not return anything. */ function _quadInsert(el, sizedPoint, quad) { if (quad.level < quad.maxLevel) { // Searching appropriate quads var indexes = _quadIndexes(sizedPoint, quad.corners); // Iterating for (var i = 0, l = indexes.length; i < l; i++) { // Subdividing if necessary if (quad.nodes[indexes[i]] === undefined) quad.nodes[indexes[i]] = _quadSubdivide(indexes[i], quad); // Recursion _quadInsert(el, sizedPoint, quad.nodes[indexes[i]]); } } else { // Pushing the element in a leaf node quad.elements.push(el); } } /** * Recursively retrieve every elements held by the node containing the * searched point. * * @param {object} point The searched point (x, y). * @param {object} quad The searched quad. * @return {array} An array of elements contained in the relevant * node. */ function _quadRetrievePoint(point, quad) { if (quad.level < quad.maxLevel) { var index = _quadIndex(point, quad.bounds); // If node does not exist we return an empty list if (quad.nodes[index] !== undefined) { return _quadRetrievePoint(point, quad.nodes[index]); } else { return []; } } else { return quad.elements; } } /** * Recursively retrieve every elements contained within an rectangular area * that may or may not be axis-aligned. * * @param {object|array} rectData The searched area defined either by * an array of four corners (x, y) in * the case of a non-axis-aligned * rectangle or an object with two top * points (x1, y1), (x2, y2) and height. * @param {object} quad The searched quad. * @param {function} collisionFunc The collision function used to search * for node indexes. * @param {array?} els The retrieved elements. * @return {array} An array of elements contained in the * area. */ function _quadRetrieveArea(rectData, quad, collisionFunc, els) { els = els || {}; if (quad.level < quad.maxLevel) { var indexes = collisionFunc(rectData, quad.corners); for (var i = 0, l = indexes.length; i < l; i++) if (quad.nodes[indexes[i]] !== undefined) _quadRetrieveArea( rectData, quad.nodes[indexes[i]], collisionFunc, els ); } else for (var j = 0, m = quad.elements.length; j < m; j++) if (els[quad.elements[j].id] === undefined) els[quad.elements[j].id] = quad.elements[j]; return els; } /** * Creates the quadtree object itself. * * @param {object} bounds The boundaries of the quad defined by an * origin (x, y), width and heigth. * @param {integer} level The level of the quad in the tree. * @param {integer} maxElements The max number of element in a leaf node. * @param {integer} maxLevel The max recursion level of the tree. * @return {object} The quadtree object. */ function _quadTree(bounds, level, maxElements, maxLevel) { return { level: level || 0, bounds: bounds, corners: _geom.splitSquare(bounds), maxElements: maxElements || 40, maxLevel: maxLevel || 8, elements: [], nodes: [] }; } /** * Sigma Quad Constructor * ---------------------- * * The edgequad API as exposed to sigma. */ /** * The edgequad core that will become the sigma interface with the quadtree. * * property {object} _tree Property holding the quadtree object. * property {object} _geom Exposition of the _geom namespace for testing. * property {object} _cache Cache for the area method. * property {boolean} _enabled Can index and retreive elements. */ var edgequad = function() { this._geom = _geom; this._tree = null; this._cache = { query: false, result: false }; this._enabled = true; }; /** * Index a graph by inserting its edges into the quadtree. * * @param {object} graph A graph instance. * @param {object} params An object of parameters with at least the quad * bounds. * @return {object} The quadtree object. * * Parameters: * ---------- * bounds: {object} boundaries of the quad defined by its origin (x, y) * width and heigth. * prefix: {string?} a prefix for edge geometric attributes. * maxElements: {integer?} the max number of elements in a leaf node. * maxLevel: {integer?} the max recursion level of the tree. */ edgequad.prototype.index = function(graph, params) { if (!this._enabled) return this._tree; // Enforcing presence of boundaries if (!params.bounds) throw 'sigma.classes.edgequad.index: bounds information not given.'; // Prefix var prefix = params.prefix || '', cp, source, target, n, e; // Building the tree this._tree = _quadTree( params.bounds, 0, params.maxElements, params.maxLevel ); var edges = graph.edges(); // Inserting graph edges into the tree for (var i = 0, l = edges.length; i < l; i++) { source = graph.nodes(edges[i].source); target = graph.nodes(edges[i].target); e = { x1: source[prefix + 'x'], y1: source[prefix + 'y'], x2: target[prefix + 'x'], y2: target[prefix + 'y'], size: edges[i][prefix + 'size'] || 0 }; // Inserting edge if (edges[i].type === 'curve' || edges[i].type === 'curvedArrow') { if (source.id === target.id) { n = { x: source[prefix + 'x'], y: source[prefix + 'y'], size: source[prefix + 'size'] || 0 }; _quadInsert( edges[i], _geom.selfLoopToSquare(n), this._tree); } else { cp = sigma.utils.getQuadraticControlPoint(e.x1, e.y1, e.x2, e.y2); _quadInsert( edges[i], _geom.quadraticCurveToSquare(e, cp), this._tree); } } else { _quadInsert( edges[i], _geom.lineToSquare(e), this._tree); } } // Reset cache: this._cache = { query: false, result: false }; // remove? return this._tree; }; /** * Retrieve every graph edges held by the quadtree node containing the * searched point. * * @param {number} x of the point. * @param {number} y of the point. * @return {array} An array of edges retrieved. */ edgequad.prototype.point = function(x, y) { if (!this._enabled) return []; return this._tree ? _quadRetrievePoint({x: x, y: y}, this._tree) || [] : []; }; /** * Retrieve every graph edges within a rectangular area. The methods keep the * last area queried in cache for optimization reason and will act differently * for the same reason if the area is axis-aligned or not. * * @param {object} A rectangle defined by two top points (x1, y1), (x2, y2) * and height. * @return {array} An array of edges retrieved. */ edgequad.prototype.area = function(rect) { if (!this._enabled) return []; var serialized = JSON.stringify(rect), collisionFunc, rectData; // Returning cache? if (this._cache.query === serialized) return this._cache.result; // Axis aligned ? if (_geom.isAxisAligned(rect)) { collisionFunc = _quadIndexes; rectData = _geom.axisAlignedTopPoints(rect); } else { collisionFunc = _quadCollision; rectData = _geom.rectangleCorners(rect); } // Retrieving edges var edges = this._tree ? _quadRetrieveArea( rectData, this._tree, collisionFunc ) : []; // Object to array var edgesArray = []; for (var i in edges) edgesArray.push(edges[i]); // Caching this._cache.query = serialized; this._cache.result = edgesArray; return edgesArray; }; /** * EXPORT: * ******* */ if (typeof this.sigma !== 'undefined') { this.sigma.classes = this.sigma.classes || {}; this.sigma.classes.edgequad = edgequad; } else if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) exports = module.exports = edgequad; exports.edgequad = edgequad; } else this.edgequad = edgequad; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.captors'); /** * The user inputs default captor. It deals with mouse events, keyboards * events and touch events. * * @param {DOMElement} target The DOM element where the listeners will be * bound. * @param {camera} camera The camera related to the target. * @param {configurable} settings The settings function. * @return {sigma.captor} The fresh new captor instance. */ sigma.captors.mouse = function(target, camera, settings) { var _self = this, _target = target, _camera = camera, _settings = settings, // CAMERA MANAGEMENT: // ****************** // The camera position when the user starts dragging: _startCameraX, _startCameraY, _startCameraAngle, // The latest stage position: _lastCameraX, _lastCameraY, _lastCameraAngle, _lastCameraRatio, // MOUSE MANAGEMENT: // ***************** // The mouse position when the user starts dragging: _startMouseX, _startMouseY, _isMouseDown, _isMoving, _hasDragged, _downStartTime, _movingTimeoutId; sigma.classes.dispatcher.extend(this); sigma.utils.doubleClick(_target, 'click', _doubleClickHandler); _target.addEventListener('DOMMouseScroll', _wheelHandler, false); _target.addEventListener('mousewheel', _wheelHandler, false); _target.addEventListener('mousemove', _moveHandler, false); _target.addEventListener('mousedown', _downHandler, false); _target.addEventListener('click', _clickHandler, false); _target.addEventListener('mouseout', _outHandler, false); document.addEventListener('mouseup', _upHandler, false); /** * This method unbinds every handlers that makes the captor work. */ this.kill = function() { sigma.utils.unbindDoubleClick(_target, 'click'); _target.removeEventListener('DOMMouseScroll', _wheelHandler); _target.removeEventListener('mousewheel', _wheelHandler); _target.removeEventListener('mousemove', _moveHandler); _target.removeEventListener('mousedown', _downHandler); _target.removeEventListener('click', _clickHandler); _target.removeEventListener('mouseout', _outHandler); document.removeEventListener('mouseup', _upHandler); }; // MOUSE EVENTS: // ************* /** * The handler listening to the 'move' mouse event. It will effectively * drag the graph. * * @param {event} e A mouse event. */ function _moveHandler(e) { var x, y, pos; // Dispatch event: if (_settings('mouseEnabled')) _self.dispatchEvent('mousemove', { x: sigma.utils.getX(e) - sigma.utils.getWidth(e) / 2, y: sigma.utils.getY(e) - sigma.utils.getHeight(e) / 2, clientX: e.clientX, clientY: e.clientY, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, shiftKey: e.shiftKey }); if (_settings('mouseEnabled') && _isMouseDown) { _isMoving = true; _hasDragged = true; if (_movingTimeoutId) clearTimeout(_movingTimeoutId); _movingTimeoutId = setTimeout(function() { _isMoving = false; }, _settings('dragTimeout')); sigma.misc.animation.killAll(_camera); _camera.isMoving = true; pos = _camera.cameraPosition( sigma.utils.getX(e) - _startMouseX, sigma.utils.getY(e) - _startMouseY, true ); x = _startCameraX - pos.x; y = _startCameraY - pos.y; if (x !== _camera.x || y !== _camera.y) { _lastCameraX = _camera.x; _lastCameraY = _camera.y; _camera.goTo({ x: x, y: y }); } if (e.preventDefault) e.preventDefault(); else e.returnValue = false; e.stopPropagation(); return false; } } /** * The handler listening to the 'up' mouse event. It will stop dragging the * graph. * * @param {event} e A mouse event. */ function _upHandler(e) { if (_settings('mouseEnabled') && _isMouseDown) { _isMouseDown = false; if (_movingTimeoutId) clearTimeout(_movingTimeoutId); _camera.isMoving = false; var x = sigma.utils.getX(e), y = sigma.utils.getY(e); if (_isMoving) { sigma.misc.animation.killAll(_camera); sigma.misc.animation.camera( _camera, { x: _camera.x + _settings('mouseInertiaRatio') * (_camera.x - _lastCameraX), y: _camera.y + _settings('mouseInertiaRatio') * (_camera.y - _lastCameraY) }, { easing: 'quadraticOut', duration: _settings('mouseInertiaDuration') } ); } else if ( _startMouseX !== x || _startMouseY !== y ) _camera.goTo({ x: _camera.x, y: _camera.y }); _self.dispatchEvent('mouseup', { x: x - sigma.utils.getWidth(e) / 2, y: y - sigma.utils.getHeight(e) / 2, clientX: e.clientX, clientY: e.clientY, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, shiftKey: e.shiftKey }); // Update _isMoving flag: _isMoving = false; } } /** * The handler listening to the 'down' mouse event. It will start observing * the mouse position for dragging the graph. * * @param {event} e A mouse event. */ function _downHandler(e) { if (_settings('mouseEnabled')) { _startCameraX = _camera.x; _startCameraY = _camera.y; _lastCameraX = _camera.x; _lastCameraY = _camera.y; _startMouseX = sigma.utils.getX(e); _startMouseY = sigma.utils.getY(e); _hasDragged = false; _downStartTime = (new Date()).getTime(); switch (e.which) { case 2: // Middle mouse button pressed // Do nothing. break; case 3: // Right mouse button pressed _self.dispatchEvent('rightclick', { x: _startMouseX - sigma.utils.getWidth(e) / 2, y: _startMouseY - sigma.utils.getHeight(e) / 2, clientX: e.clientX, clientY: e.clientY, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, shiftKey: e.shiftKey }); break; // case 1: default: // Left mouse button pressed _isMouseDown = true; _self.dispatchEvent('mousedown', { x: _startMouseX - sigma.utils.getWidth(e) / 2, y: _startMouseY - sigma.utils.getHeight(e) / 2, clientX: e.clientX, clientY: e.clientY, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, shiftKey: e.shiftKey }); } } } /** * The handler listening to the 'out' mouse event. It will just redispatch * the event. * * @param {event} e A mouse event. */ function _outHandler(e) { if (_settings('mouseEnabled')) _self.dispatchEvent('mouseout'); } /** * The handler listening to the 'click' mouse event. It will redispatch the * click event, but with normalized X and Y coordinates. * * @param {event} e A mouse event. */ function _clickHandler(e) { if (_settings('mouseEnabled')) _self.dispatchEvent('click', { x: sigma.utils.getX(e) - sigma.utils.getWidth(e) / 2, y: sigma.utils.getY(e) - sigma.utils.getHeight(e) / 2, clientX: e.clientX, clientY: e.clientY, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, shiftKey: e.shiftKey, isDragging: (((new Date()).getTime() - _downStartTime) > 100) && _hasDragged }); if (e.preventDefault) e.preventDefault(); else e.returnValue = false; e.stopPropagation(); return false; } /** * The handler listening to the double click custom event. It will * basically zoom into the graph. * * @param {event} e A mouse event. */ function _doubleClickHandler(e) { var pos, ratio, animation; if (_settings('mouseEnabled')) { ratio = 1 / _settings('doubleClickZoomingRatio'); _self.dispatchEvent('doubleclick', { x: _startMouseX - sigma.utils.getWidth(e) / 2, y: _startMouseY - sigma.utils.getHeight(e) / 2, clientX: e.clientX, clientY: e.clientY, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, shiftKey: e.shiftKey }); if (_settings('doubleClickEnabled')) { pos = _camera.cameraPosition( sigma.utils.getX(e) - sigma.utils.getWidth(e) / 2, sigma.utils.getY(e) - sigma.utils.getHeight(e) / 2, true ); animation = { duration: _settings('doubleClickZoomDuration') }; sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); } if (e.preventDefault) e.preventDefault(); else e.returnValue = false; e.stopPropagation(); return false; } } /** * The handler listening to the 'wheel' mouse event. It will basically zoom * in or not into the graph. * * @param {event} e A mouse event. */ function _wheelHandler(e) { var pos, ratio, animation; if (_settings('mouseEnabled') && _settings('mouseWheelEnabled')) { ratio = sigma.utils.getDelta(e) > 0 ? 1 / _settings('zoomingRatio') : _settings('zoomingRatio'); pos = _camera.cameraPosition( sigma.utils.getX(e) - sigma.utils.getWidth(e) / 2, sigma.utils.getY(e) - sigma.utils.getHeight(e) / 2, true ); animation = { duration: _settings('mouseZoomDuration') }; sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); if (e.preventDefault) e.preventDefault(); else e.returnValue = false; e.stopPropagation(); return false; } } }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.captors'); /** * The user inputs default captor. It deals with mouse events, keyboards * events and touch events. * * @param {DOMElement} target The DOM element where the listeners will be * bound. * @param {camera} camera The camera related to the target. * @param {configurable} settings The settings function. * @return {sigma.captor} The fresh new captor instance. */ sigma.captors.touch = function(target, camera, settings) { var _self = this, _target = target, _camera = camera, _settings = settings, // CAMERA MANAGEMENT: // ****************** // The camera position when the user starts dragging: _startCameraX, _startCameraY, _startCameraAngle, _startCameraRatio, // The latest stage position: _lastCameraX, _lastCameraY, _lastCameraAngle, _lastCameraRatio, // TOUCH MANAGEMENT: // ***************** // Touches that are down: _downTouches = [], _startTouchX0, _startTouchY0, _startTouchX1, _startTouchY1, _startTouchAngle, _startTouchDistance, _touchMode, _isMoving, _doubleTap, _movingTimeoutId; sigma.classes.dispatcher.extend(this); sigma.utils.doubleClick(_target, 'touchstart', _doubleTapHandler); _target.addEventListener('touchstart', _handleStart, false); _target.addEventListener('touchend', _handleLeave, false); _target.addEventListener('touchcancel', _handleLeave, false); _target.addEventListener('touchleave', _handleLeave, false); _target.addEventListener('touchmove', _handleMove, false); function position(e) { var offset = sigma.utils.getOffset(_target); return { x: e.pageX - offset.left, y: e.pageY - offset.top }; } /** * This method unbinds every handlers that makes the captor work. */ this.kill = function() { sigma.utils.unbindDoubleClick(_target, 'touchstart'); _target.addEventListener('touchstart', _handleStart); _target.addEventListener('touchend', _handleLeave); _target.addEventListener('touchcancel', _handleLeave); _target.addEventListener('touchleave', _handleLeave); _target.addEventListener('touchmove', _handleMove); }; // TOUCH EVENTS: // ************* /** * The handler listening to the 'touchstart' event. It will set the touch * mode ("_touchMode") and start observing the user touch moves. * * @param {event} e A touch event. */ function _handleStart(e) { if (_settings('touchEnabled')) { var x0, x1, y0, y1, pos0, pos1; _downTouches = e.touches; switch (_downTouches.length) { case 1: _camera.isMoving = true; _touchMode = 1; _startCameraX = _camera.x; _startCameraY = _camera.y; _lastCameraX = _camera.x; _lastCameraY = _camera.y; pos0 = position(_downTouches[0]); _startTouchX0 = pos0.x; _startTouchY0 = pos0.y; break; case 2: _camera.isMoving = true; _touchMode = 2; pos0 = position(_downTouches[0]); pos1 = position(_downTouches[1]); x0 = pos0.x; y0 = pos0.y; x1 = pos1.x; y1 = pos1.y; _lastCameraX = _camera.x; _lastCameraY = _camera.y; _startCameraAngle = _camera.angle; _startCameraRatio = _camera.ratio; _startCameraX = _camera.x; _startCameraY = _camera.y; _startTouchX0 = x0; _startTouchY0 = y0; _startTouchX1 = x1; _startTouchY1 = y1; _startTouchAngle = Math.atan2( _startTouchY1 - _startTouchY0, _startTouchX1 - _startTouchX0 ); _startTouchDistance = Math.sqrt( Math.pow(_startTouchY1 - _startTouchY0, 2) + Math.pow(_startTouchX1 - _startTouchX0, 2) ); e.preventDefault(); return false; } } } /** * The handler listening to the 'touchend', 'touchcancel' and 'touchleave' * event. It will update the touch mode if there are still at least one * finger, and stop dragging else. * * @param {event} e A touch event. */ function _handleLeave(e) { if (_settings('touchEnabled')) { _downTouches = e.touches; var inertiaRatio = _settings('touchInertiaRatio'); if (_movingTimeoutId) { _isMoving = false; clearTimeout(_movingTimeoutId); } switch (_touchMode) { case 2: if (e.touches.length === 1) { _handleStart(e); e.preventDefault(); break; } /* falls through */ case 1: _camera.isMoving = false; _self.dispatchEvent('stopDrag'); if (_isMoving) { _doubleTap = false; sigma.misc.animation.camera( _camera, { x: _camera.x + inertiaRatio * (_camera.x - _lastCameraX), y: _camera.y + inertiaRatio * (_camera.y - _lastCameraY) }, { easing: 'quadraticOut', duration: _settings('touchInertiaDuration') } ); } _isMoving = false; _touchMode = 0; break; } } } /** * The handler listening to the 'touchmove' event. It will effectively drag * the graph, and eventually zooms and turn it if the user is using two * fingers. * * @param {event} e A touch event. */ function _handleMove(e) { if (!_doubleTap && _settings('touchEnabled')) { var x0, x1, y0, y1, cos, sin, end, pos0, pos1, diff, start, dAngle, dRatio, newStageX, newStageY, newStageRatio, newStageAngle; _downTouches = e.touches; _isMoving = true; if (_movingTimeoutId) clearTimeout(_movingTimeoutId); _movingTimeoutId = setTimeout(function() { _isMoving = false; }, _settings('dragTimeout')); switch (_touchMode) { case 1: pos0 = position(_downTouches[0]); x0 = pos0.x; y0 = pos0.y; diff = _camera.cameraPosition( x0 - _startTouchX0, y0 - _startTouchY0, true ); newStageX = _startCameraX - diff.x; newStageY = _startCameraY - diff.y; if (newStageX !== _camera.x || newStageY !== _camera.y) { _lastCameraX = _camera.x; _lastCameraY = _camera.y; _camera.goTo({ x: newStageX, y: newStageY }); _self.dispatchEvent('mousemove', { x: pos0.x - sigma.utils.getWidth(e) / 2, y: pos0.y - sigma.utils.getHeight(e) / 2, clientX: e.clientX, clientY: e.clientY, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, shiftKey: e.shiftKey }); _self.dispatchEvent('drag'); } break; case 2: pos0 = position(_downTouches[0]); pos1 = position(_downTouches[1]); x0 = pos0.x; y0 = pos0.y; x1 = pos1.x; y1 = pos1.y; start = _camera.cameraPosition( (_startTouchX0 + _startTouchX1) / 2 - sigma.utils.getWidth(e) / 2, (_startTouchY0 + _startTouchY1) / 2 - sigma.utils.getHeight(e) / 2, true ); end = _camera.cameraPosition( (x0 + x1) / 2 - sigma.utils.getWidth(e) / 2, (y0 + y1) / 2 - sigma.utils.getHeight(e) / 2, true ); dAngle = Math.atan2(y1 - y0, x1 - x0) - _startTouchAngle; dRatio = Math.sqrt( Math.pow(y1 - y0, 2) + Math.pow(x1 - x0, 2) ) / _startTouchDistance; // Translation: x0 = start.x; y0 = start.y; // Homothetic transformation: newStageRatio = _startCameraRatio / dRatio; x0 = x0 * dRatio; y0 = y0 * dRatio; // Rotation: newStageAngle = _startCameraAngle - dAngle; cos = Math.cos(-dAngle); sin = Math.sin(-dAngle); x1 = x0 * cos + y0 * sin; y1 = y0 * cos - x0 * sin; x0 = x1; y0 = y1; // Finalize: newStageX = x0 - end.x + _startCameraX; newStageY = y0 - end.y + _startCameraY; if ( newStageRatio !== _camera.ratio || newStageAngle !== _camera.angle || newStageX !== _camera.x || newStageY !== _camera.y ) { _lastCameraX = _camera.x; _lastCameraY = _camera.y; _lastCameraAngle = _camera.angle; _lastCameraRatio = _camera.ratio; _camera.goTo({ x: newStageX, y: newStageY, angle: newStageAngle, ratio: newStageRatio }); _self.dispatchEvent('drag'); } break; } e.preventDefault(); return false; } } /** * The handler listening to the double tap custom event. It will * basically zoom into the graph. * * @param {event} e A touch event. */ function _doubleTapHandler(e) { var pos, ratio, animation; if (e.touches && e.touches.length === 1 && _settings('touchEnabled')) { _doubleTap = true; ratio = 1 / _settings('doubleClickZoomingRatio'); pos = position(e.touches[0]); _self.dispatchEvent('doubleclick', { x: pos.x - sigma.utils.getWidth(e) / 2, y: pos.y - sigma.utils.getHeight(e) / 2, clientX: e.clientX, clientY: e.clientY, ctrlKey: e.ctrlKey, metaKey: e.metaKey, altKey: e.altKey, shiftKey: e.shiftKey }); if (_settings('doubleClickEnabled')) { pos = _camera.cameraPosition( pos.x - sigma.utils.getWidth(e) / 2, pos.y - sigma.utils.getHeight(e) / 2, true ); animation = { duration: _settings('doubleClickZoomDuration'), onComplete: function() { _doubleTap = false; } }; sigma.utils.zoomTo(_camera, pos.x, pos.y, ratio, animation); } if (e.preventDefault) e.preventDefault(); else e.returnValue = false; e.stopPropagation(); return false; } } }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; if (typeof conrad === 'undefined') throw 'conrad is not declared'; // Initialize packages: sigma.utils.pkg('sigma.renderers'); /** * This function is the constructor of the canvas sigma's renderer. * * @param {sigma.classes.graph} graph The graph to render. * @param {sigma.classes.camera} camera The camera. * @param {configurable} settings The sigma instance settings * function. * @param {object} object The options object. * @return {sigma.renderers.canvas} The renderer instance. */ sigma.renderers.canvas = function(graph, camera, settings, options) { if (typeof options !== 'object') throw 'sigma.renderers.canvas: Wrong arguments.'; if (!(options.container instanceof HTMLElement)) throw 'Container not found.'; var k, i, l, a, fn, self = this; sigma.classes.dispatcher.extend(this); // Initialize main attributes: Object.defineProperty(this, 'conradId', { value: sigma.utils.id() }); this.graph = graph; this.camera = camera; this.contexts = {}; this.domElements = {}; this.options = options; this.container = this.options.container; this.settings = ( typeof options.settings === 'object' && options.settings ) ? settings.embedObjects(options.settings) : settings; // Node indexes: this.nodesOnScreen = []; this.edgesOnScreen = []; // Conrad related attributes: this.jobs = {}; // Find the prefix: this.options.prefix = 'renderer' + this.conradId + ':'; // Initialize the DOM elements: if ( !this.settings('batchEdgesDrawing') ) { this.initDOM('canvas', 'scene'); this.contexts.edges = this.contexts.scene; this.contexts.nodes = this.contexts.scene; this.contexts.labels = this.contexts.scene; } else { this.initDOM('canvas', 'edges'); this.initDOM('canvas', 'scene'); this.contexts.nodes = this.contexts.scene; this.contexts.labels = this.contexts.scene; } this.initDOM('canvas', 'mouse'); this.contexts.hover = this.contexts.mouse; // Initialize captors: this.captors = []; a = this.options.captors || [sigma.captors.mouse, sigma.captors.touch]; for (i = 0, l = a.length; i < l; i++) { fn = typeof a[i] === 'function' ? a[i] : sigma.captors[a[i]]; this.captors.push( new fn( this.domElements.mouse, this.camera, this.settings ) ); } // Deal with sigma events: sigma.misc.bindEvents.call(this, this.options.prefix); sigma.misc.drawHovers.call(this, this.options.prefix); this.resize(false); }; /** * This method renders the graph on the canvases. * * @param {?object} options Eventually an object of options. * @return {sigma.renderers.canvas} Returns the instance itself. */ sigma.renderers.canvas.prototype.render = function(options) { options = options || {}; var a, i, k, l, o, id, end, job, start, edges, renderers, rendererType, batchSize, tempGCO, index = {}, graph = this.graph, nodes = this.graph.nodes, prefix = this.options.prefix || '', drawEdges = this.settings(options, 'drawEdges'), drawNodes = this.settings(options, 'drawNodes'), drawLabels = this.settings(options, 'drawLabels'), drawEdgeLabels = this.settings(options, 'drawEdgeLabels'), embedSettings = this.settings.embedObjects(options, { prefix: this.options.prefix }); // Call the resize function: this.resize(false); // Check the 'hideEdgesOnMove' setting: if (this.settings(options, 'hideEdgesOnMove')) if (this.camera.isAnimated || this.camera.isMoving) drawEdges = false; // Apply the camera's view: this.camera.applyView( undefined, this.options.prefix, { width: this.width, height: this.height } ); // Clear canvases: this.clear(); // Kill running jobs: for (k in this.jobs) if (conrad.hasJob(k)) conrad.killJob(k); // Find which nodes are on screen: this.edgesOnScreen = []; this.nodesOnScreen = this.camera.quadtree.area( this.camera.getRectangle(this.width, this.height) ); for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++) index[a[i].id] = a[i]; // Draw edges: // - If settings('batchEdgesDrawing') is true, the edges are displayed per // batches. If not, they are drawn in one frame. if (drawEdges) { // First, let's identify which edges to draw. To do this, we just keep // every edges that have at least one extremity displayed according to // the quadtree and the "hidden" attribute. We also do not keep hidden // edges. for (a = graph.edges(), i = 0, l = a.length; i < l; i++) { o = a[i]; if ( (index[o.source] || index[o.target]) && (!o.hidden && !nodes(o.source).hidden && !nodes(o.target).hidden) ) this.edgesOnScreen.push(o); } // If the "batchEdgesDrawing" settings is true, edges are batched: if (this.settings(options, 'batchEdgesDrawing')) { id = 'edges_' + this.conradId; batchSize = embedSettings('canvasEdgesBatchSize'); edges = this.edgesOnScreen; l = edges.length; start = 0; end = Math.min(edges.length, start + batchSize); job = function() { tempGCO = this.contexts.edges.globalCompositeOperation; this.contexts.edges.globalCompositeOperation = 'destination-over'; renderers = sigma.canvas.edges; for (i = start; i < end; i++) { o = edges[i]; (renderers[ o.type || this.settings(options, 'defaultEdgeType') ] || renderers.def)( o, graph.nodes(o.source), graph.nodes(o.target), this.contexts.edges, embedSettings ); } // Draw edge labels: if (drawEdgeLabels) { renderers = sigma.canvas.edges.labels; for (i = start; i < end; i++) { o = edges[i]; if (!o.hidden) (renderers[ o.type || this.settings(options, 'defaultEdgeType') ] || renderers.def)( o, graph.nodes(o.source), graph.nodes(o.target), this.contexts.labels, embedSettings ); } } // Restore original globalCompositeOperation: this.contexts.edges.globalCompositeOperation = tempGCO; // Catch job's end: if (end === edges.length) { delete this.jobs[id]; return false; } start = end + 1; end = Math.min(edges.length, start + batchSize); return true; }; this.jobs[id] = job; conrad.addJob(id, job.bind(this)); // If not, they are drawn in one frame: } else { renderers = sigma.canvas.edges; for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) { o = a[i]; (renderers[ o.type || this.settings(options, 'defaultEdgeType') ] || renderers.def)( o, graph.nodes(o.source), graph.nodes(o.target), this.contexts.edges, embedSettings ); } // Draw edge labels: // - No batching if (drawEdgeLabels) { renderers = sigma.canvas.edges.labels; for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) if (!a[i].hidden) (renderers[ a[i].type || this.settings(options, 'defaultEdgeType') ] || renderers.def)( a[i], graph.nodes(a[i].source), graph.nodes(a[i].target), this.contexts.labels, embedSettings ); } } } // Draw nodes: // - No batching if (drawNodes) { renderers = sigma.canvas.nodes; for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++) if (!a[i].hidden) (renderers[ a[i].type || this.settings(options, 'defaultNodeType') ] || renderers.def)( a[i], this.contexts.nodes, embedSettings ); } // Draw labels: // - No batching if (drawLabels) { renderers = sigma.canvas.labels; for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++) if (!a[i].hidden) (renderers[ a[i].type || this.settings(options, 'defaultNodeType') ] || renderers.def)( a[i], this.contexts.labels, embedSettings ); } this.dispatchEvent('render'); return this; }; /** * This method creates a DOM element of the specified type, switches its * position to "absolute", references it to the domElements attribute, and * finally appends it to the container. * * @param {string} tag The label tag. * @param {string} id The id of the element (to store it in "domElements"). */ sigma.renderers.canvas.prototype.initDOM = function(tag, id) { var dom = document.createElement(tag); dom.style.position = 'absolute'; dom.setAttribute('class', 'sigma-' + id); this.domElements[id] = dom; this.container.appendChild(dom); if (tag.toLowerCase() === 'canvas') this.contexts[id] = dom.getContext('2d'); }; /** * This method resizes each DOM elements in the container and stores the new * dimensions. Then, it renders the graph. * * @param {?number} width The new width of the container. * @param {?number} height The new height of the container. * @return {sigma.renderers.canvas} Returns the instance itself. */ sigma.renderers.canvas.prototype.resize = function(w, h) { var k, oldWidth = this.width, oldHeight = this.height, pixelRatio = 1; // TODO: // ***** // This pixelRatio is the solution to display with the good definition // on canvases on Retina displays (ie oversampling). Unfortunately, it // has a huge performance cost... // > pixelRatio = window.devicePixelRatio || 1; if (w !== undefined && h !== undefined) { this.width = w; this.height = h; } else { this.width = this.container.offsetWidth; this.height = this.container.offsetHeight; w = this.width; h = this.height; } if (oldWidth !== this.width || oldHeight !== this.height) { for (k in this.domElements) { this.domElements[k].style.width = w + 'px'; this.domElements[k].style.height = h + 'px'; if (this.domElements[k].tagName.toLowerCase() === 'canvas') { this.domElements[k].setAttribute('width', (w * pixelRatio) + 'px'); this.domElements[k].setAttribute('height', (h * pixelRatio) + 'px'); if (pixelRatio !== 1) this.contexts[k].scale(pixelRatio, pixelRatio); } } } return this; }; /** * This method clears each canvas. * * @return {sigma.renderers.canvas} Returns the instance itself. */ sigma.renderers.canvas.prototype.clear = function() { var k; for (k in this.domElements) if (this.domElements[k].tagName === 'CANVAS') this.domElements[k].width = this.domElements[k].width; return this; }; /** * This method kills contexts and other attributes. */ sigma.renderers.canvas.prototype.kill = function() { var k, captor; // Kill captors: while ((captor = this.captors.pop())) captor.kill(); delete this.captors; // Kill contexts: for (k in this.domElements) { this.domElements[k].parentNode.removeChild(this.domElements[k]); delete this.domElements[k]; delete this.contexts[k]; } delete this.domElements; delete this.contexts; }; /** * The labels, nodes and edges renderers are stored in the three following * objects. When an element is drawn, its type will be checked and if a * renderer with the same name exists, it will be used. If not found, the * default renderer will be used instead. * * They are stored in different files, in the "./canvas" folder. */ sigma.utils.pkg('sigma.canvas.nodes'); sigma.utils.pkg('sigma.canvas.edges'); sigma.utils.pkg('sigma.canvas.labels'); }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.renderers'); /** * This function is the constructor of the canvas sigma's renderer. * * @param {sigma.classes.graph} graph The graph to render. * @param {sigma.classes.camera} camera The camera. * @param {configurable} settings The sigma instance settings * function. * @param {object} object The options object. * @return {sigma.renderers.canvas} The renderer instance. */ sigma.renderers.webgl = function(graph, camera, settings, options) { if (typeof options !== 'object') throw 'sigma.renderers.webgl: Wrong arguments.'; if (!(options.container instanceof HTMLElement)) throw 'Container not found.'; var k, i, l, a, fn, _self = this; sigma.classes.dispatcher.extend(this); // Conrad related attributes: this.jobs = {}; Object.defineProperty(this, 'conradId', { value: sigma.utils.id() }); // Initialize main attributes: this.graph = graph; this.camera = camera; this.contexts = {}; this.domElements = {}; this.options = options; this.container = this.options.container; this.settings = ( typeof options.settings === 'object' && options.settings ) ? settings.embedObjects(options.settings) : settings; // Find the prefix: this.options.prefix = this.camera.readPrefix; // Initialize programs hash Object.defineProperty(this, 'nodePrograms', { value: {} }); Object.defineProperty(this, 'edgePrograms', { value: {} }); Object.defineProperty(this, 'nodeFloatArrays', { value: {} }); Object.defineProperty(this, 'edgeFloatArrays', { value: {} }); // Initialize the DOM elements: if (this.settings(options, 'batchEdgesDrawing')) { this.initDOM('canvas', 'edges', true); this.initDOM('canvas', 'nodes', true); } else { this.initDOM('canvas', 'scene', true); this.contexts.nodes = this.contexts.scene; this.contexts.edges = this.contexts.scene; } this.initDOM('canvas', 'labels'); this.initDOM('canvas', 'mouse'); this.contexts.hover = this.contexts.mouse; // Initialize captors: this.captors = []; a = this.options.captors || [sigma.captors.mouse, sigma.captors.touch]; for (i = 0, l = a.length; i < l; i++) { fn = typeof a[i] === 'function' ? a[i] : sigma.captors[a[i]]; this.captors.push( new fn( this.domElements.mouse, this.camera, this.settings ) ); } // Deal with sigma events: sigma.misc.bindEvents.call(this, this.camera.prefix); sigma.misc.drawHovers.call(this, this.camera.prefix); this.resize(); }; /** * This method will generate the nodes and edges float arrays. This step is * separated from the "render" method, because to keep WebGL efficient, since * all the camera and middlewares are modelised as matrices and they do not * require the float arrays to be regenerated. * * Basically, when the user moves the camera or applies some specific linear * transformations, this process step will be skipped, and the "render" * method will efficiently refresh the rendering. * * And when the user modifies the graph colors or positions (applying a new * layout or filtering the colors, for instance), this "process" step will be * required to regenerate the float arrays. * * @return {sigma.renderers.webgl} Returns the instance itself. */ sigma.renderers.webgl.prototype.process = function() { var a, i, l, k, type, renderer, graph = this.graph, options = sigma.utils.extend(options, this.options); // Empty float arrays: for (k in this.nodeFloatArrays) delete this.nodeFloatArrays[k]; for (k in this.edgeFloatArrays) delete this.edgeFloatArrays[k]; // Sort edges and nodes per types: for (a = graph.edges(), i = 0, l = a.length; i < l; i++) { type = a[i].type || this.settings(options, 'defaultEdgeType'); k = (type && sigma.webgl.edges[type]) ? type : 'def'; if (!this.edgeFloatArrays[k]) this.edgeFloatArrays[k] = { edges: [] }; this.edgeFloatArrays[k].edges.push(a[i]); } for (a = graph.nodes(), i = 0, l = a.length; i < l; i++) { type = a[i].type || this.settings(options, 'defaultNodeType'); k = (type && sigma.webgl.nodes[type]) ? type : 'def'; if (!this.nodeFloatArrays[k]) this.nodeFloatArrays[k] = { nodes: [] }; this.nodeFloatArrays[k].nodes.push(a[i]); } // Push edges: for (k in this.edgeFloatArrays) { renderer = sigma.webgl.edges[k]; for (a = this.edgeFloatArrays[k].edges, i = 0, l = a.length; i < l; i++) { if (!this.edgeFloatArrays[k].array) this.edgeFloatArrays[k].array = new Float32Array( a.length * renderer.POINTS * renderer.ATTRIBUTES ); // Just check that the edge and both its extremities are visible: if ( !a[i].hidden && !graph.nodes(a[i].source).hidden && !graph.nodes(a[i].target).hidden ) renderer.addEdge( a[i], graph.nodes(a[i].source), graph.nodes(a[i].target), this.edgeFloatArrays[k].array, i * renderer.POINTS * renderer.ATTRIBUTES, options.prefix, this.settings ); } } // Push nodes: for (k in this.nodeFloatArrays) { renderer = sigma.webgl.nodes[k]; for (a = this.nodeFloatArrays[k].nodes, i = 0, l = a.length; i < l; i++) { if (!this.nodeFloatArrays[k].array) this.nodeFloatArrays[k].array = new Float32Array( a.length * renderer.POINTS * renderer.ATTRIBUTES ); // Just check that the edge and both its extremities are visible: if ( !a[i].hidden ) renderer.addNode( a[i], this.nodeFloatArrays[k].array, i * renderer.POINTS * renderer.ATTRIBUTES, options.prefix, this.settings ); } } return this; }; /** * This method renders the graph. It basically calls each program (and * generate them if they do not exist yet) to render nodes and edges, batched * per renderer. * * As in the canvas renderer, it is possible to display edges, nodes and / or * labels in batches, to make the whole thing way more scalable. * * @param {?object} params Eventually an object of options. * @return {sigma.renderers.webgl} Returns the instance itself. */ sigma.renderers.webgl.prototype.render = function(params) { var a, i, l, k, o, program, renderer, self = this, graph = this.graph, nodesGl = this.contexts.nodes, edgesGl = this.contexts.edges, matrix = this.camera.getMatrix(), options = sigma.utils.extend(params, this.options), drawLabels = this.settings(options, 'drawLabels'), drawEdges = this.settings(options, 'drawEdges'), drawNodes = this.settings(options, 'drawNodes'); // Call the resize function: this.resize(false); // Check the 'hideEdgesOnMove' setting: if (this.settings(options, 'hideEdgesOnMove')) if (this.camera.isAnimated || this.camera.isMoving) drawEdges = false; // Clear canvases: this.clear(); // Translate matrix to [width/2, height/2]: matrix = sigma.utils.matrices.multiply( matrix, sigma.utils.matrices.translation(this.width / 2, this.height / 2) ); // Kill running jobs: for (k in this.jobs) if (conrad.hasJob(k)) conrad.killJob(k); if (drawEdges) { if (this.settings(options, 'batchEdgesDrawing')) (function() { var a, k, i, id, job, arr, end, start, renderer, batchSize, currentProgram; id = 'edges_' + this.conradId; batchSize = this.settings(options, 'webglEdgesBatchSize'); a = Object.keys(this.edgeFloatArrays); if (!a.length) return; i = 0; renderer = sigma.webgl.edges[a[i]]; arr = this.edgeFloatArrays[a[i]].array; start = 0; end = Math.min( start + batchSize * renderer.POINTS, arr.length / renderer.ATTRIBUTES ); job = function() { // Check program: if (!this.edgePrograms[a[i]]) this.edgePrograms[a[i]] = renderer.initProgram(edgesGl); if (start < end) { edgesGl.useProgram(this.edgePrograms[a[i]]); renderer.render( edgesGl, this.edgePrograms[a[i]], arr, { settings: this.settings, matrix: matrix, width: this.width, height: this.height, ratio: this.camera.ratio, scalingRatio: this.settings( options, 'webglOversamplingRatio' ), start: start, count: end - start } ); } // Catch job's end: if ( end >= arr.length / renderer.ATTRIBUTES && i === a.length - 1 ) { delete this.jobs[id]; return false; } if (end >= arr.length / renderer.ATTRIBUTES) { i++; arr = this.edgeFloatArrays[a[i]].array; renderer = sigma.webgl.edges[a[i]]; start = 0; end = Math.min( start + batchSize * renderer.POINTS, arr.length / renderer.ATTRIBUTES ); } else { start = end; end = Math.min( start + batchSize * renderer.POINTS, arr.length / renderer.ATTRIBUTES ); } return true; }; this.jobs[id] = job; conrad.addJob(id, job.bind(this)); }).call(this); else { for (k in this.edgeFloatArrays) { renderer = sigma.webgl.edges[k]; // Check program: if (!this.edgePrograms[k]) this.edgePrograms[k] = renderer.initProgram(edgesGl); // Render if (this.edgeFloatArrays[k]) { edgesGl.useProgram(this.edgePrograms[k]); renderer.render( edgesGl, this.edgePrograms[k], this.edgeFloatArrays[k].array, { settings: this.settings, matrix: matrix, width: this.width, height: this.height, ratio: this.camera.ratio, scalingRatio: this.settings(options, 'webglOversamplingRatio') } ); } } } } if (drawNodes) { // Enable blending: nodesGl.blendFunc(nodesGl.SRC_ALPHA, nodesGl.ONE_MINUS_SRC_ALPHA); nodesGl.enable(nodesGl.BLEND); for (k in this.nodeFloatArrays) { renderer = sigma.webgl.nodes[k]; // Check program: if (!this.nodePrograms[k]) this.nodePrograms[k] = renderer.initProgram(nodesGl); // Render if (this.nodeFloatArrays[k]) { nodesGl.useProgram(this.nodePrograms[k]); renderer.render( nodesGl, this.nodePrograms[k], this.nodeFloatArrays[k].array, { settings: this.settings, matrix: matrix, width: this.width, height: this.height, ratio: this.camera.ratio, scalingRatio: this.settings(options, 'webglOversamplingRatio') } ); } } } if (drawLabels) { a = this.camera.quadtree.area( this.camera.getRectangle(this.width, this.height) ); // Apply camera view to these nodes: this.camera.applyView( undefined, undefined, { nodes: a, edges: [], width: this.width, height: this.height } ); o = function(key) { return self.settings({ prefix: self.camera.prefix }, key); }; for (i = 0, l = a.length; i < l; i++) if (!a[i].hidden) ( sigma.canvas.labels[ a[i].type || this.settings(options, 'defaultNodeType') ] || sigma.canvas.labels.def )(a[i], this.contexts.labels, o); } this.dispatchEvent('render'); return this; }; /** * This method creates a DOM element of the specified type, switches its * position to "absolute", references it to the domElements attribute, and * finally appends it to the container. * * @param {string} tag The label tag. * @param {string} id The id of the element (to store it in * "domElements"). * @param {?boolean} webgl Will init the WebGL context if true. */ sigma.renderers.webgl.prototype.initDOM = function(tag, id, webgl) { var gl, dom = document.createElement(tag), self = this; dom.style.position = 'absolute'; dom.setAttribute('class', 'sigma-' + id); this.domElements[id] = dom; this.container.appendChild(dom); if (tag.toLowerCase() === 'canvas') { this.contexts[id] = dom.getContext(webgl ? 'experimental-webgl' : '2d', { preserveDrawingBuffer: true }); // Adding webgl context loss listeners if (webgl) { dom.addEventListener('webglcontextlost', function(e) { e.preventDefault(); }, false); dom.addEventListener('webglcontextrestored', function(e) { self.render(); }, false); } } }; /** * This method resizes each DOM elements in the container and stores the new * dimensions. Then, it renders the graph. * * @param {?number} width The new width of the container. * @param {?number} height The new height of the container. * @return {sigma.renderers.webgl} Returns the instance itself. */ sigma.renderers.webgl.prototype.resize = function(w, h) { var k, oldWidth = this.width, oldHeight = this.height; if (w !== undefined && h !== undefined) { this.width = w; this.height = h; } else { this.width = this.container.offsetWidth; this.height = this.container.offsetHeight; w = this.width; h = this.height; } if (oldWidth !== this.width || oldHeight !== this.height) { for (k in this.domElements) { this.domElements[k].style.width = w + 'px'; this.domElements[k].style.height = h + 'px'; if (this.domElements[k].tagName.toLowerCase() === 'canvas') { // If simple 2D canvas: if (this.contexts[k] && this.contexts[k].scale) { this.domElements[k].setAttribute('width', w + 'px'); this.domElements[k].setAttribute('height', h + 'px'); } else { this.domElements[k].setAttribute( 'width', (w * this.settings('webglOversamplingRatio')) + 'px' ); this.domElements[k].setAttribute( 'height', (h * this.settings('webglOversamplingRatio')) + 'px' ); } } } } // Scale: for (k in this.contexts) if (this.contexts[k] && this.contexts[k].viewport) this.contexts[k].viewport( 0, 0, this.width * this.settings('webglOversamplingRatio'), this.height * this.settings('webglOversamplingRatio') ); return this; }; /** * This method clears each canvas. * * @return {sigma.renderers.webgl} Returns the instance itself. */ sigma.renderers.webgl.prototype.clear = function() { var k; for (k in this.domElements) if (this.domElements[k].tagName === 'CANVAS') this.domElements[k].width = this.domElements[k].width; this.contexts.nodes.clear(this.contexts.nodes.COLOR_BUFFER_BIT); this.contexts.edges.clear(this.contexts.edges.COLOR_BUFFER_BIT); return this; }; /** * This method kills contexts and other attributes. */ sigma.renderers.webgl.prototype.kill = function() { var k, captor; // Kill captors: while ((captor = this.captors.pop())) captor.kill(); delete this.captors; // Kill contexts: for (k in this.domElements) { this.domElements[k].parentNode.removeChild(this.domElements[k]); delete this.domElements[k]; delete this.contexts[k]; } delete this.domElements; delete this.contexts; }; /** * The object "sigma.webgl.nodes" contains the different WebGL node * renderers. The default one draw nodes as discs. Here are the attributes * any node renderer must have: * * {number} POINTS The number of points required to draw a node. * {number} ATTRIBUTES The number of attributes needed to draw one point. * {function} addNode A function that adds a node to the data stack that * will be given to the buffer. Here is the arguments: * > {object} node * > {number} index The node index in the * nodes array. * > {Float32Array} data The stack. * > {object} options Some options. * {function} render The function that will effectively render the nodes * into the buffer. * > {WebGLRenderingContext} gl * > {WebGLProgram} program * > {Float32Array} data The stack to give to the * buffer. * > {object} params An object containing some * options, like width, * height, the camera ratio. * {function} initProgram The function that will initiate the program, with * the relevant shaders and parameters. It must return * the newly created program. * * Check sigma.webgl.nodes.def or sigma.webgl.nodes.fast to see how it * works more precisely. */ sigma.utils.pkg('sigma.webgl.nodes'); /** * The object "sigma.webgl.edges" contains the different WebGL edge * renderers. The default one draw edges as direct lines. Here are the * attributes any edge renderer must have: * * {number} POINTS The number of points required to draw an edge. * {number} ATTRIBUTES The number of attributes needed to draw one point. * {function} addEdge A function that adds an edge to the data stack that * will be given to the buffer. Here is the arguments: * > {object} edge * > {object} source * > {object} target * > {Float32Array} data The stack. * > {object} options Some options. * {function} render The function that will effectively render the edges * into the buffer. * > {WebGLRenderingContext} gl * > {WebGLProgram} program * > {Float32Array} data The stack to give to the * buffer. * > {object} params An object containing some * options, like width, * height, the camera ratio. * {function} initProgram The function that will initiate the program, with * the relevant shaders and parameters. It must return * the newly created program. * * Check sigma.webgl.edges.def or sigma.webgl.edges.fast to see how it * works more precisely. */ sigma.utils.pkg('sigma.webgl.edges'); /** * The object "sigma.canvas.labels" contains the different * label renderers for the WebGL renderer. Since displaying texts in WebGL is * definitely painful and since there a way less labels to display than nodes * or edges, the default renderer simply renders them in a canvas. * * A labels renderer is a simple function, taking as arguments the related * node, the renderer and a settings function. */ sigma.utils.pkg('sigma.canvas.labels'); }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; if (typeof conrad === 'undefined') throw 'conrad is not declared'; // Initialize packages: sigma.utils.pkg('sigma.renderers'); /** * This function is the constructor of the svg sigma's renderer. * * @param {sigma.classes.graph} graph The graph to render. * @param {sigma.classes.camera} camera The camera. * @param {configurable} settings The sigma instance settings * function. * @param {object} object The options object. * @return {sigma.renderers.svg} The renderer instance. */ sigma.renderers.svg = function(graph, camera, settings, options) { if (typeof options !== 'object') throw 'sigma.renderers.svg: Wrong arguments.'; if (!(options.container instanceof HTMLElement)) throw 'Container not found.'; var i, l, a, fn, self = this; sigma.classes.dispatcher.extend(this); // Initialize main attributes: this.graph = graph; this.camera = camera; this.domElements = { graph: null, groups: {}, nodes: {}, edges: {}, labels: {}, hovers: {} }; this.measurementCanvas = null; this.options = options; this.container = this.options.container; this.settings = ( typeof options.settings === 'object' && options.settings ) ? settings.embedObjects(options.settings) : settings; // Is the renderer meant to be freestyle? this.settings('freeStyle', !!this.options.freeStyle); // SVG xmlns this.settings('xmlns', 'http://www.w3.org/2000/svg'); // Indexes: this.nodesOnScreen = []; this.edgesOnScreen = []; // Find the prefix: this.options.prefix = 'renderer' + sigma.utils.id() + ':'; // Initialize the DOM elements this.initDOM('svg'); // Initialize captors: this.captors = []; a = this.options.captors || [sigma.captors.mouse, sigma.captors.touch]; for (i = 0, l = a.length; i < l; i++) { fn = typeof a[i] === 'function' ? a[i] : sigma.captors[a[i]]; this.captors.push( new fn( this.domElements.graph, this.camera, this.settings ) ); } // Bind resize: window.addEventListener('resize', function() { self.resize(); }); // Deal with sigma events: // TODO: keep an option to override the DOM events? sigma.misc.bindDOMEvents.call(this, this.domElements.graph); this.bindHovers(this.options.prefix); // Resize this.resize(false); }; /** * This method renders the graph on the svg scene. * * @param {?object} options Eventually an object of options. * @return {sigma.renderers.svg} Returns the instance itself. */ sigma.renderers.svg.prototype.render = function(options) { options = options || {}; var a, i, k, e, l, o, source, target, start, edges, renderers, subrenderers, index = {}, graph = this.graph, nodes = this.graph.nodes, prefix = this.options.prefix || '', drawEdges = this.settings(options, 'drawEdges'), drawNodes = this.settings(options, 'drawNodes'), drawLabels = this.settings(options, 'drawLabels'), embedSettings = this.settings.embedObjects(options, { prefix: this.options.prefix, forceLabels: this.options.forceLabels }); // Check the 'hideEdgesOnMove' setting: if (this.settings(options, 'hideEdgesOnMove')) if (this.camera.isAnimated || this.camera.isMoving) drawEdges = false; // Apply the camera's view: this.camera.applyView( undefined, this.options.prefix, { width: this.width, height: this.height } ); // Hiding everything // TODO: find a more sensible way to perform this operation this.hideDOMElements(this.domElements.nodes); this.hideDOMElements(this.domElements.edges); this.hideDOMElements(this.domElements.labels); // Find which nodes are on screen this.edgesOnScreen = []; this.nodesOnScreen = this.camera.quadtree.area( this.camera.getRectangle(this.width, this.height) ); // Node index for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++) index[a[i].id] = a[i]; // Find which edges are on screen for (a = graph.edges(), i = 0, l = a.length; i < l; i++) { o = a[i]; if ( (index[o.source] || index[o.target]) && (!o.hidden && !nodes(o.source).hidden && !nodes(o.target).hidden) ) this.edgesOnScreen.push(o); } // Display nodes //--------------- renderers = sigma.svg.nodes; subrenderers = sigma.svg.labels; //-- First we create the nodes which are not already created if (drawNodes) for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++) { if (!a[i].hidden && !this.domElements.nodes[a[i].id]) { // Node e = (renderers[a[i].type] || renderers.def).create( a[i], embedSettings ); this.domElements.nodes[a[i].id] = e; this.domElements.groups.nodes.appendChild(e); // Label e = (subrenderers[a[i].type] || subrenderers.def).create( a[i], embedSettings ); this.domElements.labels[a[i].id] = e; this.domElements.groups.labels.appendChild(e); } } //-- Second we update the nodes if (drawNodes) for (a = this.nodesOnScreen, i = 0, l = a.length; i < l; i++) { if (a[i].hidden) continue; // Node (renderers[a[i].type] || renderers.def).update( a[i], this.domElements.nodes[a[i].id], embedSettings ); // Label (subrenderers[a[i].type] || subrenderers.def).update( a[i], this.domElements.labels[a[i].id], embedSettings ); } // Display edges //--------------- renderers = sigma.svg.edges; //-- First we create the edges which are not already created if (drawEdges) for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) { if (!this.domElements.edges[a[i].id]) { source = nodes(a[i].source); target = nodes(a[i].target); e = (renderers[a[i].type] || renderers.def).create( a[i], source, target, embedSettings ); this.domElements.edges[a[i].id] = e; this.domElements.groups.edges.appendChild(e); } } //-- Second we update the edges if (drawEdges) for (a = this.edgesOnScreen, i = 0, l = a.length; i < l; i++) { source = nodes(a[i].source); target = nodes(a[i].target); (renderers[a[i].type] || renderers.def).update( a[i], this.domElements.edges[a[i].id], source, target, embedSettings ); } this.dispatchEvent('render'); return this; }; /** * This method creates a DOM element of the specified type, switches its * position to "absolute", references it to the domElements attribute, and * finally appends it to the container. * * @param {string} tag The label tag. * @param {string} id The id of the element (to store it in "domElements"). */ sigma.renderers.svg.prototype.initDOM = function(tag) { var dom = document.createElementNS(this.settings('xmlns'), tag), c = this.settings('classPrefix'), g, l, i; dom.style.position = 'absolute'; dom.setAttribute('class', c + '-svg'); // Setting SVG namespace dom.setAttribute('xmlns', this.settings('xmlns')); dom.setAttribute('xmlns:xlink', 'http://www.w3.org/1999/xlink'); dom.setAttribute('version', '1.1'); // Creating the measurement canvas var canvas = document.createElement('canvas'); canvas.setAttribute('class', c + '-measurement-canvas'); // Appending elements this.domElements.graph = this.container.appendChild(dom); // Creating groups var groups = ['edges', 'nodes', 'labels', 'hovers']; for (i = 0, l = groups.length; i < l; i++) { g = document.createElementNS(this.settings('xmlns'), 'g'); g.setAttributeNS(null, 'id', c + '-group-' + groups[i]); g.setAttributeNS(null, 'class', c + '-group'); this.domElements.groups[groups[i]] = this.domElements.graph.appendChild(g); } // Appending measurement canvas this.container.appendChild(canvas); this.measurementCanvas = canvas.getContext('2d'); }; /** * This method hides a batch of SVG DOM elements. * * @param {array} elements An array of elements to hide. * @param {object} renderer The renderer to use. * @return {sigma.renderers.svg} Returns the instance itself. */ sigma.renderers.svg.prototype.hideDOMElements = function(elements) { var o, i; for (i in elements) { o = elements[i]; sigma.svg.utils.hide(o); } return this; }; /** * This method binds the hover events to the renderer. * * @param {string} prefix The renderer prefix. */ // TODO: add option about whether to display hovers or not sigma.renderers.svg.prototype.bindHovers = function(prefix) { var renderers = sigma.svg.hovers, self = this, hoveredNode; function overNode(e) { var node = e.data.node, embedSettings = self.settings.embedObjects({ prefix: prefix }); if (!embedSettings('enableHovering')) return; var hover = (renderers[node.type] || renderers.def).create( node, self.domElements.nodes[node.id], self.measurementCanvas, embedSettings ); self.domElements.hovers[node.id] = hover; // Inserting the hover in the dom self.domElements.groups.hovers.appendChild(hover); hoveredNode = node; } function outNode(e) { var node = e.data.node, embedSettings = self.settings.embedObjects({ prefix: prefix }); if (!embedSettings('enableHovering')) return; // Deleting element self.domElements.groups.hovers.removeChild( self.domElements.hovers[node.id] ); hoveredNode = null; delete self.domElements.hovers[node.id]; // Reinstate self.domElements.groups.nodes.appendChild( self.domElements.nodes[node.id] ); } // OPTIMIZE: perform a real update rather than a deletion function update() { if (!hoveredNode) return; var embedSettings = self.settings.embedObjects({ prefix: prefix }); // Deleting element before update self.domElements.groups.hovers.removeChild( self.domElements.hovers[hoveredNode.id] ); delete self.domElements.hovers[hoveredNode.id]; var hover = (renderers[hoveredNode.type] || renderers.def).create( hoveredNode, self.domElements.nodes[hoveredNode.id], self.measurementCanvas, embedSettings ); self.domElements.hovers[hoveredNode.id] = hover; // Inserting the hover in the dom self.domElements.groups.hovers.appendChild(hover); } // Binding events this.bind('overNode', overNode); this.bind('outNode', outNode); // Update on render this.bind('render', update); }; /** * This method resizes each DOM elements in the container and stores the new * dimensions. Then, it renders the graph. * * @param {?number} width The new width of the container. * @param {?number} height The new height of the container. * @return {sigma.renderers.svg} Returns the instance itself. */ sigma.renderers.svg.prototype.resize = function(w, h) { var oldWidth = this.width, oldHeight = this.height, pixelRatio = 1; if (w !== undefined && h !== undefined) { this.width = w; this.height = h; } else { this.width = this.container.offsetWidth; this.height = this.container.offsetHeight; w = this.width; h = this.height; } if (oldWidth !== this.width || oldHeight !== this.height) { this.domElements.graph.style.width = w + 'px'; this.domElements.graph.style.height = h + 'px'; if (this.domElements.graph.tagName.toLowerCase() === 'svg') { this.domElements.graph.setAttribute('width', (w * pixelRatio)); this.domElements.graph.setAttribute('height', (h * pixelRatio)); } } return this; }; /** * The labels, nodes and edges renderers are stored in the three following * objects. When an element is drawn, its type will be checked and if a * renderer with the same name exists, it will be used. If not found, the * default renderer will be used instead. * * They are stored in different files, in the "./svg" folder. */ sigma.utils.pkg('sigma.svg.nodes'); sigma.utils.pkg('sigma.svg.edges'); sigma.utils.pkg('sigma.svg.labels'); }).call(this); ;(function(global) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.renderers'); // Check if WebGL is enabled: var canvas, webgl = !!global.WebGLRenderingContext; if (webgl) { canvas = document.createElement('canvas'); try { webgl = !!( canvas.getContext('webgl') || canvas.getContext('experimental-webgl') ); } catch (e) { webgl = false; } } // Copy the good renderer: sigma.renderers.def = webgl ? sigma.renderers.webgl : sigma.renderers.canvas; })(this); ;(function() { 'use strict'; sigma.utils.pkg('sigma.webgl.nodes'); /** * This node renderer will display nodes as discs, shaped in triangles with * the gl.TRIANGLES display mode. So, to be more precise, to draw one node, * it will store three times the center of node, with the color and the size, * and an angle indicating which "corner" of the triangle to draw. * * The fragment shader does not deal with anti-aliasing, so make sure that * you deal with it somewhere else in the code (by default, the WebGL * renderer will oversample the rendering through the webglOversamplingRatio * value). */ sigma.webgl.nodes.def = { POINTS: 3, ATTRIBUTES: 5, addNode: function(node, data, i, prefix, settings) { var color = sigma.utils.floatColor( node.color || settings('defaultNodeColor') ); data[i++] = node[prefix + 'x']; data[i++] = node[prefix + 'y']; data[i++] = node[prefix + 'size']; data[i++] = color; data[i++] = 0; data[i++] = node[prefix + 'x']; data[i++] = node[prefix + 'y']; data[i++] = node[prefix + 'size']; data[i++] = color; data[i++] = 2 * Math.PI / 3; data[i++] = node[prefix + 'x']; data[i++] = node[prefix + 'y']; data[i++] = node[prefix + 'size']; data[i++] = color; data[i++] = 4 * Math.PI / 3; }, render: function(gl, program, data, params) { var buffer; // Define attributes: var positionLocation = gl.getAttribLocation(program, 'a_position'), sizeLocation = gl.getAttribLocation(program, 'a_size'), colorLocation = gl.getAttribLocation(program, 'a_color'), angleLocation = gl.getAttribLocation(program, 'a_angle'), resolutionLocation = gl.getUniformLocation(program, 'u_resolution'), matrixLocation = gl.getUniformLocation(program, 'u_matrix'), ratioLocation = gl.getUniformLocation(program, 'u_ratio'), scaleLocation = gl.getUniformLocation(program, 'u_scale'); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW); gl.uniform2f(resolutionLocation, params.width, params.height); gl.uniform1f( ratioLocation, 1 / Math.pow(params.ratio, params.settings('nodesPowRatio')) ); gl.uniform1f(scaleLocation, params.scalingRatio); gl.uniformMatrix3fv(matrixLocation, false, params.matrix); gl.enableVertexAttribArray(positionLocation); gl.enableVertexAttribArray(sizeLocation); gl.enableVertexAttribArray(colorLocation); gl.enableVertexAttribArray(angleLocation); gl.vertexAttribPointer( positionLocation, 2, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 0 ); gl.vertexAttribPointer( sizeLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 8 ); gl.vertexAttribPointer( colorLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 12 ); gl.vertexAttribPointer( angleLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 16 ); gl.drawArrays( gl.TRIANGLES, params.start || 0, params.count || (data.length / this.ATTRIBUTES) ); }, initProgram: function(gl) { var vertexShader, fragmentShader, program; vertexShader = sigma.utils.loadShader( gl, [ 'attribute vec2 a_position;', 'attribute float a_size;', 'attribute float a_color;', 'attribute float a_angle;', 'uniform vec2 u_resolution;', 'uniform float u_ratio;', 'uniform float u_scale;', 'uniform mat3 u_matrix;', 'varying vec4 color;', 'varying vec2 center;', 'varying float radius;', 'void main() {', // Multiply the point size twice: 'radius = a_size * u_ratio;', // Scale from [[-1 1] [-1 1]] to the container: 'vec2 position = (u_matrix * vec3(a_position, 1)).xy;', // 'center = (position / u_resolution * 2.0 - 1.0) * vec2(1, -1);', 'center = position * u_scale;', 'center = vec2(center.x, u_scale * u_resolution.y - center.y);', 'position = position +', '2.0 * radius * vec2(cos(a_angle), sin(a_angle));', 'position = (position / u_resolution * 2.0 - 1.0) * vec2(1, -1);', 'radius = radius * u_scale;', 'gl_Position = vec4(position, 0, 1);', // Extract the color: 'float c = a_color;', 'color.b = mod(c, 256.0); c = floor(c / 256.0);', 'color.g = mod(c, 256.0); c = floor(c / 256.0);', 'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;', 'color.a = 1.0;', '}' ].join('\n'), gl.VERTEX_SHADER ); fragmentShader = sigma.utils.loadShader( gl, [ 'precision mediump float;', 'varying vec4 color;', 'varying vec2 center;', 'varying float radius;', 'void main(void) {', 'vec4 color0 = vec4(0.0, 0.0, 0.0, 0.0);', 'vec2 m = gl_FragCoord.xy - center;', 'float diff = radius - sqrt(m.x * m.x + m.y * m.y);', // Here is how we draw a disc instead of a square: 'if (diff > 0.0)', 'gl_FragColor = color;', 'else', 'gl_FragColor = color0;', '}' ].join('\n'), gl.FRAGMENT_SHADER ); program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]); return program; } }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.webgl.nodes'); /** * This node renderer will display nodes in the fastest way: Nodes are basic * squares, drawn through the gl.POINTS drawing method. The size of the nodes * are represented with the "gl_PointSize" value in the vertex shader. * * It is the fastest node renderer here since the buffer just takes one line * to draw each node (with attributes "x", "y", "size" and "color"). * * Nevertheless, this method has some problems, especially due to some issues * with the gl.POINTS: * - First, if the center of a node is outside the scene, the point will not * be drawn, even if it should be partly on screen. * - I tried applying a fragment shader similar to the one in the default * node renderer to display them as discs, but it did not work fine on * some computers settings, filling the discs with weird gradients not * depending on the actual color. */ sigma.webgl.nodes.fast = { POINTS: 1, ATTRIBUTES: 4, addNode: function(node, data, i, prefix, settings) { data[i++] = node[prefix + 'x']; data[i++] = node[prefix + 'y']; data[i++] = node[prefix + 'size']; data[i++] = sigma.utils.floatColor( node.color || settings('defaultNodeColor') ); }, render: function(gl, program, data, params) { var buffer; // Define attributes: var positionLocation = gl.getAttribLocation(program, 'a_position'), sizeLocation = gl.getAttribLocation(program, 'a_size'), colorLocation = gl.getAttribLocation(program, 'a_color'), resolutionLocation = gl.getUniformLocation(program, 'u_resolution'), matrixLocation = gl.getUniformLocation(program, 'u_matrix'), ratioLocation = gl.getUniformLocation(program, 'u_ratio'), scaleLocation = gl.getUniformLocation(program, 'u_scale'); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW); gl.uniform2f(resolutionLocation, params.width, params.height); gl.uniform1f( ratioLocation, 1 / Math.pow(params.ratio, params.settings('nodesPowRatio')) ); gl.uniform1f(scaleLocation, params.scalingRatio); gl.uniformMatrix3fv(matrixLocation, false, params.matrix); gl.enableVertexAttribArray(positionLocation); gl.enableVertexAttribArray(sizeLocation); gl.enableVertexAttribArray(colorLocation); gl.vertexAttribPointer( positionLocation, 2, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 0 ); gl.vertexAttribPointer( sizeLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 8 ); gl.vertexAttribPointer( colorLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 12 ); gl.drawArrays( gl.POINTS, params.start || 0, params.count || (data.length / this.ATTRIBUTES) ); }, initProgram: function(gl) { var vertexShader, fragmentShader, program; vertexShader = sigma.utils.loadShader( gl, [ 'attribute vec2 a_position;', 'attribute float a_size;', 'attribute float a_color;', 'uniform vec2 u_resolution;', 'uniform float u_ratio;', 'uniform float u_scale;', 'uniform mat3 u_matrix;', 'varying vec4 color;', 'void main() {', // Scale from [[-1 1] [-1 1]] to the container: 'gl_Position = vec4(', '((u_matrix * vec3(a_position, 1)).xy /', 'u_resolution * 2.0 - 1.0) * vec2(1, -1),', '0,', '1', ');', // Multiply the point size twice: // - x SCALING_RATIO to correct the canvas scaling // - x 2 to correct the formulae 'gl_PointSize = a_size * u_ratio * u_scale * 2.0;', // Extract the color: 'float c = a_color;', 'color.b = mod(c, 256.0); c = floor(c / 256.0);', 'color.g = mod(c, 256.0); c = floor(c / 256.0);', 'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;', 'color.a = 1.0;', '}' ].join('\n'), gl.VERTEX_SHADER ); fragmentShader = sigma.utils.loadShader( gl, [ 'precision mediump float;', 'varying vec4 color;', 'void main(void) {', 'gl_FragColor = color;', '}' ].join('\n'), gl.FRAGMENT_SHADER ); program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]); return program; } }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.webgl.edges'); /** * This edge renderer will display edges as lines going from the source node * to the target node. To deal with edge thicknesses, the lines are made of * two triangles forming rectangles, with the gl.TRIANGLES drawing mode. * * It is expensive, since drawing a single edge requires 6 points, each * having 7 attributes (source position, target position, thickness, color * and a flag indicating which vertice of the rectangle it is). */ sigma.webgl.edges.def = { POINTS: 6, ATTRIBUTES: 7, addEdge: function(edge, source, target, data, i, prefix, settings) { var w = (edge[prefix + 'size'] || 1) / 2, x1 = source[prefix + 'x'], y1 = source[prefix + 'y'], x2 = target[prefix + 'x'], y2 = target[prefix + 'y'], color = edge.color; if (!color) switch (settings('edgeColor')) { case 'source': color = source.color || settings('defaultNodeColor'); break; case 'target': color = target.color || settings('defaultNodeColor'); break; default: color = settings('defaultEdgeColor'); break; } // Normalize color: color = sigma.utils.floatColor(color); data[i++] = x1; data[i++] = y1; data[i++] = x2; data[i++] = y2; data[i++] = w; data[i++] = 0.0; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = 1.0; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = 0.0; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = 0.0; data[i++] = color; data[i++] = x1; data[i++] = y1; data[i++] = x2; data[i++] = y2; data[i++] = w; data[i++] = 1.0; data[i++] = color; data[i++] = x1; data[i++] = y1; data[i++] = x2; data[i++] = y2; data[i++] = w; data[i++] = 0.0; data[i++] = color; }, render: function(gl, program, data, params) { var buffer; // Define attributes: var colorLocation = gl.getAttribLocation(program, 'a_color'), positionLocation1 = gl.getAttribLocation(program, 'a_position1'), positionLocation2 = gl.getAttribLocation(program, 'a_position2'), thicknessLocation = gl.getAttribLocation(program, 'a_thickness'), minusLocation = gl.getAttribLocation(program, 'a_minus'), resolutionLocation = gl.getUniformLocation(program, 'u_resolution'), matrixLocation = gl.getUniformLocation(program, 'u_matrix'), matrixHalfPiLocation = gl.getUniformLocation(program, 'u_matrixHalfPi'), matrixHalfPiMinusLocation = gl.getUniformLocation(program, 'u_matrixHalfPiMinus'), ratioLocation = gl.getUniformLocation(program, 'u_ratio'), scaleLocation = gl.getUniformLocation(program, 'u_scale'); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); gl.uniform2f(resolutionLocation, params.width, params.height); gl.uniform1f( ratioLocation, params.ratio / Math.pow(params.ratio, params.settings('edgesPowRatio')) ); gl.uniform1f(scaleLocation, params.scalingRatio); gl.uniformMatrix3fv(matrixLocation, false, params.matrix); gl.uniformMatrix2fv( matrixHalfPiLocation, false, sigma.utils.matrices.rotation(Math.PI / 2, true) ); gl.uniformMatrix2fv( matrixHalfPiMinusLocation, false, sigma.utils.matrices.rotation(-Math.PI / 2, true) ); gl.enableVertexAttribArray(colorLocation); gl.enableVertexAttribArray(positionLocation1); gl.enableVertexAttribArray(positionLocation2); gl.enableVertexAttribArray(thicknessLocation); gl.enableVertexAttribArray(minusLocation); gl.vertexAttribPointer(positionLocation1, 2, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 0 ); gl.vertexAttribPointer(positionLocation2, 2, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 8 ); gl.vertexAttribPointer(thicknessLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 16 ); gl.vertexAttribPointer(minusLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 20 ); gl.vertexAttribPointer(colorLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 24 ); gl.drawArrays( gl.TRIANGLES, params.start || 0, params.count || (data.length / this.ATTRIBUTES) ); }, initProgram: function(gl) { var vertexShader, fragmentShader, program; vertexShader = sigma.utils.loadShader( gl, [ 'attribute vec2 a_position1;', 'attribute vec2 a_position2;', 'attribute float a_thickness;', 'attribute float a_minus;', 'attribute float a_color;', 'uniform vec2 u_resolution;', 'uniform float u_ratio;', 'uniform float u_scale;', 'uniform mat3 u_matrix;', 'uniform mat2 u_matrixHalfPi;', 'uniform mat2 u_matrixHalfPiMinus;', 'varying vec4 color;', 'void main() {', // Find the good point: 'vec2 position = a_thickness * u_ratio *', 'normalize(a_position2 - a_position1);', 'mat2 matrix = a_minus * u_matrixHalfPiMinus +', '(1.0 - a_minus) * u_matrixHalfPi;', 'position = matrix * position + a_position1;', // Scale from [[-1 1] [-1 1]] to the container: 'gl_Position = vec4(', '((u_matrix * vec3(position, 1)).xy /', 'u_resolution * 2.0 - 1.0) * vec2(1, -1),', '0,', '1', ');', // Extract the color: 'float c = a_color;', 'color.b = mod(c, 256.0); c = floor(c / 256.0);', 'color.g = mod(c, 256.0); c = floor(c / 256.0);', 'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;', 'color.a = 1.0;', '}' ].join('\n'), gl.VERTEX_SHADER ); fragmentShader = sigma.utils.loadShader( gl, [ 'precision mediump float;', 'varying vec4 color;', 'void main(void) {', 'gl_FragColor = color;', '}' ].join('\n'), gl.FRAGMENT_SHADER ); program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]); return program; } }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.webgl.edges'); /** * This edge renderer will display edges as lines with the gl.LINES display * mode. Since this mode does not support well thickness, edges are all drawn * with the same thickness (3px), independantly of the edge attributes or the * zooming ratio. */ sigma.webgl.edges.fast = { POINTS: 2, ATTRIBUTES: 3, addEdge: function(edge, source, target, data, i, prefix, settings) { var w = (edge[prefix + 'size'] || 1) / 2, x1 = source[prefix + 'x'], y1 = source[prefix + 'y'], x2 = target[prefix + 'x'], y2 = target[prefix + 'y'], color = edge.color; if (!color) switch (settings('edgeColor')) { case 'source': color = source.color || settings('defaultNodeColor'); break; case 'target': color = target.color || settings('defaultNodeColor'); break; default: color = settings('defaultEdgeColor'); break; } // Normalize color: color = sigma.utils.floatColor(color); data[i++] = x1; data[i++] = y1; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = color; }, render: function(gl, program, data, params) { var buffer; // Define attributes: var colorLocation = gl.getAttribLocation(program, 'a_color'), positionLocation = gl.getAttribLocation(program, 'a_position'), resolutionLocation = gl.getUniformLocation(program, 'u_resolution'), matrixLocation = gl.getUniformLocation(program, 'u_matrix'); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.DYNAMIC_DRAW); gl.uniform2f(resolutionLocation, params.width, params.height); gl.uniformMatrix3fv(matrixLocation, false, params.matrix); gl.enableVertexAttribArray(positionLocation); gl.enableVertexAttribArray(colorLocation); gl.vertexAttribPointer(positionLocation, 2, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 0 ); gl.vertexAttribPointer(colorLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 8 ); gl.lineWidth(3); gl.drawArrays( gl.LINES, params.start || 0, params.count || (data.length / this.ATTRIBUTES) ); }, initProgram: function(gl) { var vertexShader, fragmentShader, program; vertexShader = sigma.utils.loadShader( gl, [ 'attribute vec2 a_position;', 'attribute float a_color;', 'uniform vec2 u_resolution;', 'uniform mat3 u_matrix;', 'varying vec4 color;', 'void main() {', // Scale from [[-1 1] [-1 1]] to the container: 'gl_Position = vec4(', '((u_matrix * vec3(a_position, 1)).xy /', 'u_resolution * 2.0 - 1.0) * vec2(1, -1),', '0,', '1', ');', // Extract the color: 'float c = a_color;', 'color.b = mod(c, 256.0); c = floor(c / 256.0);', 'color.g = mod(c, 256.0); c = floor(c / 256.0);', 'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;', 'color.a = 1.0;', '}' ].join('\n'), gl.VERTEX_SHADER ); fragmentShader = sigma.utils.loadShader( gl, [ 'precision mediump float;', 'varying vec4 color;', 'void main(void) {', 'gl_FragColor = color;', '}' ].join('\n'), gl.FRAGMENT_SHADER ); program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]); return program; } }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.webgl.edges'); /** * This edge renderer will display edges as arrows going from the source node * to the target node. To deal with edge thicknesses, the lines are made of * three triangles: two forming rectangles, with the gl.TRIANGLES drawing * mode. * * It is expensive, since drawing a single edge requires 9 points, each * having a lot of attributes. */ sigma.webgl.edges.arrow = { POINTS: 9, ATTRIBUTES: 11, addEdge: function(edge, source, target, data, i, prefix, settings) { var w = (edge[prefix + 'size'] || 1) / 2, x1 = source[prefix + 'x'], y1 = source[prefix + 'y'], x2 = target[prefix + 'x'], y2 = target[prefix + 'y'], targetSize = target[prefix + 'size'], color = edge.color; if (!color) switch (settings('edgeColor')) { case 'source': color = source.color || settings('defaultNodeColor'); break; case 'target': color = target.color || settings('defaultNodeColor'); break; default: color = settings('defaultEdgeColor'); break; } // Normalize color: color = sigma.utils.floatColor(color); data[i++] = x1; data[i++] = y1; data[i++] = x2; data[i++] = y2; data[i++] = w; data[i++] = targetSize; data[i++] = 0.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = targetSize; data[i++] = 1.0; data[i++] = 1.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = targetSize; data[i++] = 1.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = targetSize; data[i++] = 1.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = color; data[i++] = x1; data[i++] = y1; data[i++] = x2; data[i++] = y2; data[i++] = w; data[i++] = targetSize; data[i++] = 0.0; data[i++] = 1.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = color; data[i++] = x1; data[i++] = y1; data[i++] = x2; data[i++] = y2; data[i++] = w; data[i++] = targetSize; data[i++] = 0.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = 0.0; data[i++] = color; // Arrow head: data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = targetSize; data[i++] = 1.0; data[i++] = 0.0; data[i++] = 1.0; data[i++] = -1.0; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = targetSize; data[i++] = 1.0; data[i++] = 0.0; data[i++] = 1.0; data[i++] = 0.0; data[i++] = color; data[i++] = x2; data[i++] = y2; data[i++] = x1; data[i++] = y1; data[i++] = w; data[i++] = targetSize; data[i++] = 1.0; data[i++] = 0.0; data[i++] = 1.0; data[i++] = 1.0; data[i++] = color; }, render: function(gl, program, data, params) { var buffer; // Define attributes: var positionLocation1 = gl.getAttribLocation(program, 'a_pos1'), positionLocation2 = gl.getAttribLocation(program, 'a_pos2'), thicknessLocation = gl.getAttribLocation(program, 'a_thickness'), targetSizeLocation = gl.getAttribLocation(program, 'a_tSize'), delayLocation = gl.getAttribLocation(program, 'a_delay'), minusLocation = gl.getAttribLocation(program, 'a_minus'), headLocation = gl.getAttribLocation(program, 'a_head'), headPositionLocation = gl.getAttribLocation(program, 'a_headPosition'), colorLocation = gl.getAttribLocation(program, 'a_color'), resolutionLocation = gl.getUniformLocation(program, 'u_resolution'), matrixLocation = gl.getUniformLocation(program, 'u_matrix'), matrixHalfPiLocation = gl.getUniformLocation(program, 'u_matrixHalfPi'), matrixHalfPiMinusLocation = gl.getUniformLocation(program, 'u_matrixHalfPiMinus'), ratioLocation = gl.getUniformLocation(program, 'u_ratio'), nodeRatioLocation = gl.getUniformLocation(program, 'u_nodeRatio'), arrowHeadLocation = gl.getUniformLocation(program, 'u_arrowHead'), scaleLocation = gl.getUniformLocation(program, 'u_scale'); buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, data, gl.STATIC_DRAW); gl.uniform2f(resolutionLocation, params.width, params.height); gl.uniform1f( ratioLocation, params.ratio / Math.pow(params.ratio, params.settings('edgesPowRatio')) ); gl.uniform1f( nodeRatioLocation, Math.pow(params.ratio, params.settings('nodesPowRatio')) / params.ratio ); gl.uniform1f(arrowHeadLocation, 5.0); gl.uniform1f(scaleLocation, params.scalingRatio); gl.uniformMatrix3fv(matrixLocation, false, params.matrix); gl.uniformMatrix2fv( matrixHalfPiLocation, false, sigma.utils.matrices.rotation(Math.PI / 2, true) ); gl.uniformMatrix2fv( matrixHalfPiMinusLocation, false, sigma.utils.matrices.rotation(-Math.PI / 2, true) ); gl.enableVertexAttribArray(positionLocation1); gl.enableVertexAttribArray(positionLocation2); gl.enableVertexAttribArray(thicknessLocation); gl.enableVertexAttribArray(targetSizeLocation); gl.enableVertexAttribArray(delayLocation); gl.enableVertexAttribArray(minusLocation); gl.enableVertexAttribArray(headLocation); gl.enableVertexAttribArray(headPositionLocation); gl.enableVertexAttribArray(colorLocation); gl.vertexAttribPointer(positionLocation1, 2, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 0 ); gl.vertexAttribPointer(positionLocation2, 2, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 8 ); gl.vertexAttribPointer(thicknessLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 16 ); gl.vertexAttribPointer(targetSizeLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 20 ); gl.vertexAttribPointer(delayLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 24 ); gl.vertexAttribPointer(minusLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 28 ); gl.vertexAttribPointer(headLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 32 ); gl.vertexAttribPointer(headPositionLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 36 ); gl.vertexAttribPointer(colorLocation, 1, gl.FLOAT, false, this.ATTRIBUTES * Float32Array.BYTES_PER_ELEMENT, 40 ); gl.drawArrays( gl.TRIANGLES, params.start || 0, params.count || (data.length / this.ATTRIBUTES) ); }, initProgram: function(gl) { var vertexShader, fragmentShader, program; vertexShader = sigma.utils.loadShader( gl, [ 'attribute vec2 a_pos1;', 'attribute vec2 a_pos2;', 'attribute float a_thickness;', 'attribute float a_tSize;', 'attribute float a_delay;', 'attribute float a_minus;', 'attribute float a_head;', 'attribute float a_headPosition;', 'attribute float a_color;', 'uniform vec2 u_resolution;', 'uniform float u_ratio;', 'uniform float u_nodeRatio;', 'uniform float u_arrowHead;', 'uniform float u_scale;', 'uniform mat3 u_matrix;', 'uniform mat2 u_matrixHalfPi;', 'uniform mat2 u_matrixHalfPiMinus;', 'varying vec4 color;', 'void main() {', // Find the good point: 'vec2 pos = normalize(a_pos2 - a_pos1);', 'mat2 matrix = (1.0 - a_head) *', '(', 'a_minus * u_matrixHalfPiMinus +', '(1.0 - a_minus) * u_matrixHalfPi', ') + a_head * (', 'a_headPosition * u_matrixHalfPiMinus * 0.6 +', '(a_headPosition * a_headPosition - 1.0) * mat2(1.0)', ');', 'pos = a_pos1 + (', // Deal with body: '(1.0 - a_head) * a_thickness * u_ratio * matrix * pos +', // Deal with head: 'a_head * u_arrowHead * a_thickness * u_ratio * matrix * pos +', // Deal with delay: 'a_delay * pos * (', 'a_tSize / u_nodeRatio +', 'u_arrowHead * a_thickness * u_ratio', ')', ');', // Scale from [[-1 1] [-1 1]] to the container: 'gl_Position = vec4(', '((u_matrix * vec3(pos, 1)).xy /', 'u_resolution * 2.0 - 1.0) * vec2(1, -1),', '0,', '1', ');', // Extract the color: 'float c = a_color;', 'color.b = mod(c, 256.0); c = floor(c / 256.0);', 'color.g = mod(c, 256.0); c = floor(c / 256.0);', 'color.r = mod(c, 256.0); c = floor(c / 256.0); color /= 255.0;', 'color.a = 1.0;', '}' ].join('\n'), gl.VERTEX_SHADER ); fragmentShader = sigma.utils.loadShader( gl, [ 'precision mediump float;', 'varying vec4 color;', 'void main(void) {', 'gl_FragColor = color;', '}' ].join('\n'), gl.FRAGMENT_SHADER ); program = sigma.utils.loadProgram(gl, [vertexShader, fragmentShader]); return program; } }; })(); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.canvas.labels'); /** * This label renderer will just display the label on the right of the node. * * @param {object} node The node object. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.labels.def = function(node, context, settings) { var fontSize, prefix = settings('prefix') || '', size = node[prefix + 'size']; if (size < settings('labelThreshold')) return; if (!node.label || typeof node.label !== 'string') return; fontSize = (settings('labelSize') === 'fixed') ? settings('defaultLabelSize') : settings('labelSizeRatio') * size; context.font = (settings('fontStyle') ? settings('fontStyle') + ' ' : '') + fontSize + 'px ' + settings('font'); context.fillStyle = (settings('labelColor') === 'node') ? (node.color || settings('defaultNodeColor')) : settings('defaultLabelColor'); context.fillText( node.label, Math.round(node[prefix + 'x'] + size + 3), Math.round(node[prefix + 'y'] + fontSize / 3) ); }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.canvas.hovers'); /** * This hover renderer will basically display the label with a background. * * @param {object} node The node object. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.hovers.def = function(node, context, settings) { var x, y, w, h, e, fontStyle = settings('hoverFontStyle') || settings('fontStyle'), prefix = settings('prefix') || '', size = node[prefix + 'size'], fontSize = (settings('labelSize') === 'fixed') ? settings('defaultLabelSize') : settings('labelSizeRatio') * size; // Label background: context.font = (fontStyle ? fontStyle + ' ' : '') + fontSize + 'px ' + (settings('hoverFont') || settings('font')); context.beginPath(); context.fillStyle = settings('labelHoverBGColor') === 'node' ? (node.color || settings('defaultNodeColor')) : settings('defaultHoverLabelBGColor'); if (node.label && settings('labelHoverShadow')) { context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.shadowBlur = 8; context.shadowColor = settings('labelHoverShadowColor'); } if (node.label && typeof node.label === 'string') { x = Math.round(node[prefix + 'x'] - fontSize / 2 - 2); y = Math.round(node[prefix + 'y'] - fontSize / 2 - 2); w = Math.round( context.measureText(node.label).width + fontSize / 2 + size + 7 ); h = Math.round(fontSize + 4); e = Math.round(fontSize / 2 + 2); context.moveTo(x, y + e); context.arcTo(x, y, x + e, y, e); context.lineTo(x + w, y); context.lineTo(x + w, y + h); context.lineTo(x + e, y + h); context.arcTo(x, y + h, x, y + h - e, e); context.lineTo(x, y + e); context.closePath(); context.fill(); context.shadowOffsetX = 0; context.shadowOffsetY = 0; context.shadowBlur = 0; } // Node border: if (settings('borderSize') > 0) { context.beginPath(); context.fillStyle = settings('nodeBorderColor') === 'node' ? (node.color || settings('defaultNodeColor')) : settings('defaultNodeBorderColor'); context.arc( node[prefix + 'x'], node[prefix + 'y'], size + settings('borderSize'), 0, Math.PI * 2, true ); context.closePath(); context.fill(); } // Node: var nodeRenderer = sigma.canvas.nodes[node.type] || sigma.canvas.nodes.def; nodeRenderer(node, context, settings); // Display the label: if (node.label && typeof node.label === 'string') { context.fillStyle = (settings('labelHoverColor') === 'node') ? (node.color || settings('defaultNodeColor')) : settings('defaultLabelHoverColor'); context.fillText( node.label, Math.round(node[prefix + 'x'] + size + 3), Math.round(node[prefix + 'y'] + fontSize / 3) ); } }; }).call(this); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.nodes'); /** * The default node renderer. It renders the node as a simple disc. * * @param {object} node The node object. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.nodes.def = function(node, context, settings) { var prefix = settings('prefix') || ''; context.fillStyle = node.color || settings('defaultNodeColor'); context.beginPath(); context.arc( node[prefix + 'x'], node[prefix + 'y'], node[prefix + 'size'], 0, Math.PI * 2, true ); context.closePath(); context.fill(); }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edges'); /** * The default edge renderer. It renders the edge as a simple line. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edges.def = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', size = edge[prefix + 'size'] || 1, edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'); if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo( source[prefix + 'x'], source[prefix + 'y'] ); context.lineTo( target[prefix + 'x'], target[prefix + 'y'] ); context.stroke(); }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edges'); /** * This edge renderer will display edges as curves. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edges.curve = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', size = edge[prefix + 'size'] || 1, edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'), cp = {}, sSize = source[prefix + 'size'], sX = source[prefix + 'x'], sY = source[prefix + 'y'], tX = target[prefix + 'x'], tY = target[prefix + 'y']; cp = (source.id === target.id) ? sigma.utils.getSelfLoopControlPoints(sX, sY, sSize) : sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY); if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo(sX, sY); if (source.id === target.id) { context.bezierCurveTo(cp.x1, cp.y1, cp.x2, cp.y2, tX, tY); } else { context.quadraticCurveTo(cp.x, cp.y, tX, tY); } context.stroke(); }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edges'); /** * This edge renderer will display edges as arrows going from the source node * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edges.arrow = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'), size = edge[prefix + 'size'] || 1, tSize = target[prefix + 'size'], sX = source[prefix + 'x'], sY = source[prefix + 'y'], tX = target[prefix + 'x'], tY = target[prefix + 'y'], aSize = Math.max(size * 2.5, settings('minArrowSize')), d = Math.sqrt(Math.pow(tX - sX, 2) + Math.pow(tY - sY, 2)), aX = sX + (tX - sX) * (d - aSize - tSize) / d, aY = sY + (tY - sY) * (d - aSize - tSize) / d, vX = (tX - sX) * aSize / d, vY = (tY - sY) * aSize / d; if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo(sX, sY); context.lineTo( aX, aY ); context.stroke(); context.fillStyle = color; context.beginPath(); context.moveTo(aX + vX, aY + vY); context.lineTo(aX + vY * 0.6, aY - vX * 0.6); context.lineTo(aX - vY * 0.6, aY + vX * 0.6); context.lineTo(aX + vX, aY + vY); context.closePath(); context.fill(); }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edges'); /** * This edge renderer will display edges as curves with arrow heading. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edges.curvedArrow = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'), cp = {}, size = edge[prefix + 'size'] || 1, tSize = target[prefix + 'size'], sX = source[prefix + 'x'], sY = source[prefix + 'y'], tX = target[prefix + 'x'], tY = target[prefix + 'y'], aSize = Math.max(size * 2.5, settings('minArrowSize')), d, aX, aY, vX, vY; cp = (source.id === target.id) ? sigma.utils.getSelfLoopControlPoints(sX, sY, tSize) : sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY); if (source.id === target.id) { d = Math.sqrt(Math.pow(tX - cp.x1, 2) + Math.pow(tY - cp.y1, 2)); aX = cp.x1 + (tX - cp.x1) * (d - aSize - tSize) / d; aY = cp.y1 + (tY - cp.y1) * (d - aSize - tSize) / d; vX = (tX - cp.x1) * aSize / d; vY = (tY - cp.y1) * aSize / d; } else { d = Math.sqrt(Math.pow(tX - cp.x, 2) + Math.pow(tY - cp.y, 2)); aX = cp.x + (tX - cp.x) * (d - aSize - tSize) / d; aY = cp.y + (tY - cp.y) * (d - aSize - tSize) / d; vX = (tX - cp.x) * aSize / d; vY = (tY - cp.y) * aSize / d; } if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo(sX, sY); if (source.id === target.id) { context.bezierCurveTo(cp.x2, cp.y2, cp.x1, cp.y1, aX, aY); } else { context.quadraticCurveTo(cp.x, cp.y, aX, aY); } context.stroke(); context.fillStyle = color; context.beginPath(); context.moveTo(aX + vX, aY + vY); context.lineTo(aX + vY * 0.6, aY - vX * 0.6); context.lineTo(aX - vY * 0.6, aY + vX * 0.6); context.lineTo(aX + vX, aY + vY); context.closePath(); context.fill(); }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edgehovers'); /** * This hover renderer will display the edge with a different color or size. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edgehovers.def = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', size = edge[prefix + 'size'] || 1, edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'); if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } if (settings('edgeHoverColor') === 'edge') { color = edge.hover_color || color; } else { color = edge.hover_color || settings('defaultEdgeHoverColor') || color; } size *= settings('edgeHoverSizeRatio'); context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo( source[prefix + 'x'], source[prefix + 'y'] ); context.lineTo( target[prefix + 'x'], target[prefix + 'y'] ); context.stroke(); }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edgehovers'); /** * This hover renderer will display the edge with a different color or size. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edgehovers.curve = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', size = settings('edgeHoverSizeRatio') * (edge[prefix + 'size'] || 1), edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'), cp = {}, sSize = source[prefix + 'size'], sX = source[prefix + 'x'], sY = source[prefix + 'y'], tX = target[prefix + 'x'], tY = target[prefix + 'y']; cp = (source.id === target.id) ? sigma.utils.getSelfLoopControlPoints(sX, sY, sSize) : sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY); if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } if (settings('edgeHoverColor') === 'edge') { color = edge.hover_color || color; } else { color = edge.hover_color || settings('defaultEdgeHoverColor') || color; } context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo(sX, sY); if (source.id === target.id) { context.bezierCurveTo(cp.x1, cp.y1, cp.x2, cp.y2, tX, tY); } else { context.quadraticCurveTo(cp.x, cp.y, tX, tY); } context.stroke(); }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edgehovers'); /** * This hover renderer will display the edge with a different color or size. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edgehovers.arrow = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'), size = edge[prefix + 'size'] || 1, tSize = target[prefix + 'size'], sX = source[prefix + 'x'], sY = source[prefix + 'y'], tX = target[prefix + 'x'], tY = target[prefix + 'y']; size = (edge.hover) ? settings('edgeHoverSizeRatio') * size : size; var aSize = size * 2.5, d = Math.sqrt(Math.pow(tX - sX, 2) + Math.pow(tY - sY, 2)), aX = sX + (tX - sX) * (d - aSize - tSize) / d, aY = sY + (tY - sY) * (d - aSize - tSize) / d, vX = (tX - sX) * aSize / d, vY = (tY - sY) * aSize / d; if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } if (settings('edgeHoverColor') === 'edge') { color = edge.hover_color || color; } else { color = edge.hover_color || settings('defaultEdgeHoverColor') || color; } context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo(sX, sY); context.lineTo( aX, aY ); context.stroke(); context.fillStyle = color; context.beginPath(); context.moveTo(aX + vX, aY + vY); context.lineTo(aX + vY * 0.6, aY - vX * 0.6); context.lineTo(aX - vY * 0.6, aY + vX * 0.6); context.lineTo(aX + vX, aY + vY); context.closePath(); context.fill(); }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.canvas.edgehovers'); /** * This hover renderer will display the edge with a different color or size. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.edgehovers.curvedArrow = function(edge, source, target, context, settings) { var color = edge.color, prefix = settings('prefix') || '', edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'), cp = {}, size = settings('edgeHoverSizeRatio') * (edge[prefix + 'size'] || 1), tSize = target[prefix + 'size'], sX = source[prefix + 'x'], sY = source[prefix + 'y'], tX = target[prefix + 'x'], tY = target[prefix + 'y'], d, aSize, aX, aY, vX, vY; cp = (source.id === target.id) ? sigma.utils.getSelfLoopControlPoints(sX, sY, tSize) : sigma.utils.getQuadraticControlPoint(sX, sY, tX, tY); if (source.id === target.id) { d = Math.sqrt(Math.pow(tX - cp.x1, 2) + Math.pow(tY - cp.y1, 2)); aSize = size * 2.5; aX = cp.x1 + (tX - cp.x1) * (d - aSize - tSize) / d; aY = cp.y1 + (tY - cp.y1) * (d - aSize - tSize) / d; vX = (tX - cp.x1) * aSize / d; vY = (tY - cp.y1) * aSize / d; } else { d = Math.sqrt(Math.pow(tX - cp.x, 2) + Math.pow(tY - cp.y, 2)); aSize = size * 2.5; aX = cp.x + (tX - cp.x) * (d - aSize - tSize) / d; aY = cp.y + (tY - cp.y) * (d - aSize - tSize) / d; vX = (tX - cp.x) * aSize / d; vY = (tY - cp.y) * aSize / d; } if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } if (settings('edgeHoverColor') === 'edge') { color = edge.hover_color || color; } else { color = edge.hover_color || settings('defaultEdgeHoverColor') || color; } context.strokeStyle = color; context.lineWidth = size; context.beginPath(); context.moveTo(sX, sY); if (source.id === target.id) { context.bezierCurveTo(cp.x2, cp.y2, cp.x1, cp.y1, aX, aY); } else { context.quadraticCurveTo(cp.x, cp.y, aX, aY); } context.stroke(); context.fillStyle = color; context.beginPath(); context.moveTo(aX + vX, aY + vY); context.lineTo(aX + vY * 0.6, aY - vX * 0.6); context.lineTo(aX - vY * 0.6, aY + vX * 0.6); context.lineTo(aX + vX, aY + vY); context.closePath(); context.fill(); }; })(); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.canvas.extremities'); /** * The default renderer for hovered edge extremities. It renders the edge * extremities as hovered. * * @param {object} edge The edge object. * @param {object} source node The edge source node. * @param {object} target node The edge target node. * @param {CanvasRenderingContext2D} context The canvas context. * @param {configurable} settings The settings function. */ sigma.canvas.extremities.def = function(edge, source, target, context, settings) { // Source Node: ( sigma.canvas.hovers[source.type] || sigma.canvas.hovers.def ) ( source, context, settings ); // Target Node: ( sigma.canvas.hovers[target.type] || sigma.canvas.hovers.def ) ( target, context, settings ); }; }).call(this); ;(function() { 'use strict'; sigma.utils.pkg('sigma.svg.utils'); /** * Some useful functions used by sigma's SVG renderer. */ sigma.svg.utils = { /** * SVG Element show. * * @param {DOMElement} element The DOM element to show. */ show: function(element) { element.style.display = ''; return this; }, /** * SVG Element hide. * * @param {DOMElement} element The DOM element to hide. */ hide: function(element) { element.style.display = 'none'; return this; } }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.svg.nodes'); /** * The default node renderer. It renders the node as a simple disc. */ sigma.svg.nodes.def = { /** * SVG Element creation. * * @param {object} node The node object. * @param {configurable} settings The settings function. */ create: function(node, settings) { var prefix = settings('prefix') || '', circle = document.createElementNS(settings('xmlns'), 'circle'); // Defining the node's circle circle.setAttributeNS(null, 'data-node-id', node.id); circle.setAttributeNS(null, 'class', settings('classPrefix') + '-node'); circle.setAttributeNS( null, 'fill', node.color || settings('defaultNodeColor')); // Returning the DOM Element return circle; }, /** * SVG Element update. * * @param {object} node The node object. * @param {DOMElement} circle The node DOM element. * @param {configurable} settings The settings function. */ update: function(node, circle, settings) { var prefix = settings('prefix') || ''; // Applying changes // TODO: optimize - check if necessary circle.setAttributeNS(null, 'cx', node[prefix + 'x']); circle.setAttributeNS(null, 'cy', node[prefix + 'y']); circle.setAttributeNS(null, 'r', node[prefix + 'size']); // Updating only if not freestyle if (!settings('freeStyle')) circle.setAttributeNS( null, 'fill', node.color || settings('defaultNodeColor')); // Showing circle.style.display = ''; return this; } }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.svg.edges'); /** * The default edge renderer. It renders the node as a simple line. */ sigma.svg.edges.def = { /** * SVG Element creation. * * @param {object} edge The edge object. * @param {object} source The source node object. * @param {object} target The target node object. * @param {configurable} settings The settings function. */ create: function(edge, source, target, settings) { var color = edge.color, prefix = settings('prefix') || '', edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'); if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } var line = document.createElementNS(settings('xmlns'), 'line'); // Attributes line.setAttributeNS(null, 'data-edge-id', edge.id); line.setAttributeNS(null, 'class', settings('classPrefix') + '-edge'); line.setAttributeNS(null, 'stroke', color); return line; }, /** * SVG Element update. * * @param {object} edge The edge object. * @param {DOMElement} line The line DOM Element. * @param {object} source The source node object. * @param {object} target The target node object. * @param {configurable} settings The settings function. */ update: function(edge, line, source, target, settings) { var prefix = settings('prefix') || ''; line.setAttributeNS(null, 'stroke-width', edge[prefix + 'size'] || 1); line.setAttributeNS(null, 'x1', source[prefix + 'x']); line.setAttributeNS(null, 'y1', source[prefix + 'y']); line.setAttributeNS(null, 'x2', target[prefix + 'x']); line.setAttributeNS(null, 'y2', target[prefix + 'y']); // Showing line.style.display = ''; return this; } }; })(); ;(function() { 'use strict'; sigma.utils.pkg('sigma.svg.edges'); /** * The curve edge renderer. It renders the node as a bezier curve. */ sigma.svg.edges.curve = { /** * SVG Element creation. * * @param {object} edge The edge object. * @param {object} source The source node object. * @param {object} target The target node object. * @param {configurable} settings The settings function. */ create: function(edge, source, target, settings) { var color = edge.color, prefix = settings('prefix') || '', edgeColor = settings('edgeColor'), defaultNodeColor = settings('defaultNodeColor'), defaultEdgeColor = settings('defaultEdgeColor'); if (!color) switch (edgeColor) { case 'source': color = source.color || defaultNodeColor; break; case 'target': color = target.color || defaultNodeColor; break; default: color = defaultEdgeColor; break; } var path = document.createElementNS(settings('xmlns'), 'path'); // Attributes path.setAttributeNS(null, 'data-edge-id', edge.id); path.setAttributeNS(null, 'class', settings('classPrefix') + '-edge'); path.setAttributeNS(null, 'stroke', color); return path; }, /** * SVG Element update. * * @param {object} edge The edge object. * @param {DOMElement} line The line DOM Element. * @param {object} source The source node object. * @param {object} target The target node object. * @param {configurable} settings The settings function. */ update: function(edge, path, source, target, settings) { var prefix = settings('prefix') || ''; path.setAttributeNS(null, 'stroke-width', edge[prefix + 'size'] || 1); // Control point var cx = (source[prefix + 'x'] + target[prefix + 'x']) / 2 + (target[prefix + 'y'] - source[prefix + 'y']) / 4, cy = (source[prefix + 'y'] + target[prefix + 'y']) / 2 + (source[prefix + 'x'] - target[prefix + 'x']) / 4; // Path var p = 'M' + source[prefix + 'x'] + ',' + source[prefix + 'y'] + ' ' + 'Q' + cx + ',' + cy + ' ' + target[prefix + 'x'] + ',' + target[prefix + 'y']; // Updating attributes path.setAttributeNS(null, 'd', p); path.setAttributeNS(null, 'fill', 'none'); // Showing path.style.display = ''; return this; } }; })(); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.svg.labels'); /** * The default label renderer. It renders the label as a simple text. */ sigma.svg.labels.def = { /** * SVG Element creation. * * @param {object} node The node object. * @param {configurable} settings The settings function. */ create: function(node, settings) { var prefix = settings('prefix') || '', size = node[prefix + 'size'], text = document.createElementNS(settings('xmlns'), 'text'); var fontSize = (settings('labelSize') === 'fixed') ? settings('defaultLabelSize') : settings('labelSizeRatio') * size; var fontColor = (settings('labelColor') === 'node') ? (node.color || settings('defaultNodeColor')) : settings('defaultLabelColor'); text.setAttributeNS(null, 'data-label-target', node.id); text.setAttributeNS(null, 'class', settings('classPrefix') + '-label'); text.setAttributeNS(null, 'font-size', fontSize); text.setAttributeNS(null, 'font-family', settings('font')); text.setAttributeNS(null, 'fill', fontColor); text.innerHTML = node.label; text.textContent = node.label; return text; }, /** * SVG Element update. * * @param {object} node The node object. * @param {DOMElement} text The label DOM element. * @param {configurable} settings The settings function. */ update: function(node, text, settings) { var prefix = settings('prefix') || '', size = node[prefix + 'size']; var fontSize = (settings('labelSize') === 'fixed') ? settings('defaultLabelSize') : settings('labelSizeRatio') * size; // Case when we don't want to display the label if (!settings('forceLabels') && size < settings('labelThreshold')) return; if (typeof node.label !== 'string') return; // Updating text.setAttributeNS(null, 'x', Math.round(node[prefix + 'x'] + size + 3)); text.setAttributeNS(null, 'y', Math.round(node[prefix + 'y'] + fontSize / 3)); // Showing text.style.display = ''; return this; } }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.svg.hovers'); /** * The default hover renderer. */ sigma.svg.hovers.def = { /** * SVG Element creation. * * @param {object} node The node object. * @param {CanvasElement} measurementCanvas A fake canvas handled by * the svg to perform some measurements and * passed by the renderer. * @param {DOMElement} nodeCircle The node DOM Element. * @param {configurable} settings The settings function. */ create: function(node, nodeCircle, measurementCanvas, settings) { // Defining visual properties var x, y, w, h, e, d, fontStyle = settings('hoverFontStyle') || settings('fontStyle'), prefix = settings('prefix') || '', size = node[prefix + 'size'], fontSize = (settings('labelSize') === 'fixed') ? settings('defaultLabelSize') : settings('labelSizeRatio') * size, fontColor = (settings('labelHoverColor') === 'node') ? (node.color || settings('defaultNodeColor')) : settings('defaultLabelHoverColor'); // Creating elements var group = document.createElementNS(settings('xmlns'), 'g'), rectangle = document.createElementNS(settings('xmlns'), 'rect'), circle = document.createElementNS(settings('xmlns'), 'circle'), text = document.createElementNS(settings('xmlns'), 'text'); // Defining properties group.setAttributeNS(null, 'class', settings('classPrefix') + '-hover'); group.setAttributeNS(null, 'data-node-id', node.id); if (typeof node.label === 'string') { // Text text.innerHTML = node.label; text.textContent = node.label; text.setAttributeNS( null, 'class', settings('classPrefix') + '-hover-label'); text.setAttributeNS(null, 'font-size', fontSize); text.setAttributeNS(null, 'font-family', settings('font')); text.setAttributeNS(null, 'fill', fontColor); text.setAttributeNS(null, 'x', Math.round(node[prefix + 'x'] + size + 3)); text.setAttributeNS(null, 'y', Math.round(node[prefix + 'y'] + fontSize / 3)); // Measures // OPTIMIZE: Find a better way than a measurement canvas x = Math.round(node[prefix + 'x'] - fontSize / 2 - 2); y = Math.round(node[prefix + 'y'] - fontSize / 2 - 2); w = Math.round( measurementCanvas.measureText(node.label).width + fontSize / 2 + size + 9 ); h = Math.round(fontSize + 4); e = Math.round(fontSize / 2 + 2); // Circle circle.setAttributeNS( null, 'class', settings('classPrefix') + '-hover-area'); circle.setAttributeNS(null, 'fill', '#fff'); circle.setAttributeNS(null, 'cx', node[prefix + 'x']); circle.setAttributeNS(null, 'cy', node[prefix + 'y']); circle.setAttributeNS(null, 'r', e); // Rectangle rectangle.setAttributeNS( null, 'class', settings('classPrefix') + '-hover-area'); rectangle.setAttributeNS(null, 'fill', '#fff'); rectangle.setAttributeNS(null, 'x', node[prefix + 'x'] + e / 4); rectangle.setAttributeNS(null, 'y', node[prefix + 'y'] - e); rectangle.setAttributeNS(null, 'width', w); rectangle.setAttributeNS(null, 'height', h); } // Appending childs group.appendChild(circle); group.appendChild(rectangle); group.appendChild(text); group.appendChild(nodeCircle); return group; } }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.middlewares'); sigma.utils.pkg('sigma.utils'); /** * This middleware will rescale the graph such that it takes an optimal space * on the renderer. * * As each middleware, this function is executed in the scope of the sigma * instance. * * @param {?string} readPrefix The read prefix. * @param {?string} writePrefix The write prefix. * @param {object} options The parameters. */ sigma.middlewares.rescale = function(readPrefix, writePrefix, options) { var i, l, a, b, c, d, scale, margin, n = this.graph.nodes(), e = this.graph.edges(), settings = this.settings.embedObjects(options || {}), bounds = settings('bounds') || sigma.utils.getBoundaries( this.graph, readPrefix, true ), minX = bounds.minX, minY = bounds.minY, maxX = bounds.maxX, maxY = bounds.maxY, sizeMax = bounds.sizeMax, weightMax = bounds.weightMax, w = settings('width') || 1, h = settings('height') || 1, rescaleSettings = settings('autoRescale'), validSettings = { nodePosition: 1, nodeSize: 1, edgeSize: 1 }; /** * What elements should we rescale? */ if (!(rescaleSettings instanceof Array)) rescaleSettings = ['nodePosition', 'nodeSize', 'edgeSize']; for (i = 0, l = rescaleSettings.length; i < l; i++) if (!validSettings[rescaleSettings[i]]) throw new Error( 'The rescale setting "' + rescaleSettings[i] + '" is not recognized.' ); var np = ~rescaleSettings.indexOf('nodePosition'), ns = ~rescaleSettings.indexOf('nodeSize'), es = ~rescaleSettings.indexOf('edgeSize'); /** * First, we compute the scaling ratio, without considering the sizes * of the nodes : Each node will have its center in the canvas, but might * be partially out of it. */ scale = settings('scalingMode') === 'outside' ? Math.max( w / Math.max(maxX - minX, 1), h / Math.max(maxY - minY, 1) ) : Math.min( w / Math.max(maxX - minX, 1), h / Math.max(maxY - minY, 1) ); /** * Then, we correct that scaling ratio considering a margin, which is * basically the size of the biggest node. * This has to be done as a correction since to compare the size of the * biggest node to the X and Y values, we have to first get an * approximation of the scaling ratio. **/ margin = ( settings('rescaleIgnoreSize') ? 0 : (settings('maxNodeSize') || sizeMax) / scale ) + (settings('sideMargin') || 0); maxX += margin; minX -= margin; maxY += margin; minY -= margin; // Fix the scaling with the new extrema: scale = settings('scalingMode') === 'outside' ? Math.max( w / Math.max(maxX - minX, 1), h / Math.max(maxY - minY, 1) ) : Math.min( w / Math.max(maxX - minX, 1), h / Math.max(maxY - minY, 1) ); // Size homothetic parameters: if (!settings('maxNodeSize') && !settings('minNodeSize')) { a = 1; b = 0; } else if (settings('maxNodeSize') === settings('minNodeSize')) { a = 0; b = +settings('maxNodeSize'); } else { a = (settings('maxNodeSize') - settings('minNodeSize')) / sizeMax; b = +settings('minNodeSize'); } if (!settings('maxEdgeSize') && !settings('minEdgeSize')) { c = 1; d = 0; } else if (settings('maxEdgeSize') === settings('minEdgeSize')) { c = 0; d = +settings('minEdgeSize'); } else { c = (settings('maxEdgeSize') - settings('minEdgeSize')) / weightMax; d = +settings('minEdgeSize'); } // Rescale the nodes and edges: for (i = 0, l = e.length; i < l; i++) e[i][writePrefix + 'size'] = e[i][readPrefix + 'size'] * (es ? c : 1) + (es ? d : 0); for (i = 0, l = n.length; i < l; i++) { n[i][writePrefix + 'size'] = n[i][readPrefix + 'size'] * (ns ? a : 1) + (ns ? b : 0); n[i][writePrefix + 'x'] = (n[i][readPrefix + 'x'] - (maxX + minX) / 2) * (np ? scale : 1); n[i][writePrefix + 'y'] = (n[i][readPrefix + 'y'] - (maxY + minY) / 2) * (np ? scale : 1); } }; sigma.utils.getBoundaries = function(graph, prefix, doEdges) { var i, l, e = graph.edges(), n = graph.nodes(), weightMax = -Infinity, sizeMax = -Infinity, minX = Infinity, minY = Infinity, maxX = -Infinity, maxY = -Infinity; if (doEdges) for (i = 0, l = e.length; i < l; i++) weightMax = Math.max(e[i][prefix + 'size'], weightMax); for (i = 0, l = n.length; i < l; i++) { sizeMax = Math.max(n[i][prefix + 'size'], sizeMax); maxX = Math.max(n[i][prefix + 'x'], maxX); minX = Math.min(n[i][prefix + 'x'], minX); maxY = Math.max(n[i][prefix + 'y'], maxY); minY = Math.min(n[i][prefix + 'y'], minY); } weightMax = weightMax || 1; sizeMax = sizeMax || 1; return { weightMax: weightMax, sizeMax: sizeMax, minX: minX, minY: minY, maxX: maxX, maxY: maxY }; }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.middlewares'); /** * This middleware will just copy the graphic properties. * * @param {?string} readPrefix The read prefix. * @param {?string} writePrefix The write prefix. */ sigma.middlewares.copy = function(readPrefix, writePrefix) { var i, l, a; if (writePrefix + '' === readPrefix + '') return; a = this.graph.nodes(); for (i = 0, l = a.length; i < l; i++) { a[i][writePrefix + 'x'] = a[i][readPrefix + 'x']; a[i][writePrefix + 'y'] = a[i][readPrefix + 'y']; a[i][writePrefix + 'size'] = a[i][readPrefix + 'size']; } a = this.graph.edges(); for (i = 0, l = a.length; i < l; i++) a[i][writePrefix + 'size'] = a[i][readPrefix + 'size']; }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.misc.animation.running'); /** * Generates a unique ID for the animation. * * @return {string} Returns the new ID. */ var _getID = (function() { var id = 0; return function() { return '' + (++id); }; })(); /** * This function animates a camera. It has to be called with the camera to * animate, the values of the coordinates to reach and eventually some * options. It returns a number id, that you can use to kill the animation, * with the method sigma.misc.animation.kill(id). * * The available options are: * * {?number} duration The duration of the animation. * {?function} onNewFrame A callback to execute when the animation * enter a new frame. * {?function} onComplete A callback to execute when the animation * is completed or killed. * {?(string|function)} easing The name of a function from the package * sigma.utils.easings, or a custom easing * function. * * @param {camera} camera The camera to animate. * @param {object} target The coordinates to reach. * @param {?object} options Eventually an object to specify some options to * the function. The available options are * presented in the description of the function. * @return {number} The animation id, to make it easy to kill * through the method "sigma.misc.animation.kill". */ sigma.misc.animation.camera = function(camera, val, options) { if ( !(camera instanceof sigma.classes.camera) || typeof val !== 'object' || !val ) throw 'animation.camera: Wrong arguments.'; if ( typeof val.x !== 'number' && typeof val.y !== 'number' && typeof val.ratio !== 'number' && typeof val.angle !== 'number' ) throw 'There must be at least one valid coordinate in the given val.'; var fn, id, anim, easing, duration, initialVal, o = options || {}, start = sigma.utils.dateNow(); // Store initial values: initialVal = { x: camera.x, y: camera.y, ratio: camera.ratio, angle: camera.angle }; duration = o.duration; easing = typeof o.easing !== 'function' ? sigma.utils.easings[o.easing || 'quadraticInOut'] : o.easing; fn = function() { var coef, t = o.duration ? (sigma.utils.dateNow() - start) / o.duration : 1; // If the animation is over: if (t >= 1) { camera.isAnimated = false; camera.goTo({ x: val.x !== undefined ? val.x : initialVal.x, y: val.y !== undefined ? val.y : initialVal.y, ratio: val.ratio !== undefined ? val.ratio : initialVal.ratio, angle: val.angle !== undefined ? val.angle : initialVal.angle }); cancelAnimationFrame(id); delete sigma.misc.animation.running[id]; // Check callbacks: if (typeof o.onComplete === 'function') o.onComplete(); // Else, let's keep going: } else { coef = easing(t); camera.isAnimated = true; camera.goTo({ x: val.x !== undefined ? initialVal.x + (val.x - initialVal.x) * coef : initialVal.x, y: val.y !== undefined ? initialVal.y + (val.y - initialVal.y) * coef : initialVal.y, ratio: val.ratio !== undefined ? initialVal.ratio + (val.ratio - initialVal.ratio) * coef : initialVal.ratio, angle: val.angle !== undefined ? initialVal.angle + (val.angle - initialVal.angle) * coef : initialVal.angle }); // Check callbacks: if (typeof o.onNewFrame === 'function') o.onNewFrame(); anim.frameId = requestAnimationFrame(fn); } }; id = _getID(); anim = { frameId: requestAnimationFrame(fn), target: camera, type: 'camera', options: o, fn: fn }; sigma.misc.animation.running[id] = anim; return id; }; /** * Kills a running animation. It triggers the eventual onComplete callback. * * @param {number} id The id of the animation to kill. * @return {object} Returns the sigma.misc.animation package. */ sigma.misc.animation.kill = function(id) { if (arguments.length !== 1 || typeof id !== 'number') throw 'animation.kill: Wrong arguments.'; var o = sigma.misc.animation.running[id]; if (o) { cancelAnimationFrame(id); delete sigma.misc.animation.running[o.frameId]; if (o.type === 'camera') o.target.isAnimated = false; // Check callbacks: if (typeof (o.options || {}).onComplete === 'function') o.options.onComplete(); } return this; }; /** * Kills every running animations, or only the one with the specified type, * if a string parameter is given. * * @param {?(string|object)} filter A string to filter the animations to kill * on their type (example: "camera"), or an * object to filter on their target. * @return {number} Returns the number of animations killed * that way. */ sigma.misc.animation.killAll = function(filter) { var o, id, count = 0, type = typeof filter === 'string' ? filter : null, target = typeof filter === 'object' ? filter : null, running = sigma.misc.animation.running; for (id in running) if ( (!type || running[id].type === type) && (!target || running[id].target === target) ) { o = sigma.misc.animation.running[id]; cancelAnimationFrame(o.frameId); delete sigma.misc.animation.running[id]; if (o.type === 'camera') o.target.isAnimated = false; // Increment counter: count++; // Check callbacks: if (typeof (o.options || {}).onComplete === 'function') o.options.onComplete(); } return count; }; /** * Returns "true" if any animation that is currently still running matches * the filter given to the function. * * @param {string|object} filter A string to filter the animations to kill * on their type (example: "camera"), or an * object to filter on their target. * @return {boolean} Returns true if any running animation * matches. */ sigma.misc.animation.has = function(filter) { var id, type = typeof filter === 'string' ? filter : null, target = typeof filter === 'object' ? filter : null, running = sigma.misc.animation.running; for (id in running) if ( (!type || running[id].type === type) && (!target || running[id].target === target) ) return true; return false; }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.misc'); /** * This helper will bind any no-DOM renderer (for instance canvas or WebGL) * to its captors, to properly dispatch the good events to the sigma instance * to manage clicking, hovering etc... * * It has to be called in the scope of the related renderer. */ sigma.misc.bindEvents = function(prefix) { var i, l, mX, mY, captor, self = this; function getNodes(e) { if (e) { mX = 'x' in e.data ? e.data.x : mX; mY = 'y' in e.data ? e.data.y : mY; } var i, j, l, n, x, y, s, inserted, selected = [], modifiedX = mX + self.width / 2, modifiedY = mY + self.height / 2, point = self.camera.cameraPosition( mX, mY ), nodes = self.camera.quadtree.point( point.x, point.y ); if (nodes.length) for (i = 0, l = nodes.length; i < l; i++) { n = nodes[i]; x = n[prefix + 'x']; y = n[prefix + 'y']; s = n[prefix + 'size']; if ( !n.hidden && modifiedX > x - s && modifiedX < x + s && modifiedY > y - s && modifiedY < y + s && Math.sqrt( Math.pow(modifiedX - x, 2) + Math.pow(modifiedY - y, 2) ) < s ) { // Insert the node: inserted = false; for (j = 0; j < selected.length; j++) if (n.size > selected[j].size) { selected.splice(j, 0, n); inserted = true; break; } if (!inserted) selected.push(n); } } return selected; } function getEdges(e) { if (!self.settings('enableEdgeHovering')) { // No event if the setting is off: return []; } var isCanvas = ( sigma.renderers.canvas && self instanceof sigma.renderers.canvas); if (!isCanvas) { // A quick hardcoded rule to prevent people from using this feature // with the WebGL renderer (which is not good enough at the moment): throw new Error( 'The edge events feature is not compatible with the WebGL renderer' ); } if (e) { mX = 'x' in e.data ? e.data.x : mX; mY = 'y' in e.data ? e.data.y : mY; } var i, j, l, a, edge, s, maxEpsilon = self.settings('edgeHoverPrecision'), source, target, cp, nodeIndex = {}, inserted, selected = [], modifiedX = mX + self.width / 2, modifiedY = mY + self.height / 2, point = self.camera.cameraPosition( mX, mY ), edges = []; if (isCanvas) { var nodesOnScreen = self.camera.quadtree.area( self.camera.getRectangle(self.width, self.height) ); for (a = nodesOnScreen, i = 0, l = a.length; i < l; i++) nodeIndex[a[i].id] = a[i]; } if (self.camera.edgequadtree !== undefined) { edges = self.camera.edgequadtree.point( point.x, point.y ); } function insertEdge(selected, edge) { inserted = false; for (j = 0; j < selected.length; j++) if (edge.size > selected[j].size) { selected.splice(j, 0, edge); inserted = true; break; } if (!inserted) selected.push(edge); } if (edges.length) for (i = 0, l = edges.length; i < l; i++) { edge = edges[i]; source = self.graph.nodes(edge.source); target = self.graph.nodes(edge.target); // (HACK) we can't get edge[prefix + 'size'] on WebGL renderer: s = edge[prefix + 'size'] || edge['read_' + prefix + 'size']; // First, let's identify which edges are drawn. To do this, we keep // every edges that have at least one extremity displayed according to // the quadtree and the "hidden" attribute. We also do not keep hidden // edges. // Then, let's check if the mouse is on the edge (we suppose that it // is a line segment). if ( !edge.hidden && !source.hidden && !target.hidden && (!isCanvas || (nodeIndex[edge.source] || nodeIndex[edge.target])) && sigma.utils.getDistance( source[prefix + 'x'], source[prefix + 'y'], modifiedX, modifiedY) > source[prefix + 'size'] && sigma.utils.getDistance( target[prefix + 'x'], target[prefix + 'y'], modifiedX, modifiedY) > target[prefix + 'size'] ) { if (edge.type == 'curve' || edge.type == 'curvedArrow') { if (source.id === target.id) { cp = sigma.utils.getSelfLoopControlPoints( source[prefix + 'x'], source[prefix + 'y'], source[prefix + 'size'] ); if ( sigma.utils.isPointOnBezierCurve( modifiedX, modifiedY, source[prefix + 'x'], source[prefix + 'y'], target[prefix + 'x'], target[prefix + 'y'], cp.x1, cp.y1, cp.x2, cp.y2, Math.max(s, maxEpsilon) )) { insertEdge(selected, edge); } } else { cp = sigma.utils.getQuadraticControlPoint( source[prefix + 'x'], source[prefix + 'y'], target[prefix + 'x'], target[prefix + 'y']); if ( sigma.utils.isPointOnQuadraticCurve( modifiedX, modifiedY, source[prefix + 'x'], source[prefix + 'y'], target[prefix + 'x'], target[prefix + 'y'], cp.x, cp.y, Math.max(s, maxEpsilon) )) { insertEdge(selected, edge); } } } else if ( sigma.utils.isPointOnSegment( modifiedX, modifiedY, source[prefix + 'x'], source[prefix + 'y'], target[prefix + 'x'], target[prefix + 'y'], Math.max(s, maxEpsilon) )) { insertEdge(selected, edge); } } } return selected; } function bindCaptor(captor) { var nodes, edges, overNodes = {}, overEdges = {}; function onClick(e) { if (!self.settings('eventsEnabled')) return; self.dispatchEvent('click', e.data); nodes = getNodes(e); edges = getEdges(e); if (nodes.length) { self.dispatchEvent('clickNode', { node: nodes[0], captor: e.data }); self.dispatchEvent('clickNodes', { node: nodes, captor: e.data }); } else if (edges.length) { self.dispatchEvent('clickEdge', { edge: edges[0], captor: e.data }); self.dispatchEvent('clickEdges', { edge: edges, captor: e.data }); } else self.dispatchEvent('clickStage', {captor: e.data}); } function onDoubleClick(e) { if (!self.settings('eventsEnabled')) return; self.dispatchEvent('doubleClick', e.data); nodes = getNodes(e); edges = getEdges(e); if (nodes.length) { self.dispatchEvent('doubleClickNode', { node: nodes[0], captor: e.data }); self.dispatchEvent('doubleClickNodes', { node: nodes, captor: e.data }); } else if (edges.length) { self.dispatchEvent('doubleClickEdge', { edge: edges[0], captor: e.data }); self.dispatchEvent('doubleClickEdges', { edge: edges, captor: e.data }); } else self.dispatchEvent('doubleClickStage', {captor: e.data}); } function onRightClick(e) { if (!self.settings('eventsEnabled')) return; self.dispatchEvent('rightClick', e.data); nodes = getNodes(e); edges = getEdges(e); if (nodes.length) { self.dispatchEvent('rightClickNode', { node: nodes[0], captor: e.data }); self.dispatchEvent('rightClickNodes', { node: nodes, captor: e.data }); } else if (edges.length) { self.dispatchEvent('rightClickEdge', { edge: edges[0], captor: e.data }); self.dispatchEvent('rightClickEdges', { edge: edges, captor: e.data }); } else self.dispatchEvent('rightClickStage', {captor: e.data}); } function onOut(e) { if (!self.settings('eventsEnabled')) return; var k, i, l, le, outNodes = [], outEdges = []; for (k in overNodes) outNodes.push(overNodes[k]); overNodes = {}; // Dispatch both single and multi events: for (i = 0, l = outNodes.length; i < l; i++) self.dispatchEvent('outNode', { node: outNodes[i], captor: e.data }); if (outNodes.length) self.dispatchEvent('outNodes', { nodes: outNodes, captor: e.data }); overEdges = {}; // Dispatch both single and multi events: for (i = 0, le = outEdges.length; i < le; i++) self.dispatchEvent('outEdge', { edge: outEdges[i], captor: e.data }); if (outEdges.length) self.dispatchEvent('outEdges', { edges: outEdges, captor: e.data }); } function onMove(e) { if (!self.settings('eventsEnabled')) return; nodes = getNodes(e); edges = getEdges(e); var i, k, node, edge, newOutNodes = [], newOverNodes = [], currentOverNodes = {}, l = nodes.length, newOutEdges = [], newOverEdges = [], currentOverEdges = {}, le = edges.length; // Check newly overred nodes: for (i = 0; i < l; i++) { node = nodes[i]; currentOverNodes[node.id] = node; if (!overNodes[node.id]) { newOverNodes.push(node); overNodes[node.id] = node; } } // Check no more overred nodes: for (k in overNodes) if (!currentOverNodes[k]) { newOutNodes.push(overNodes[k]); delete overNodes[k]; } // Dispatch both single and multi events: for (i = 0, l = newOverNodes.length; i < l; i++) self.dispatchEvent('overNode', { node: newOverNodes[i], captor: e.data }); for (i = 0, l = newOutNodes.length; i < l; i++) self.dispatchEvent('outNode', { node: newOutNodes[i], captor: e.data }); if (newOverNodes.length) self.dispatchEvent('overNodes', { nodes: newOverNodes, captor: e.data }); if (newOutNodes.length) self.dispatchEvent('outNodes', { nodes: newOutNodes, captor: e.data }); // Check newly overred edges: for (i = 0; i < le; i++) { edge = edges[i]; currentOverEdges[edge.id] = edge; if (!overEdges[edge.id]) { newOverEdges.push(edge); overEdges[edge.id] = edge; } } // Check no more overred edges: for (k in overEdges) if (!currentOverEdges[k]) { newOutEdges.push(overEdges[k]); delete overEdges[k]; } // Dispatch both single and multi events: for (i = 0, le = newOverEdges.length; i < le; i++) self.dispatchEvent('overEdge', { edge: newOverEdges[i], captor: e.data }); for (i = 0, le = newOutEdges.length; i < le; i++) self.dispatchEvent('outEdge', { edge: newOutEdges[i], captor: e.data }); if (newOverEdges.length) self.dispatchEvent('overEdges', { edges: newOverEdges, captor: e.data }); if (newOutEdges.length) self.dispatchEvent('outEdges', { edges: newOutEdges, captor: e.data }); } // Bind events: captor.bind('click', onClick); captor.bind('mousedown', onMove); captor.bind('mouseup', onMove); captor.bind('mousemove', onMove); captor.bind('mouseout', onOut); captor.bind('doubleclick', onDoubleClick); captor.bind('rightclick', onRightClick); self.bind('render', onMove); } for (i = 0, l = this.captors.length; i < l; i++) bindCaptor(this.captors[i]); }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.misc'); /** * This helper will bind any DOM renderer (for instance svg) * to its captors, to properly dispatch the good events to the sigma instance * to manage clicking, hovering etc... * * It has to be called in the scope of the related renderer. */ sigma.misc.bindDOMEvents = function(container) { var self = this, graph = this.graph; // DOMElement abstraction function Element(domElement) { // Helpers this.attr = function(attrName) { return domElement.getAttributeNS(null, attrName); }; // Properties this.tag = domElement.tagName; this.class = this.attr('class'); this.id = this.attr('id'); // Methods this.isNode = function() { return !!~this.class.indexOf(self.settings('classPrefix') + '-node'); }; this.isEdge = function() { return !!~this.class.indexOf(self.settings('classPrefix') + '-edge'); }; this.isHover = function() { return !!~this.class.indexOf(self.settings('classPrefix') + '-hover'); }; } // Click function click(e) { if (!self.settings('eventsEnabled')) return; // Generic event self.dispatchEvent('click', e); // Are we on a node? var element = new Element(e.target); if (element.isNode()) self.dispatchEvent('clickNode', { node: graph.nodes(element.attr('data-node-id')) }); else self.dispatchEvent('clickStage'); e.preventDefault(); e.stopPropagation(); } // Double click function doubleClick(e) { if (!self.settings('eventsEnabled')) return; // Generic event self.dispatchEvent('doubleClick', e); // Are we on a node? var element = new Element(e.target); if (element.isNode()) self.dispatchEvent('doubleClickNode', { node: graph.nodes(element.attr('data-node-id')) }); else self.dispatchEvent('doubleClickStage'); e.preventDefault(); e.stopPropagation(); } // On over function onOver(e) { var target = e.toElement || e.target; if (!self.settings('eventsEnabled') || !target) return; var el = new Element(target); if (el.isNode()) { self.dispatchEvent('overNode', { node: graph.nodes(el.attr('data-node-id')) }); } else if (el.isEdge()) { var edge = graph.edges(el.attr('data-edge-id')); self.dispatchEvent('overEdge', { edge: edge, source: graph.nodes(edge.source), target: graph.nodes(edge.target) }); } } // On out function onOut(e) { var target = e.fromElement || e.originalTarget; if (!self.settings('eventsEnabled')) return; var el = new Element(target); if (el.isNode()) { self.dispatchEvent('outNode', { node: graph.nodes(el.attr('data-node-id')) }); } else if (el.isEdge()) { var edge = graph.edges(el.attr('data-edge-id')); self.dispatchEvent('outEdge', { edge: edge, source: graph.nodes(edge.source), target: graph.nodes(edge.target) }); } } // Registering Events: // Click container.addEventListener('click', click, false); sigma.utils.doubleClick(container, 'click', doubleClick); // Touch counterparts container.addEventListener('touchstart', click, false); sigma.utils.doubleClick(container, 'touchstart', doubleClick); // Mouseover container.addEventListener('mouseover', onOver, true); // Mouseout container.addEventListener('mouseout', onOut, true); }; }).call(this); ;(function(undefined) { 'use strict'; if (typeof sigma === 'undefined') throw 'sigma is not declared'; // Initialize packages: sigma.utils.pkg('sigma.misc'); /** * This method listens to "overNode", "outNode", "overEdge" and "outEdge" * events from a renderer and renders the nodes differently on the top layer. * The goal is to make any node label readable with the mouse, and to * highlight hovered nodes and edges. * * It has to be called in the scope of the related renderer. */ sigma.misc.drawHovers = function(prefix) { var self = this, hoveredNodes = {}, hoveredEdges = {}; this.bind('overNode', function(event) { var node = event.data.node; if (!node.hidden) { hoveredNodes[node.id] = node; draw(); } }); this.bind('outNode', function(event) { delete hoveredNodes[event.data.node.id]; draw(); }); this.bind('overEdge', function(event) { var edge = event.data.edge; if (!edge.hidden) { hoveredEdges[edge.id] = edge; draw(); } }); this.bind('outEdge', function(event) { delete hoveredEdges[event.data.edge.id]; draw(); }); this.bind('render', function(event) { draw(); }); function draw() { // Clear self.contexts.hover: self.contexts.hover.canvas.width = self.contexts.hover.canvas.width; var k, source, target, hoveredNode, hoveredEdge, defaultNodeType = self.settings('defaultNodeType'), defaultEdgeType = self.settings('defaultEdgeType'), nodeRenderers = sigma.canvas.hovers, edgeRenderers = sigma.canvas.edgehovers, extremitiesRenderers = sigma.canvas.extremities, embedSettings = self.settings.embedObjects({ prefix: prefix }); // Node render: single hover if ( embedSettings('enableHovering') && embedSettings('singleHover') && Object.keys(hoveredNodes).length ) { hoveredNode = hoveredNodes[Object.keys(hoveredNodes)[0]]; ( nodeRenderers[hoveredNode.type] || nodeRenderers[defaultNodeType] || nodeRenderers.def )( hoveredNode, self.contexts.hover, embedSettings ); } // Node render: multiple hover if ( embedSettings('enableHovering') && !embedSettings('singleHover') ) for (k in hoveredNodes) ( nodeRenderers[hoveredNodes[k].type] || nodeRenderers[defaultNodeType] || nodeRenderers.def )( hoveredNodes[k], self.contexts.hover, embedSettings ); // Edge render: single hover if ( embedSettings('enableEdgeHovering') && embedSettings('singleHover') && Object.keys(hoveredEdges).length ) { hoveredEdge = hoveredEdges[Object.keys(hoveredEdges)[0]]; source = self.graph.nodes(hoveredEdge.source); target = self.graph.nodes(hoveredEdge.target); if (! hoveredEdge.hidden) { ( edgeRenderers[hoveredEdge.type] || edgeRenderers[defaultEdgeType] || edgeRenderers.def ) ( hoveredEdge, source, target, self.contexts.hover, embedSettings ); if (embedSettings('edgeHoverExtremities')) { ( extremitiesRenderers[hoveredEdge.type] || extremitiesRenderers.def )( hoveredEdge, source, target, self.contexts.hover, embedSettings ); } else { // Avoid edges rendered over nodes: ( sigma.canvas.nodes[source.type] || sigma.canvas.nodes.def ) ( source, self.contexts.hover, embedSettings ); ( sigma.canvas.nodes[target.type] || sigma.canvas.nodes.def ) ( target, self.contexts.hover, embedSettings ); } } } // Edge render: multiple hover if ( embedSettings('enableEdgeHovering') && !embedSettings('singleHover') ) { for (k in hoveredEdges) { hoveredEdge = hoveredEdges[k]; source = self.graph.nodes(hoveredEdge.source); target = self.graph.nodes(hoveredEdge.target); if (!hoveredEdge.hidden) { ( edgeRenderers[hoveredEdge.type] || edgeRenderers[defaultEdgeType] || edgeRenderers.def ) ( hoveredEdge, source, target, self.contexts.hover, embedSettings ); if (embedSettings('edgeHoverExtremities')) { ( extremitiesRenderers[hoveredEdge.type] || extremitiesRenderers.def )( hoveredEdge, source, target, self.contexts.hover, embedSettings ); } else { // Avoid edges rendered over nodes: ( sigma.canvas.nodes[source.type] || sigma.canvas.nodes.def ) ( source, self.contexts.hover, embedSettings ); ( sigma.canvas.nodes[target.type] || sigma.canvas.nodes.def ) ( target, self.contexts.hover, embedSettings ); } } } } } }; }).call(this);
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/worker-latex_beta.js
3,207
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; if (!window.console) { window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; } window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); } } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!(range instanceof Range)) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject(array[i]); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } if (Object.prototype.toString.call(obj) !== "[object Object]") return obj; copy = {}; for (var key in obj) copy[key] = deepCopy(obj[key]); return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/latex_beta_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var LatexWorker = exports.LatexWorker = function(sender) { Mirror.call(this, sender); this.setTimeout(250); }; oop.inherits(LatexWorker, Mirror); var Tokenise = function (text) { var Tokens = []; var Comments = []; var pos = -1; var SPECIAL = /[\\\{\}\$\&\#\^\_\~\%]/g; // match TeX special characters var NEXTCS = /[^a-zA-Z]/g; // match characters which aren't part of a TeX control sequence var idx = 0; var lineNumber = 0; // current line number when parsing tokens (zero-based) var linePosition = []; // mapping from line number to absolute offset of line in text[] linePosition[0] = 0; var checkingDisabled = false; var count = 0; // number of tokens parses var MAX_TOKENS = 100000; while (true) { count++; if (count > MAX_TOKENS) { throw new Error("exceed max token count of " + MAX_TOKENS); break; }; var result = SPECIAL.exec(text); if (result == null) { if (idx < text.length) { Tokens.push([lineNumber, "Text", idx, text.length]); } break; } if (result && result.index <= pos) { throw new Error("infinite loop in parsing"); break; }; pos = result.index; if (pos > idx) { Tokens.push([lineNumber, "Text", idx, pos]); } for (var i = idx; i < pos; i++) { if (text[i] === "\n") { lineNumber++; linePosition[lineNumber] = i+1; } } var newIdx = SPECIAL.lastIndex; idx = newIdx; var code = result[0]; if (code === "%") { // comment character var newLinePos = text.indexOf("\n", idx); if (newLinePos === -1) { newLinePos = text.length; }; var commentString = text.substring(idx, newLinePos); if (commentString.indexOf("%novalidate") === 0) { return []; } else if(!checkingDisabled && commentString.indexOf("%begin novalidate") === 0) { checkingDisabled = true; } else if (checkingDisabled && commentString.indexOf("%end novalidate") === 0) { checkingDisabled = false; }; idx = SPECIAL.lastIndex = newLinePos + 1; Comments.push([lineNumber, idx, newLinePos]); lineNumber++; linePosition[lineNumber] = idx; } else if (checkingDisabled) { continue; } else if (code === '\\') { // escape character NEXTCS.lastIndex = idx; var controlSequence = NEXTCS.exec(text); var nextSpecialPos = controlSequence === null ? idx : controlSequence.index; if (nextSpecialPos === idx) { Tokens.push([lineNumber, code, pos, idx + 1, text[idx], "control-symbol"]); idx = SPECIAL.lastIndex = idx + 1; char = text[nextSpecialPos]; if (char === '\n') { lineNumber++; linePosition[lineNumber] = nextSpecialPos;}; } else { Tokens.push([lineNumber, code, pos, nextSpecialPos, text.slice(idx, nextSpecialPos)]); var char; while ((char = text[nextSpecialPos]) === ' ' || char === '\t' || char === '\r' || char === '\n') { nextSpecialPos++; if (char === '\n') { lineNumber++; linePosition[lineNumber] = nextSpecialPos;}; } idx = SPECIAL.lastIndex = nextSpecialPos; } } else if (code === "{") { // open group Tokens.push([lineNumber, code, pos]); } else if (code === "}") { // close group Tokens.push([lineNumber, code, pos]); } else if (code === "$") { // math mode Tokens.push([lineNumber, code, pos]); } else if (code === "&") { // tabalign Tokens.push([lineNumber, code, pos]); } else if (code === "#") { // macro parameter Tokens.push([lineNumber, code, pos]); } else if (code === "^") { // superscript Tokens.push([lineNumber, code, pos]); } else if (code === "_") { // subscript Tokens.push([lineNumber, code, pos]); } else if (code === "~") { // active character (space) Tokens.push([lineNumber, code, pos]); } else { throw "unrecognised character " + code; } } return {tokens: Tokens, comments: Comments, linePosition: linePosition, lineNumber: lineNumber, text: text}; }; var read1arg = function (TokeniseResult, k, options) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; if (options && options.allowStar) { var optional = Tokens[k+1]; if (optional && optional[1] === "Text") { var optionalstr = text.substring(optional[2], optional[3]); if (optionalstr === "*") { k++;} }; }; var open = Tokens[k+1]; var env = Tokens[k+2]; var close = Tokens[k+3]; var envName; if(open && open[1] === "\\") { envName = open[4]; // array element 4 is command sequence return k + 1; } else if(open && open[1] === "{" && env && env[1] === "\\" && close && close[1] === "}") { envName = env[4]; // NOTE: if we were actually using this, keep track of * above return k + 3; // array element 4 is command sequence } else { return null; } }; var readLetDefinition = function (TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var first = Tokens[k+1]; var second = Tokens[k+2]; var third = Tokens[k+3]; if(first && first[1] === "\\" && second && second[1] === "\\") { return k + 2; } else if(first && first[1] === "\\" && second && second[1] === "Text" && text.substring(second[2], second[3]) === "=" && third && third[1] === "\\") { return k + 3; } else { return null; } }; var read1name = function (TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var open = Tokens[k+1]; var env = Tokens[k+2]; var close = Tokens[k+3]; if(open && open[1] === "{" && env && env[1] === "Text" && close && close[1] === "}") { var envName = text.substring(env[2], env[3]); return k + 3; } else if (open && open[1] === "{" && env && env[1] === "Text") { envName = ""; for (var j = k + 2, tok; (tok = Tokens[j]); j++) { if (tok[1] === "Text") { var str = text.substring(tok[2], tok[3]); if (!str.match(/^\S*$/)) { break; } envName = envName + str; } else if (tok[1] === "_") { envName = envName + "_"; } else { break; } } if (tok && tok[1] === "}") { return j; // advance past these tokens } else { return null; } } else { return null; } }; var read1filename = function (TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var fileName = ""; for (var j = k + 1, tok; (tok = Tokens[j]); j++) { if (tok[1] === "Text") { var str = text.substring(tok[2], tok[3]); if (!str.match(/^\S*$/)) { break; } fileName = fileName + str; } else if (tok[1] === "_") { fileName = fileName + "_"; } else { break; } } if (fileName.length > 0) { return j; // advance past these tokens } else { return null; } }; var readOptionalParams = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var params = Tokens[k+1]; if(params && params[1] === "Text") { var paramNum = text.substring(params[2], params[3]); if (paramNum.match(/^\[\d+\](\[[^\]]*\])*\s*$/)) { return k + 1; // got it }; }; var count = 0; var nextToken = Tokens[k+1]; var pos = nextToken[2]; for (var i = pos, end = text.length; i < end; i++) { var char = text[i]; if (nextToken && i >= nextToken[2]) { k++; nextToken = Tokens[k+1];}; if (char === "[") { count++; } if (char === "]") { count--; } if (count === 0 && char === "{") { return k - 1; } if (count > 0 && (char === '\r' || char === '\n')) { return null; } }; return null; }; var readOptionalGeneric = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var params = Tokens[k+1]; if(params && params[1] === "Text") { var paramNum = text.substring(params[2], params[3]); if (paramNum.match(/^(\[[^\]]*\])+\s*$/)) { return k + 1; // got it }; }; return null; }; var readOptionalDef = function (TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var defToken = Tokens[k]; var pos = defToken[3]; var openBrace = "{"; var nextToken = Tokens[k+1]; for (var i = pos, end = text.length; i < end; i++) { var char = text[i]; if (nextToken && i >= nextToken[2]) { k++; nextToken = Tokens[k+1];}; if (char === openBrace) { return k - 1; }; // move back to the last token of the optional arguments if (char === '\r' || char === '\n') { return null; } }; return null; }; var readDefinition = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; k = k + 1; var count = 0; var nextToken = Tokens[k]; while (nextToken && nextToken[1] === "Text") { var start = nextToken[2], end = nextToken[3]; for (var i = start; i < end; i++) { var char = text[i]; if (char === ' ' || char === '\t' || char === '\r' || char === '\n') { continue; } return null; // bail out, should begin with a { } k++; nextToken = Tokens[k]; } if (nextToken && nextToken[1] === "{") { count++; while (count>0) { k++; nextToken = Tokens[k]; if(!nextToken) { break; }; if (nextToken[1] === "}") { count--; } if (nextToken[1] === "{") { count++; } } return k; } return null; }; var readVerb = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var verbToken = Tokens[k]; var verbStr = text.substring(verbToken[2], verbToken[3]); var pos = verbToken[3]; if (text[pos] === "*") { pos++; } // \verb* form of command var delimiter = text[pos]; pos++; var nextToken = Tokens[k+1]; for (var i = pos, end = text.length; i < end; i++) { var char = text[i]; if (nextToken && i >= nextToken[2]) { k++; nextToken = Tokens[k+1];}; if (char === delimiter) { return k; }; if (char === '\r' || char === '\n') { return null; } }; return null; }; var readUrl = function(TokeniseResult, k) { var Tokens = TokeniseResult.tokens; var text = TokeniseResult.text; var urlToken = Tokens[k]; var urlStr = text.substring(urlToken[2], urlToken[3]); var pos = urlToken[3]; var openDelimiter = text[pos]; var closeDelimiter = (openDelimiter === "{") ? "}" : openDelimiter; var nextToken = Tokens[k+1]; if (nextToken && pos === nextToken[2]) { k++; nextToken = Tokens[k+1]; }; pos++; var count = 1; for (var i = pos, end = text.length; count > 0 && i < end; i++) { var char = text[i]; if (nextToken && i >= nextToken[2]) { k++; nextToken = Tokens[k+1];}; if (char === closeDelimiter) { count--; } else if (char === openDelimiter) { count++; }; if (count === 0) { return k; }; if (char === '\r' || char === '\n') { return null; } }; return null; }; var InterpretTokens = function (TokeniseResult, ErrorReporter) { var Tokens = TokeniseResult.tokens; var linePosition = TokeniseResult.linePosition; var lineNumber = TokeniseResult.lineNumber; var text = TokeniseResult.text; var TokenErrorFromTo = ErrorReporter.TokenErrorFromTo; var TokenError = ErrorReporter.TokenError; var Environments = new EnvHandler(ErrorReporter); var nextGroupMathMode = null; // if the next group should have math mode on or off (for \hbox) var nextGroupMathModeStack = [] ; // tracking all nextGroupMathModes var seenUserDefinedBeginEquation = false; // if we have seen macros like \beq var seenUserDefinedEndEquation = false; // if we have seen macros like \eeq for (var i = 0, len = Tokens.length; i < len; i++) { var token = Tokens[i]; var line = token[0], type = token[1], start = token[2], end = token[3], seq = token[4]; if (type === "{") { Environments.push({command:"{", token:token, mathMode: nextGroupMathMode}); nextGroupMathModeStack.push(nextGroupMathMode); nextGroupMathMode = null; continue; } else if (type === "}") { Environments.push({command:"}", token:token}); nextGroupMathMode = nextGroupMathModeStack.pop(); continue; } else { nextGroupMathMode = null; }; if (type === "\\") { if (seq === "begin" || seq === "end") { var open = Tokens[i+1]; var env = Tokens[i+2]; var close = Tokens[i+3]; if(open && open[1] === "{" && env && env[1] === "Text" && close && close[1] === "}") { var envName = text.substring(env[2], env[3]); Environments.push({command: seq, name: envName, token: token, closeToken: close}); i = i + 3; // advance past these tokens } else { if (open && open[1] === "{" && env && env[1] === "Text") { envName = ""; for (var j = i + 2, tok; (tok = Tokens[j]); j++) { if (tok[1] === "Text") { var str = text.substring(tok[2], tok[3]); if (!str.match(/^\S*$/)) { break; } envName = envName + str; } else if (tok[1] === "_") { envName = envName + "_"; } else { break; } } if (tok && tok[1] === "}") { Environments.push({command: seq, name: envName, token: token, closeToken: close}); i = j; // advance past these tokens continue; } } var endToken = null; if (open && open[1] === "{") { endToken = open; // we've got a { if (env && env[1] === "Text") { endToken = env.slice(); // we've got some text following the { start = endToken[2]; end = endToken[3]; for (j = start; j < end; j++) { var char = text[j]; if (char === ' ' || char === '\t' || char === '\r' || char === '\n') { break; } } endToken[3] = j; // the end of partial token is as far as we got looking ahead }; }; if (endToken) { TokenErrorFromTo(token, endToken, "invalid environment command " + text.substring(token[2], endToken[3] || endToken[2])); } else { TokenError(token, "invalid environment command"); }; } } else if (typeof seq === "string" && seq.match(/^(be|beq|beqa|bea)$/i)) { seenUserDefinedBeginEquation = true; } else if (typeof seq === "string" && seq.match(/^(ee|eeq|eeqn|eeqa|eeqan|eea)$/i)) { seenUserDefinedEndEquation = true; } else if (seq === "newcommand" || seq === "renewcommand" || seq === "DeclareRobustCommand") { var newPos = read1arg(TokeniseResult, i, {allowStar: true}); if (newPos === null) { continue; } else {i = newPos;}; newPos = readOptionalParams(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "def") { newPos = read1arg(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; newPos = readOptionalDef(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "let") { newPos = readLetDefinition(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; } else if (seq === "newcolumntype") { newPos = read1name(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; newPos = readOptionalParams(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "newenvironment" || seq === "renewenvironment") { newPos = read1name(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; newPos = readOptionalParams(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "verb") { newPos = readVerb(TokeniseResult, i); if (newPos === null) { TokenError(token, "invalid verbatim command"); } else {i = newPos;}; } else if (seq === "url") { newPos = readUrl(TokeniseResult, i); if (newPos === null) { TokenError(token, "invalid url command"); } else {i = newPos;}; } else if (seq === "left" || seq === "right") { var nextToken = Tokens[i+1]; char = ""; if (nextToken && nextToken[1] === "Text") { char = text.substring(nextToken[2], nextToken[2] + 1); } else if (nextToken && nextToken[1] === "\\" && nextToken[5] == "control-symbol") { char = nextToken[4]; } else if (nextToken && nextToken[1] === "\\") { char = "unknown"; } if (char === "" || (char !== "unknown" && "(){}[]<>/|\\.".indexOf(char) === -1)) { TokenError(token, "invalid bracket command"); } else { i = i + 1; Environments.push({command:seq, token:token}); }; } else if (seq === "(" || seq === ")" || seq === "[" || seq === "]") { Environments.push({command:seq, token:token}); } else if (seq === "input") { newPos = read1filename(TokeniseResult, i); if (newPos === null) { continue; } else {i = newPos;}; } else if (seq === "hbox" || seq === "text" || seq === "mbox" || seq === "footnote" || seq === "intertext" || seq === "shortintertext" || seq === "textnormal" || seq === "tag" || seq === "reflectbox" || seq === "textrm") { nextGroupMathMode = false; } else if (seq === "rotatebox" || seq === "scalebox") { newPos = readOptionalGeneric(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; nextGroupMathMode = false; } else if (seq === "resizebox") { newPos = readOptionalGeneric(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; nextGroupMathMode = false; } else if (seq === "DeclareMathOperator") { newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (seq === "DeclarePairedDelimiter") { newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; newPos = readDefinition(TokeniseResult, i); if (newPos === null) { /* do nothing */ } else {i = newPos;}; } else if (typeof seq === "string" && seq.match(/^(alpha|beta|gamma|delta|epsilon|varepsilon|zeta|eta|theta|vartheta|iota|kappa|lambda|mu|nu|xi|pi|varpi|rho|varrho|sigma|varsigma|tau|upsilon|phi|varphi|chi|psi|omega|Gamma|Delta|Theta|Lambda|Xi|Pi|Sigma|Upsilon|Phi|Psi|Omega)$/)) { var currentMathMode = Environments.getMathMode() ; // returns null / $(inline) / $$(display) if (currentMathMode === null) { TokenError(token, type + seq + " must be inside math mode", {mathMode:true}); }; } else if (typeof seq === "string" && seq.match(/^(chapter|section|subsection|subsubsection)$/)) { currentMathMode = Environments.getMathMode() ; // returns null / $(inline) / $$(display) if (currentMathMode) { TokenError(token, type + seq + " used inside math mode", {mathMode:true}); Environments.resetMathMode(); }; } else if (typeof seq === "string" && seq.match(/^[a-z]+$/)) { nextGroupMathMode = undefined; }; } else if (type === "$") { var lookAhead = Tokens[i+1]; var nextIsDollar = lookAhead && lookAhead[1] === "$"; currentMathMode = Environments.getMathMode() ; // returns null / $(inline) / $$(display) if (nextIsDollar && (!currentMathMode || currentMathMode.command == "$$")) { Environments.push({command:"$$", token:token}); i = i + 1; } else { Environments.push({command:"$", token:token}); } } else if (type === "^" || type === "_") { currentMathMode = Environments.getMathMode() ; // returns null / $(inline) / $$(display) var insideGroup = Environments.insideGroup(); // true if inside {....} if (currentMathMode === null && !insideGroup) { TokenError(token, type + " must be inside math mode", {mathMode:true}); }; } }; if (seenUserDefinedBeginEquation && seenUserDefinedEndEquation) { ErrorReporter.filterMath = true; }; return Environments; }; var EnvHandler = function (ErrorReporter) { var ErrorTo = ErrorReporter.EnvErrorTo; var ErrorFromTo = ErrorReporter.EnvErrorFromTo; var ErrorFrom = ErrorReporter.EnvErrorFrom; var envs = []; var state = []; var documentClosed = null; var inVerbatim = false; var verbatimRanges = []; this.Environments = envs; this.push = function (newEnv) { this.setEnvProps(newEnv); this.checkAndUpdateState(newEnv); envs.push(newEnv); }; this._endVerbatim = function (thisEnv) { var lastEnv = state.pop(); if (lastEnv && lastEnv.name === thisEnv.name) { inVerbatim = false; verbatimRanges.push({start: lastEnv.token[2], end: thisEnv.token[2]}); } else { if(lastEnv) { state.push(lastEnv); } ; } }; var invalidEnvs = []; this._end = function (thisEnv) { do { var lastEnv = state.pop(); var retry = false; var i; if (closedBy(lastEnv, thisEnv)) { if (thisEnv.command === "end" && thisEnv.name === "document" && !documentClosed) { documentClosed = thisEnv; }; return; } else if (!lastEnv) { if (documentClosed) { ErrorFromTo(documentClosed, thisEnv, "\\end{" + documentClosed.name + "} is followed by unexpected content",{errorAtStart: true, type: "info"}); } else { ErrorTo(thisEnv, "unexpected " + getName(thisEnv)); } } else if (invalidEnvs.length > 0 && (i = indexOfClosingEnvInArray(invalidEnvs, thisEnv) > -1)) { invalidEnvs.splice(i, 1); if (lastEnv) { state.push(lastEnv); } ; return; } else { var status = reportError(lastEnv, thisEnv); if (envPrecedence(lastEnv) < envPrecedence(thisEnv)) { invalidEnvs.push(lastEnv); retry = true; } else { var prevLastEnv = state.pop(); if(prevLastEnv) { if (thisEnv.name === prevLastEnv.name) { return; } else { state.push(prevLastEnv); } } invalidEnvs.push(lastEnv); } } } while (retry === true); }; var CLOSING_DELIMITER = { "{" : "}", "left" : "right", "[" : "]", "(" : ")", "$" : "$", "$$": "$$" }; var closedBy = function (lastEnv, thisEnv) { if (!lastEnv) { return false ; } else if (thisEnv.command === "end") { return lastEnv.command === "begin" && lastEnv.name === thisEnv.name; } else if (thisEnv.command === CLOSING_DELIMITER[lastEnv.command]) { return true; } else { return false; } }; var indexOfClosingEnvInArray = function (envs, thisEnv) { for (var i = 0, n = envs.length; i < n ; i++) { if (closedBy(envs[i], thisEnv)) { return i; } } return -1; }; var envPrecedence = function (env) { var openScore = { "{" : 1, "left" : 2, "$" : 3, "$$" : 4, "begin": 4 }; var closeScore = { "}" : 1, "right" : 2, "$" : 3, "$$" : 5, "end": 4 }; if (env.command) { return openScore[env.command] || closeScore[env.command]; } else { return 0; } }; var getName = function(env) { var description = { "{" : "open group {", "}" : "close group }", "[" : "open display math \\[", "]" : "close display math \\]", "(" : "open inline math \\(", ")" : "close inline math \\)", "$" : "$", "$$" : "$$", "left" : "\\left", "right" : "\\right" }; if (env.command === "begin" || env.command === "end") { return "\\" + env.command + "{" + env.name + "}"; } else if (env.command in description) { return description[env.command]; } else { return env.command; } }; var EXTRA_CLOSE = 1; var UNCLOSED_GROUP = 2; var UNCLOSED_ENV = 3; var reportError = function(lastEnv, thisEnv) { if (!lastEnv) { // unexpected close, nothing was open! if (documentClosed) { ErrorFromTo(documentClosed, thisEnv, "\\end{" + documentClosed.name + "} is followed by unexpected end group }",{errorAtStart: true, type: "info"}); } else { ErrorTo(thisEnv, "unexpected " + getName(thisEnv)); }; return EXTRA_CLOSE; } else if (lastEnv.command === "{" && thisEnv.command === "end") { ErrorFromTo(lastEnv, thisEnv, "unclosed " + getName(lastEnv) + " found at " + getName(thisEnv), {suppressIfEditing:true, errorAtStart: true, type:"warning"}); return UNCLOSED_GROUP; } else { var pLast = envPrecedence(lastEnv); var pThis = envPrecedence(thisEnv); if (pThis > pLast) { ErrorFromTo(lastEnv, thisEnv, "unclosed " + getName(lastEnv) + " found at " + getName(thisEnv), {suppressIfEditing:true, errorAtStart: true}); } else { ErrorFromTo(lastEnv, thisEnv, "unexpected " + getName(thisEnv) + " after " + getName(lastEnv)); } return UNCLOSED_ENV; }; }; this._beginMathMode = function (thisEnv) { var currentMathMode = this.getMathMode(); // undefined, null, $, $$, name of mathmode env if (currentMathMode) { ErrorFrom(thisEnv, thisEnv.name + " used inside existing math mode " + getName(currentMathMode), {suppressIfEditing:true, errorAtStart: true, mathMode:true}); }; thisEnv.mathMode = thisEnv; state.push(thisEnv); }; this._toggleMathMode = function (thisEnv) { var lastEnv = state.pop(); if (closedBy(lastEnv, thisEnv)) { return; } else { if (lastEnv) {state.push(lastEnv);} if (lastEnv && lastEnv.mathMode) { this._end(thisEnv); } else { thisEnv.mathMode = thisEnv; state.push(thisEnv); } }; }; this.getMathMode = function () { var n = state.length; if (n > 0) { return state[n-1].mathMode; } else { return null; } }; this.insideGroup = function () { var n = state.length; if (n > 0) { return (state[n-1].command === "{"); } else { return null; } }; var resetMathMode = function () { var n = state.length; if (n > 0) { var lastMathMode = state[n-1].mathMode; do { var lastEnv = state.pop(); } while (lastEnv && lastEnv !== lastMathMode); } else { return; } }; this.resetMathMode = resetMathMode; var getNewMathMode = function (currentMathMode, thisEnv) { var newMathMode = null; if (thisEnv.command === "{") { if (thisEnv.mathMode !== null) { newMathMode = thisEnv.mathMode; } else { newMathMode = currentMathMode; } } else if (thisEnv.command === "left") { if (currentMathMode === null) { ErrorFrom(thisEnv, "\\left can only be used in math mode", {mathMode: true}); }; newMathMode = currentMathMode; } else if (thisEnv.command === "begin") { var name = thisEnv.name; if (name) { if (name.match(/^(document|figure|center|enumerate|itemize|table|abstract|proof|lemma|theorem|definition|proposition|corollary|remark|notation|thebibliography)$/)) { if (currentMathMode) { ErrorFromTo(currentMathMode, thisEnv, thisEnv.name + " used inside " + getName(currentMathMode), {suppressIfEditing:true, errorAtStart: true, mathMode: true}); resetMathMode(); }; newMathMode = null; } else if (name.match(/^(array|gathered|split|aligned|alignedat)\*?$/)) { if (currentMathMode === null) { ErrorFrom(thisEnv, thisEnv.name + " not inside math mode", {mathMode: true}); }; newMathMode = currentMathMode; } else if (name.match(/^(math|displaymath|equation|eqnarray|multline|align|gather|flalign|alignat)\*?$/)) { if (currentMathMode) { ErrorFromTo(currentMathMode, thisEnv, thisEnv.name + " used inside " + getName(currentMathMode), {suppressIfEditing:true, errorAtStart: true, mathMode: true}); resetMathMode(); }; newMathMode = thisEnv; } else { newMathMode = undefined; // undefined means we don't know if we are in math mode or not } } }; return newMathMode; }; this.checkAndUpdateState = function (thisEnv) { if (inVerbatim) { if (thisEnv.command === "end") { this._endVerbatim(thisEnv); } else { return; // ignore anything in verbatim environments } } else if(thisEnv.command === "begin" || thisEnv.command === "{" || thisEnv.command === "left") { if (thisEnv.verbatim) {inVerbatim = true;}; var currentMathMode = this.getMathMode(); // undefined, null, $, $$, name of mathmode env var newMathMode = getNewMathMode(currentMathMode, thisEnv); thisEnv.mathMode = newMathMode; state.push(thisEnv); } else if (thisEnv.command === "end") { this._end(thisEnv); } else if (thisEnv.command === "(" || thisEnv.command === "[") { this._beginMathMode(thisEnv); } else if (thisEnv.command === ")" || thisEnv.command === "]") { this._end(thisEnv); } else if (thisEnv.command === "}") { this._end(thisEnv); } else if (thisEnv.command === "right") { this._end(thisEnv); } else if (thisEnv.command === "$" || thisEnv.command === "$$") { this._toggleMathMode(thisEnv); } }; this.close = function () { while (state.length > 0) { var thisEnv = state.pop(); if (thisEnv.command === "{") { ErrorFrom(thisEnv, "unclosed group {", {type:"warning"}); } else { ErrorFrom(thisEnv, "unclosed " + getName(thisEnv)); } } var vlen = verbatimRanges.length; var len = ErrorReporter.tokenErrors.length; if (vlen >0 && len > 0) { for (var i = 0; i < len; i++) { var tokenError = ErrorReporter.tokenErrors[i]; var startPos = tokenError.startPos; var endPos = tokenError.endPos; for (var j = 0; j < vlen; j++) { if (startPos > verbatimRanges[j].start && startPos < verbatimRanges[j].end) { tokenError.ignore = true; break; } } } } }; this.setEnvProps = function (env) { var name = env.name ; if (name && name.match(/^(verbatim|boxedverbatim|lstlisting|minted|Verbatim)$/)) { env.verbatim = true; } }; }; var ErrorReporter = function (TokeniseResult) { var text = TokeniseResult.text; var linePosition = TokeniseResult.linePosition; var lineNumber = TokeniseResult.lineNumber; var errors = [], tokenErrors = []; this.errors = errors; this.tokenErrors = tokenErrors; this.filterMath = false; this.getErrors = function () { var returnedErrors = []; for (var i = 0, len = tokenErrors.length; i < len; i++) { if (!tokenErrors[i].ignore) { returnedErrors.push(tokenErrors[i]); } } var allErrors = returnedErrors.concat(errors); var result = []; var mathErrorCount = 0; for (i = 0, len = allErrors.length; i < len; i++) { if (allErrors[i].mathMode) { mathErrorCount++; } if (mathErrorCount > 10) { return []; } } if (this.filterMath && mathErrorCount > 0) { for (i = 0, len = allErrors.length; i < len; i++) { if (!allErrors[i].mathMode) { result.push(allErrors[i]); } } return result; } else { return allErrors; } }; this.TokenError = function (token, message, options) { if(!options) { options = { suppressIfEditing:true } ; }; var line = token[0], type = token[1], start = token[2], end = token[3]; var start_col = start - linePosition[line]; if (!end) { end = start + 1; } ; var end_col = end - linePosition[line]; tokenErrors.push({row: line, column: start_col, start_row:line, start_col: start_col, end_row:line, end_col: end_col, type:"error", text:message, startPos: start, endPos: end, suppressIfEditing:options.suppressIfEditing, mathMode: options.mathMode}); }; this.TokenErrorFromTo = function (fromToken, toToken, message, options) { if(!options) { options = {suppressIfEditing:true } ; }; var fromLine = fromToken[0], fromStart = fromToken[2], fromEnd = fromToken[3]; var toLine = toToken[0], toStart = toToken[2], toEnd = toToken[3]; if (!toEnd) { toEnd = toStart + 1;}; var start_col = fromStart - linePosition[fromLine]; var end_col = toEnd - linePosition[toLine]; tokenErrors.push({row: fromLine, column: start_col, start_row: fromLine, start_col: start_col, end_row: toLine, end_col: end_col, type:"error", text:message, startPos: fromStart, endPos: toEnd, suppressIfEditing:options.suppressIfEditing, mathMode: options.mathMode}); }; this.EnvErrorFromTo = function (fromEnv, toEnv, message, options) { if(!options) { options = {} ; }; var fromToken = fromEnv.token, toToken = toEnv.closeToken || toEnv.token; var fromLine = fromToken[0], fromStart = fromToken[2], fromEnd = fromToken[3]; if (!toToken) {toToken = fromToken;}; var toLine = toToken[0], toStart = toToken[2], toEnd = toToken[3]; if (!toEnd) { toEnd = toStart + 1;}; var start_col = fromStart - linePosition[fromLine]; var end_col = toEnd - linePosition[toLine]; errors.push({row: options.errorAtStart ? fromLine : toLine, column: options.errorAtStart ? start_col: end_col, start_row:fromLine, start_col: start_col, end_row:toLine, end_col: end_col, type: options.type ? options.type : "error", text:message, suppressIfEditing:options.suppressIfEditing, mathMode: options.mathMode}); }; this.EnvErrorTo = function (toEnv, message, options) { if(!options) { options = {} ; }; var token = toEnv.closeToken || toEnv.token; var line = token[0], type = token[1], start = token[2], end = token[3]; if (!end) { end = start + 1; }; var end_col = end - linePosition[line]; var err = {row: line, column: end_col, start_row:0, start_col: 0, end_row: line, end_col: end_col, type: options.type ? options.type : "error", text:message, mathMode: options.mathMode}; errors.push(err); }; this.EnvErrorFrom = function (env, message, options) { if(!options) { options = {} ; }; var token = env.token; var line = token[0], type = token[1], start = token[2], end = token[3]; var start_col = start - linePosition[line]; var end_col = Infinity; errors.push({row: line, column: start_col, start_row:line, start_col: start_col, end_row: lineNumber, end_col: end_col, type: options.type ? options.type : "error", text:message, mathMode: options.mathMode}); }; }; var Parse = function (text) { var TokeniseResult = Tokenise(text); var Reporter = new ErrorReporter(TokeniseResult); var Environments = InterpretTokens(TokeniseResult, Reporter); Environments.close(); return Reporter.getErrors(); }; (function() { var disabled = false; this.onUpdate = function() { if (disabled) { return ; }; var value = this.doc.getValue(); var errors = []; try { if (value) errors = Parse(value); } catch (e) { disabled = true; errors = []; } this.sender.emit("lint", errors); }; }).call(LatexWorker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/worker-html.js
11,605
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; if (!window.console) { window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; } window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject(array[i]); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } if (Object.prototype.toString.call(obj) !== "[object Object]") return obj; copy = {}; for (var key in obj) copy[key] = deepCopy(obj[key]); return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); } } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!(range instanceof Range)) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/html/saxparser",["require","exports","module"], function(require, exports, module) { module.exports = (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({ 1:[function(_dereq_,module,exports){ function isScopeMarker(node) { if (node.namespaceURI === "http://www.w3.org/1999/xhtml") { return node.localName === "applet" || node.localName === "caption" || node.localName === "marquee" || node.localName === "object" || node.localName === "table" || node.localName === "td" || node.localName === "th"; } if (node.namespaceURI === "http://www.w3.org/1998/Math/MathML") { return node.localName === "mi" || node.localName === "mo" || node.localName === "mn" || node.localName === "ms" || node.localName === "mtext" || node.localName === "annotation-xml"; } if (node.namespaceURI === "http://www.w3.org/2000/svg") { return node.localName === "foreignObject" || node.localName === "desc" || node.localName === "title"; } } function isListItemScopeMarker(node) { return isScopeMarker(node) || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'ol') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'ul'); } function isTableScopeMarker(node) { return (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'table') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'html'); } function isTableBodyScopeMarker(node) { return (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'tbody') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'tfoot') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'thead') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'html'); } function isTableRowScopeMarker(node) { return (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'tr') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'html'); } function isButtonScopeMarker(node) { return isScopeMarker(node) || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'button'); } function isSelectScopeMarker(node) { return !(node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'optgroup') && !(node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'option'); } function ElementStack() { this.elements = []; this.rootNode = null; this.headElement = null; this.bodyElement = null; } ElementStack.prototype._inScope = function(localName, isMarker) { for (var i = this.elements.length - 1; i >= 0; i--) { var node = this.elements[i]; if (node.localName === localName) return true; if (isMarker(node)) return false; } }; ElementStack.prototype.push = function(item) { this.elements.push(item); }; ElementStack.prototype.pushHtmlElement = function(item) { this.rootNode = item.node; this.push(item); }; ElementStack.prototype.pushHeadElement = function(item) { this.headElement = item.node; this.push(item); }; ElementStack.prototype.pushBodyElement = function(item) { this.bodyElement = item.node; this.push(item); }; ElementStack.prototype.pop = function() { return this.elements.pop(); }; ElementStack.prototype.remove = function(item) { this.elements.splice(this.elements.indexOf(item), 1); }; ElementStack.prototype.popUntilPopped = function(localName) { var element; do { element = this.pop(); } while (element.localName != localName); }; ElementStack.prototype.popUntilTableScopeMarker = function() { while (!isTableScopeMarker(this.top)) this.pop(); }; ElementStack.prototype.popUntilTableBodyScopeMarker = function() { while (!isTableBodyScopeMarker(this.top)) this.pop(); }; ElementStack.prototype.popUntilTableRowScopeMarker = function() { while (!isTableRowScopeMarker(this.top)) this.pop(); }; ElementStack.prototype.item = function(index) { return this.elements[index]; }; ElementStack.prototype.contains = function(element) { return this.elements.indexOf(element) !== -1; }; ElementStack.prototype.inScope = function(localName) { return this._inScope(localName, isScopeMarker); }; ElementStack.prototype.inListItemScope = function(localName) { return this._inScope(localName, isListItemScopeMarker); }; ElementStack.prototype.inTableScope = function(localName) { return this._inScope(localName, isTableScopeMarker); }; ElementStack.prototype.inButtonScope = function(localName) { return this._inScope(localName, isButtonScopeMarker); }; ElementStack.prototype.inSelectScope = function(localName) { return this._inScope(localName, isSelectScopeMarker); }; ElementStack.prototype.hasNumberedHeaderElementInScope = function() { for (var i = this.elements.length - 1; i >= 0; i--) { var node = this.elements[i]; if (node.isNumberedHeader()) return true; if (isScopeMarker(node)) return false; } }; ElementStack.prototype.furthestBlockForFormattingElement = function(element) { var furthestBlock = null; for (var i = this.elements.length - 1; i >= 0; i--) { var node = this.elements[i]; if (node.node === element) break; if (node.isSpecial()) furthestBlock = node; } return furthestBlock; }; ElementStack.prototype.findIndex = function(localName) { for (var i = this.elements.length - 1; i >= 0; i--) { if (this.elements[i].localName == localName) return i; } return -1; }; ElementStack.prototype.remove_openElements_until = function(callback) { var finished = false; var element; while (!finished) { element = this.elements.pop(); finished = callback(element); } return element; }; Object.defineProperty(ElementStack.prototype, 'top', { get: function() { return this.elements[this.elements.length - 1]; } }); Object.defineProperty(ElementStack.prototype, 'length', { get: function() { return this.elements.length; } }); exports.ElementStack = ElementStack; }, {}], 2:[function(_dereq_,module,exports){ var entities = _dereq_('html5-entities'); var InputStream = _dereq_('./InputStream').InputStream; var namedEntityPrefixes = {}; Object.keys(entities).forEach(function (entityKey) { for (var i = 0; i < entityKey.length; i++) { namedEntityPrefixes[entityKey.substring(0, i + 1)] = true; } }); function isAlphaNumeric(c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } function isHexDigit(c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } function isDecimalDigit(c) { return (c >= '0' && c <= '9'); } var EntityParser = {}; EntityParser.consumeEntity = function(buffer, tokenizer, additionalAllowedCharacter) { var decodedCharacter = ''; var consumedCharacters = ''; var ch = buffer.char(); if (ch === InputStream.EOF) return false; consumedCharacters += ch; if (ch == '\t' || ch == '\n' || ch == '\v' || ch == ' ' || ch == '<' || ch == '&') { buffer.unget(consumedCharacters); return false; } if (additionalAllowedCharacter === ch) { buffer.unget(consumedCharacters); return false; } if (ch == '#') { ch = buffer.shift(1); if (ch === InputStream.EOF) { tokenizer._parseError("expected-numeric-entity-but-got-eof"); buffer.unget(consumedCharacters); return false; } consumedCharacters += ch; var radix = 10; var isDigit = isDecimalDigit; if (ch == 'x' || ch == 'X') { radix = 16; isDigit = isHexDigit; ch = buffer.shift(1); if (ch === InputStream.EOF) { tokenizer._parseError("expected-numeric-entity-but-got-eof"); buffer.unget(consumedCharacters); return false; } consumedCharacters += ch; } if (isDigit(ch)) { var code = ''; while (ch !== InputStream.EOF && isDigit(ch)) { code += ch; ch = buffer.char(); } code = parseInt(code, radix); var replacement = this.replaceEntityNumbers(code); if (replacement) { tokenizer._parseError("invalid-numeric-entity-replaced"); code = replacement; } if (code > 0xFFFF && code <= 0x10FFFF) { code -= 0x10000; var first = ((0xffc00 & code) >> 10) + 0xD800; var second = (0x3ff & code) + 0xDC00; decodedCharacter = String.fromCharCode(first, second); } else decodedCharacter = String.fromCharCode(code); if (ch !== ';') { tokenizer._parseError("numeric-entity-without-semicolon"); buffer.unget(ch); } return decodedCharacter; } buffer.unget(consumedCharacters); tokenizer._parseError("expected-numeric-entity"); return false; } if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { var mostRecentMatch = ''; while (namedEntityPrefixes[consumedCharacters]) { if (entities[consumedCharacters]) { mostRecentMatch = consumedCharacters; } if (ch == ';') break; ch = buffer.char(); if (ch === InputStream.EOF) break; consumedCharacters += ch; } if (!mostRecentMatch) { tokenizer._parseError("expected-named-entity"); buffer.unget(consumedCharacters); return false; } decodedCharacter = entities[mostRecentMatch]; if (ch === ';' || !additionalAllowedCharacter || !(isAlphaNumeric(ch) || ch === '=')) { if (consumedCharacters.length > mostRecentMatch.length) { buffer.unget(consumedCharacters.substring(mostRecentMatch.length)); } if (ch !== ';') { tokenizer._parseError("named-entity-without-semicolon"); } return decodedCharacter; } buffer.unget(consumedCharacters); return false; } }; EntityParser.replaceEntityNumbers = function(c) { switch(c) { case 0x00: return 0xFFFD; // REPLACEMENT CHARACTER case 0x13: return 0x0010; // Carriage return case 0x80: return 0x20AC; // EURO SIGN case 0x81: return 0x0081; // <control> case 0x82: return 0x201A; // SINGLE LOW-9 QUOTATION MARK case 0x83: return 0x0192; // LATIN SMALL LETTER F WITH HOOK case 0x84: return 0x201E; // DOUBLE LOW-9 QUOTATION MARK case 0x85: return 0x2026; // HORIZONTAL ELLIPSIS case 0x86: return 0x2020; // DAGGER case 0x87: return 0x2021; // DOUBLE DAGGER case 0x88: return 0x02C6; // MODIFIER LETTER CIRCUMFLEX ACCENT case 0x89: return 0x2030; // PER MILLE SIGN case 0x8A: return 0x0160; // LATIN CAPITAL LETTER S WITH CARON case 0x8B: return 0x2039; // SINGLE LEFT-POINTING ANGLE QUOTATION MARK case 0x8C: return 0x0152; // LATIN CAPITAL LIGATURE OE case 0x8D: return 0x008D; // <control> case 0x8E: return 0x017D; // LATIN CAPITAL LETTER Z WITH CARON case 0x8F: return 0x008F; // <control> case 0x90: return 0x0090; // <control> case 0x91: return 0x2018; // LEFT SINGLE QUOTATION MARK case 0x92: return 0x2019; // RIGHT SINGLE QUOTATION MARK case 0x93: return 0x201C; // LEFT DOUBLE QUOTATION MARK case 0x94: return 0x201D; // RIGHT DOUBLE QUOTATION MARK case 0x95: return 0x2022; // BULLET case 0x96: return 0x2013; // EN DASH case 0x97: return 0x2014; // EM DASH case 0x98: return 0x02DC; // SMALL TILDE case 0x99: return 0x2122; // TRADE MARK SIGN case 0x9A: return 0x0161; // LATIN SMALL LETTER S WITH CARON case 0x9B: return 0x203A; // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK case 0x9C: return 0x0153; // LATIN SMALL LIGATURE OE case 0x9D: return 0x009D; // <control> case 0x9E: return 0x017E; // LATIN SMALL LETTER Z WITH CARON case 0x9F: return 0x0178; // LATIN CAPITAL LETTER Y WITH DIAERESIS default: if ((c >= 0xD800 && c <= 0xDFFF) || c > 0x10FFFF) { return 0xFFFD; } else if ((c >= 0x0001 && c <= 0x0008) || (c >= 0x000E && c <= 0x001F) || (c >= 0x007F && c <= 0x009F) || (c >= 0xFDD0 && c <= 0xFDEF) || c == 0x000B || c == 0xFFFE || c == 0x1FFFE || c == 0x2FFFFE || c == 0x2FFFF || c == 0x3FFFE || c == 0x3FFFF || c == 0x4FFFE || c == 0x4FFFF || c == 0x5FFFE || c == 0x5FFFF || c == 0x6FFFE || c == 0x6FFFF || c == 0x7FFFE || c == 0x7FFFF || c == 0x8FFFE || c == 0x8FFFF || c == 0x9FFFE || c == 0x9FFFF || c == 0xAFFFE || c == 0xAFFFF || c == 0xBFFFE || c == 0xBFFFF || c == 0xCFFFE || c == 0xCFFFF || c == 0xDFFFE || c == 0xDFFFF || c == 0xEFFFE || c == 0xEFFFF || c == 0xFFFFE || c == 0xFFFFF || c == 0x10FFFE || c == 0x10FFFF) { return c; } } }; exports.EntityParser = EntityParser; }, {"./InputStream":3,"html5-entities":12}], 3:[function(_dereq_,module,exports){ function InputStream() { this.data = ''; this.start = 0; this.committed = 0; this.eof = false; this.lastLocation = {line: 0, column: 0}; } InputStream.EOF = -1; InputStream.DRAIN = -2; InputStream.prototype = { slice: function() { if(this.start >= this.data.length) { if(!this.eof) throw InputStream.DRAIN; return InputStream.EOF; } return this.data.slice(this.start, this.data.length); }, char: function() { if(!this.eof && this.start >= this.data.length - 1) throw InputStream.DRAIN; if(this.start >= this.data.length) { return InputStream.EOF; } var ch = this.data[this.start++]; if (ch === '\r') ch = '\n'; return ch; }, advance: function(amount) { this.start += amount; if(this.start >= this.data.length) { if(!this.eof) throw InputStream.DRAIN; return InputStream.EOF; } else { if(this.committed > this.data.length / 2) { this.lastLocation = this.location(); this.data = this.data.slice(this.committed); this.start = this.start - this.committed; this.committed = 0; } } }, matchWhile: function(re) { if(this.eof && this.start >= this.data.length ) return ''; var r = new RegExp("^"+re+"+"); var m = r.exec(this.slice()); if(m) { if(!this.eof && m[0].length == this.data.length - this.start) throw InputStream.DRAIN; this.advance(m[0].length); return m[0]; } else { return ''; } }, matchUntil: function(re) { var m, s; s = this.slice(); if(s === InputStream.EOF) { return ''; } else if(m = new RegExp(re + (this.eof ? "|$" : "")).exec(s)) { var t = this.data.slice(this.start, this.start + m.index); this.advance(m.index); return t.replace(/\r/g, '\n').replace(/\n{2,}/g, '\n'); } else { throw InputStream.DRAIN; } }, append: function(data) { this.data += data; }, shift: function(n) { if(!this.eof && this.start + n >= this.data.length) throw InputStream.DRAIN; if(this.eof && this.start >= this.data.length) return InputStream.EOF; var d = this.data.slice(this.start, this.start + n).toString(); this.advance(Math.min(n, this.data.length - this.start)); return d; }, peek: function(n) { if(!this.eof && this.start + n >= this.data.length) throw InputStream.DRAIN; if(this.eof && this.start >= this.data.length) return InputStream.EOF; return this.data.slice(this.start, Math.min(this.start + n, this.data.length)).toString(); }, length: function() { return this.data.length - this.start - 1; }, unget: function(d) { if(d === InputStream.EOF) return; this.start -= (d.length); }, undo: function() { this.start = this.committed; }, commit: function() { this.committed = this.start; }, location: function() { var lastLine = this.lastLocation.line; var lastColumn = this.lastLocation.column; var read = this.data.slice(0, this.committed); var newlines = read.match(/\n/g); var line = newlines ? lastLine + newlines.length : lastLine; var column = newlines ? read.length - read.lastIndexOf('\n') - 1 : lastColumn + read.length; return {line: line, column: column}; } }; exports.InputStream = InputStream; }, {}], 4:[function(_dereq_,module,exports){ var SpecialElements = { "http://www.w3.org/1999/xhtml": [ 'address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp' ], "http://www.w3.org/1998/Math/MathML": [ 'mi', 'mo', 'mn', 'ms', 'mtext', 'annotation-xml' ], "http://www.w3.org/2000/svg": [ 'foreignObject', 'desc', 'title' ] }; function StackItem(namespaceURI, localName, attributes, node) { this.localName = localName; this.namespaceURI = namespaceURI; this.attributes = attributes; this.node = node; } StackItem.prototype.isSpecial = function() { return this.namespaceURI in SpecialElements && SpecialElements[this.namespaceURI].indexOf(this.localName) > -1; }; StackItem.prototype.isFosterParenting = function() { if (this.namespaceURI === "http://www.w3.org/1999/xhtml") { return this.localName === 'table' || this.localName === 'tbody' || this.localName === 'tfoot' || this.localName === 'thead' || this.localName === 'tr'; } return false; }; StackItem.prototype.isNumberedHeader = function() { if (this.namespaceURI === "http://www.w3.org/1999/xhtml") { return this.localName === 'h1' || this.localName === 'h2' || this.localName === 'h3' || this.localName === 'h4' || this.localName === 'h5' || this.localName === 'h6'; } return false; }; StackItem.prototype.isForeign = function() { return this.namespaceURI != "http://www.w3.org/1999/xhtml"; }; function getAttribute(item, name) { for (var i = 0; i < item.attributes.length; i++) { if (item.attributes[i].nodeName == name) return item.attributes[i].nodeValue; } return null; } StackItem.prototype.isHtmlIntegrationPoint = function() { if (this.namespaceURI === "http://www.w3.org/1998/Math/MathML") { if (this.localName !== "annotation-xml") return false; var encoding = getAttribute(this, 'encoding'); if (!encoding) return false; encoding = encoding.toLowerCase(); return encoding === "text/html" || encoding === "application/xhtml+xml"; } if (this.namespaceURI === "http://www.w3.org/2000/svg") { return this.localName === "foreignObject" || this.localName === "desc" || this.localName === "title"; } return false; }; StackItem.prototype.isMathMLTextIntegrationPoint = function() { if (this.namespaceURI === "http://www.w3.org/1998/Math/MathML") { return this.localName === "mi" || this.localName === "mo" || this.localName === "mn" || this.localName === "ms" || this.localName === "mtext"; } return false; }; exports.StackItem = StackItem; }, {}], 5:[function(_dereq_,module,exports){ var InputStream = _dereq_('./InputStream').InputStream; var EntityParser = _dereq_('./EntityParser').EntityParser; function isWhitespace(c){ return c === " " || c === "\n" || c === "\t" || c === "\r" || c === "\f"; } function isAlpha(c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } function Tokenizer(tokenHandler) { this._tokenHandler = tokenHandler; this._state = Tokenizer.DATA; this._inputStream = new InputStream(); this._currentToken = null; this._temporaryBuffer = ''; this._additionalAllowedCharacter = ''; } Tokenizer.prototype._parseError = function(code, args) { this._tokenHandler.parseError(code, args); }; Tokenizer.prototype._emitToken = function(token) { if (token.type === 'StartTag') { for (var i = 1; i < token.data.length; i++) { if (!token.data[i].nodeName) token.data.splice(i--, 1); } } else if (token.type === 'EndTag') { if (token.selfClosing) { this._parseError('self-closing-flag-on-end-tag'); } if (token.data.length !== 0) { this._parseError('attributes-in-end-tag'); } } this._tokenHandler.processToken(token); if (token.type === 'StartTag' && token.selfClosing && !this._tokenHandler.isSelfClosingFlagAcknowledged()) { this._parseError('non-void-element-with-trailing-solidus', {name: token.name}); } }; Tokenizer.prototype._emitCurrentToken = function() { this._state = Tokenizer.DATA; this._emitToken(this._currentToken); }; Tokenizer.prototype._currentAttribute = function() { return this._currentToken.data[this._currentToken.data.length - 1]; }; Tokenizer.prototype.setState = function(state) { this._state = state; }; Tokenizer.prototype.tokenize = function(source) { Tokenizer.DATA = data_state; Tokenizer.RCDATA = rcdata_state; Tokenizer.RAWTEXT = rawtext_state; Tokenizer.SCRIPT_DATA = script_data_state; Tokenizer.PLAINTEXT = plaintext_state; this._state = Tokenizer.DATA; this._inputStream.append(source); this._tokenHandler.startTokenization(this); this._inputStream.eof = true; var tokenizer = this; while (this._state.call(this, this._inputStream)); function data_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === '&') { tokenizer.setState(character_reference_in_data_state); } else if (data === '<') { tokenizer.setState(tag_open_state); } else if (data === '\u0000') { tokenizer._emitToken({type: 'Characters', data: data}); buffer.commit(); } else { var chars = buffer.matchUntil("&|<|\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); buffer.commit(); } return true; } function character_reference_in_data_state(buffer) { var character = EntityParser.consumeEntity(buffer, tokenizer); tokenizer.setState(data_state); tokenizer._emitToken({type: 'Characters', data: character || '&'}); return true; } function rcdata_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === '&') { tokenizer.setState(character_reference_in_rcdata_state); } else if (data === '<') { tokenizer.setState(rcdata_less_than_sign_state); } else if (data === "\u0000") { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil("&|<|\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); buffer.commit(); } return true; } function character_reference_in_rcdata_state(buffer) { var character = EntityParser.consumeEntity(buffer, tokenizer); tokenizer.setState(rcdata_state); tokenizer._emitToken({type: 'Characters', data: character || '&'}); return true; } function rawtext_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === '<') { tokenizer.setState(rawtext_less_than_sign_state); } else if (data === "\u0000") { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil("<|\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); } return true; } function plaintext_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === "\u0000") { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil("\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); } return true; } function script_data_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === '<') { tokenizer.setState(script_data_less_than_sign_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil("<|\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); } return true; } function rcdata_less_than_sign_state(buffer) { var data = buffer.char(); if (data === "/") { this._temporaryBuffer = ''; tokenizer.setState(rcdata_end_tag_open_state); } else { tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(rcdata_state); } return true; } function rcdata_end_tag_open_state(buffer) { var data = buffer.char(); if (isAlpha(data)) { this._temporaryBuffer += data; tokenizer.setState(rcdata_end_tag_name_state); } else { tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(rcdata_state); } return true; } function rcdata_end_tag_name_state(buffer) { var appropriate = tokenizer._currentToken && (tokenizer._currentToken.name === this._temporaryBuffer.toLowerCase()); var data = buffer.char(); if (isWhitespace(data) && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer.setState(before_attribute_name_state); } else if (data === '/' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer.setState(self_closing_tag_state); } else if (data === '>' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else if (isAlpha(data)) { this._temporaryBuffer += data; buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: '</' + this._temporaryBuffer}); buffer.unget(data); tokenizer.setState(rcdata_state); } return true; } function rawtext_less_than_sign_state(buffer) { var data = buffer.char(); if (data === "/") { this._temporaryBuffer = ''; tokenizer.setState(rawtext_end_tag_open_state); } else { tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(rawtext_state); } return true; } function rawtext_end_tag_open_state(buffer) { var data = buffer.char(); if (isAlpha(data)) { this._temporaryBuffer += data; tokenizer.setState(rawtext_end_tag_name_state); } else { tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(rawtext_state); } return true; } function rawtext_end_tag_name_state(buffer) { var appropriate = tokenizer._currentToken && (tokenizer._currentToken.name === this._temporaryBuffer.toLowerCase()); var data = buffer.char(); if (isWhitespace(data) && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer.setState(before_attribute_name_state); } else if (data === '/' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer.setState(self_closing_tag_state); } else if (data === '>' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else if (isAlpha(data)) { this._temporaryBuffer += data; buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: '</' + this._temporaryBuffer}); buffer.unget(data); tokenizer.setState(rawtext_state); } return true; } function script_data_less_than_sign_state(buffer) { var data = buffer.char(); if (data === "/") { this._temporaryBuffer = ''; tokenizer.setState(script_data_end_tag_open_state); } else if (data === '!') { tokenizer._emitToken({type: 'Characters', data: '<!'}); tokenizer.setState(script_data_escape_start_state); } else { tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_end_tag_open_state(buffer) { var data = buffer.char(); if (isAlpha(data)) { this._temporaryBuffer += data; tokenizer.setState(script_data_end_tag_name_state); } else { tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_end_tag_name_state(buffer) { var appropriate = tokenizer._currentToken && (tokenizer._currentToken.name === this._temporaryBuffer.toLowerCase()); var data = buffer.char(); if (isWhitespace(data) && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(before_attribute_name_state); } else if (data === '/' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(self_closing_tag_state); } else if (data === '>' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer._emitCurrentToken(); } else if (isAlpha(data)) { this._temporaryBuffer += data; buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: '</' + this._temporaryBuffer}); buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_escape_start_state(buffer) { var data = buffer.char(); if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_escape_start_dash_state); } else { buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_escape_start_dash_state(buffer) { var data = buffer.char(); if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_escaped_dash_dash_state); } else { buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_escaped_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_escaped_dash_state); } else if (data === '<') { tokenizer.setState(script_data_escaped_less_then_sign_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil('<|-|\u0000'); tokenizer._emitToken({type: 'Characters', data: data + chars}); } return true; } function script_data_escaped_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_escaped_dash_dash_state); } else if (data === '<') { tokenizer.setState(script_data_escaped_less_then_sign_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); tokenizer.setState(script_data_escaped_state); } else { tokenizer._emitToken({type: 'Characters', data: data}); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_escaped_dash_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-script'); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '<') { tokenizer.setState(script_data_escaped_less_then_sign_state); } else if (data === '>') { tokenizer._emitToken({type: 'Characters', data: '>'}); tokenizer.setState(script_data_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); tokenizer.setState(script_data_escaped_state); } else { tokenizer._emitToken({type: 'Characters', data: data}); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_escaped_less_then_sign_state(buffer) { var data = buffer.char(); if (data === '/') { this._temporaryBuffer = ''; tokenizer.setState(script_data_escaped_end_tag_open_state); } else if (isAlpha(data)) { tokenizer._emitToken({type: 'Characters', data: '<' + data}); this._temporaryBuffer = data; tokenizer.setState(script_data_double_escape_start_state); } else { tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_escaped_end_tag_open_state(buffer) { var data = buffer.char(); if (isAlpha(data)) { this._temporaryBuffer = data; tokenizer.setState(script_data_escaped_end_tag_name_state); } else { tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_escaped_end_tag_name_state(buffer) { var appropriate = tokenizer._currentToken && (tokenizer._currentToken.name === this._temporaryBuffer.toLowerCase()); var data = buffer.char(); if (isWhitespace(data) && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(before_attribute_name_state); } else if (data === '/' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(self_closing_tag_state); } else if (data === '>' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isAlpha(data)) { this._temporaryBuffer += data; buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: '</' + this._temporaryBuffer}); buffer.unget(data); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_double_escape_start_state(buffer) { var data = buffer.char(); if (isWhitespace(data) || data === '/' || data === '>') { tokenizer._emitToken({type: 'Characters', data: data}); if (this._temporaryBuffer.toLowerCase() === 'script') tokenizer.setState(script_data_double_escaped_state); else tokenizer.setState(script_data_escaped_state); } else if (isAlpha(data)) { tokenizer._emitToken({type: 'Characters', data: data}); this._temporaryBuffer += data; buffer.commit(); } else { buffer.unget(data); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_double_escaped_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-script'); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_double_escaped_dash_state); } else if (data === '<') { tokenizer._emitToken({type: 'Characters', data: '<'}); tokenizer.setState(script_data_double_escaped_less_than_sign_state); } else if (data === '\u0000') { tokenizer._parseError('invalid-codepoint'); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: data}); buffer.commit(); } return true; } function script_data_double_escaped_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-script'); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_double_escaped_dash_dash_state); } else if (data === '<') { tokenizer._emitToken({type: 'Characters', data: '<'}); tokenizer.setState(script_data_double_escaped_less_than_sign_state); } else if (data === '\u0000') { tokenizer._parseError('invalid-codepoint'); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); tokenizer.setState(script_data_double_escaped_state); } else { tokenizer._emitToken({type: 'Characters', data: data}); tokenizer.setState(script_data_double_escaped_state); } return true; } function script_data_double_escaped_dash_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-script'); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); buffer.commit(); } else if (data === '<') { tokenizer._emitToken({type: 'Characters', data: '<'}); tokenizer.setState(script_data_double_escaped_less_than_sign_state); } else if (data === '>') { tokenizer._emitToken({type: 'Characters', data: '>'}); tokenizer.setState(script_data_state); } else if (data === '\u0000') { tokenizer._parseError('invalid-codepoint'); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); tokenizer.setState(script_data_double_escaped_state); } else { tokenizer._emitToken({type: 'Characters', data: data}); tokenizer.setState(script_data_double_escaped_state); } return true; } function script_data_double_escaped_less_than_sign_state(buffer) { var data = buffer.char(); if (data === '/') { tokenizer._emitToken({type: 'Characters', data: '/'}); this._temporaryBuffer = ''; tokenizer.setState(script_data_double_escape_end_state); } else { buffer.unget(data); tokenizer.setState(script_data_double_escaped_state); } return true; } function script_data_double_escape_end_state(buffer) { var data = buffer.char(); if (isWhitespace(data) || data === '/' || data === '>') { tokenizer._emitToken({type: 'Characters', data: data}); if (this._temporaryBuffer.toLowerCase() === 'script') tokenizer.setState(script_data_escaped_state); else tokenizer.setState(script_data_double_escaped_state); } else if (isAlpha(data)) { tokenizer._emitToken({type: 'Characters', data: data}); this._temporaryBuffer += data; buffer.commit(); } else { buffer.unget(data); tokenizer.setState(script_data_double_escaped_state); } return true; } function tag_open_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("bare-less-than-sign-at-eof"); tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(data_state); } else if (isAlpha(data)) { tokenizer._currentToken = {type: 'StartTag', name: data.toLowerCase(), data: []}; tokenizer.setState(tag_name_state); } else if (data === '!') { tokenizer.setState(markup_declaration_open_state); } else if (data === '/') { tokenizer.setState(close_tag_open_state); } else if (data === '>') { tokenizer._parseError("expected-tag-name-but-got-right-bracket"); tokenizer._emitToken({type: 'Characters', data: "<>"}); tokenizer.setState(data_state); } else if (data === '?') { tokenizer._parseError("expected-tag-name-but-got-question-mark"); buffer.unget(data); tokenizer.setState(bogus_comment_state); } else { tokenizer._parseError("expected-tag-name"); tokenizer._emitToken({type: 'Characters', data: "<"}); buffer.unget(data); tokenizer.setState(data_state); } return true; } function close_tag_open_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-closing-tag-but-got-eof"); tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(data_state); } else if (isAlpha(data)) { tokenizer._currentToken = {type: 'EndTag', name: data.toLowerCase(), data: []}; tokenizer.setState(tag_name_state); } else if (data === '>') { tokenizer._parseError("expected-closing-tag-but-got-right-bracket"); tokenizer.setState(data_state); } else { tokenizer._parseError("expected-closing-tag-but-got-char", {data: data}); // param 1 is datavars: buffer.unget(data); tokenizer.setState(bogus_comment_state); } return true; } function tag_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-tag-name'); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(before_attribute_name_state); } else if (isAlpha(data)) { tokenizer._currentToken.name += data.toLowerCase(); } else if (data === '>') { tokenizer._emitCurrentToken(); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.name += "\uFFFD"; } else { tokenizer._currentToken.name += data; } buffer.commit(); return true; } function before_attribute_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-attribute-name-but-got-eof"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { return true; } else if (isAlpha(data)) { tokenizer._currentToken.data.push({nodeName: data.toLowerCase(), nodeValue: ""}); tokenizer.setState(attribute_name_state); } else if (data === '>') { tokenizer._emitCurrentToken(); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else if (data === "'" || data === '"' || data === '=' || data === '<') { tokenizer._parseError("invalid-character-in-attribute-name"); tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data.push({nodeName: "\uFFFD", nodeValue: ""}); } else { tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } return true; } function attribute_name_state(buffer) { var data = buffer.char(); var leavingThisState = true; var shouldEmit = false; if (data === InputStream.EOF) { tokenizer._parseError("eof-in-attribute-name"); buffer.unget(data); tokenizer.setState(data_state); shouldEmit = true; } else if (data === '=') { tokenizer.setState(before_attribute_value_state); } else if (isAlpha(data)) { tokenizer._currentAttribute().nodeName += data.toLowerCase(); leavingThisState = false; } else if (data === '>') { shouldEmit = true; } else if (isWhitespace(data)) { tokenizer.setState(after_attribute_name_state); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else if (data === "'" || data === '"') { tokenizer._parseError("invalid-character-in-attribute-name"); tokenizer._currentAttribute().nodeName += data; leavingThisState = false; } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeName += "\uFFFD"; } else { tokenizer._currentAttribute().nodeName += data; leavingThisState = false; } if (leavingThisState) { var attributes = tokenizer._currentToken.data; var currentAttribute = attributes[attributes.length - 1]; for (var i = attributes.length - 2; i >= 0; i--) { if (currentAttribute.nodeName === attributes[i].nodeName) { tokenizer._parseError("duplicate-attribute", {name: currentAttribute.nodeName}); currentAttribute.nodeName = null; break; } } if (shouldEmit) tokenizer._emitCurrentToken(); } else { buffer.commit(); } return true; } function after_attribute_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-end-of-tag-but-got-eof"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { return true; } else if (data === '=') { tokenizer.setState(before_attribute_value_state); } else if (data === '>') { tokenizer._emitCurrentToken(); } else if (isAlpha(data)) { tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else if (data === "'" || data === '"' || data === '<') { tokenizer._parseError("invalid-character-after-attribute-name"); tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data.push({nodeName: "\uFFFD", nodeValue: ""}); } else { tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } return true; } function before_attribute_value_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-attribute-value-but-got-eof"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { return true; } else if (data === '"') { tokenizer.setState(attribute_value_double_quoted_state); } else if (data === '&') { tokenizer.setState(attribute_value_unquoted_state); buffer.unget(data); } else if (data === "'") { tokenizer.setState(attribute_value_single_quoted_state); } else if (data === '>') { tokenizer._parseError("expected-attribute-value-but-got-right-bracket"); tokenizer._emitCurrentToken(); } else if (data === '=' || data === '<' || data === '`') { tokenizer._parseError("unexpected-character-in-unquoted-attribute-value"); tokenizer._currentAttribute().nodeValue += data; tokenizer.setState(attribute_value_unquoted_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeValue += "\uFFFD"; } else { tokenizer._currentAttribute().nodeValue += data; tokenizer.setState(attribute_value_unquoted_state); } return true; } function attribute_value_double_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-attribute-value-double-quote"); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '"') { tokenizer.setState(after_attribute_value_state); } else if (data === '&') { this._additionalAllowedCharacter = '"'; tokenizer.setState(character_reference_in_attribute_value_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeValue += "\uFFFD"; } else { var s = buffer.matchUntil('[\0"&]'); data = data + s; tokenizer._currentAttribute().nodeValue += data; } return true; } function attribute_value_single_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-attribute-value-single-quote"); buffer.unget(data); tokenizer.setState(data_state); } else if (data === "'") { tokenizer.setState(after_attribute_value_state); } else if (data === '&') { this._additionalAllowedCharacter = "'"; tokenizer.setState(character_reference_in_attribute_value_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeValue += "\uFFFD"; } else { tokenizer._currentAttribute().nodeValue += data + buffer.matchUntil("\u0000|['&]"); } return true; } function attribute_value_unquoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-after-attribute-value"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(before_attribute_name_state); } else if (data === '&') { this._additionalAllowedCharacter = ">"; tokenizer.setState(character_reference_in_attribute_value_state); } else if (data === '>') { tokenizer._emitCurrentToken(); } else if (data === '"' || data === "'" || data === '=' || data === '`' || data === '<') { tokenizer._parseError("unexpected-character-in-unquoted-attribute-value"); tokenizer._currentAttribute().nodeValue += data; buffer.commit(); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeValue += "\uFFFD"; } else { var o = buffer.matchUntil("\u0000|["+ "\t\n\v\f\x20\r" + "&<>\"'=`" +"]"); if (o === InputStream.EOF) { tokenizer._parseError("eof-in-attribute-value-no-quotes"); tokenizer._emitCurrentToken(); } buffer.commit(); tokenizer._currentAttribute().nodeValue += data + o; } return true; } function character_reference_in_attribute_value_state(buffer) { var character = EntityParser.consumeEntity(buffer, tokenizer, this._additionalAllowedCharacter); this._currentAttribute().nodeValue += character || '&'; if (this._additionalAllowedCharacter === '"') tokenizer.setState(attribute_value_double_quoted_state); else if (this._additionalAllowedCharacter === '\'') tokenizer.setState(attribute_value_single_quoted_state); else if (this._additionalAllowedCharacter === '>') tokenizer.setState(attribute_value_unquoted_state); return true; } function after_attribute_value_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-after-attribute-value"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(before_attribute_name_state); } else if (data === '>') { tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else { tokenizer._parseError("unexpected-character-after-attribute-value"); buffer.unget(data); tokenizer.setState(before_attribute_name_state); } return true; } function self_closing_tag_state(buffer) { var c = buffer.char(); if (c === InputStream.EOF) { tokenizer._parseError("unexpected-eof-after-solidus-in-tag"); buffer.unget(c); tokenizer.setState(data_state); } else if (c === '>') { tokenizer._currentToken.selfClosing = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._parseError("unexpected-character-after-solidus-in-tag"); buffer.unget(c); tokenizer.setState(before_attribute_name_state); } return true; } function bogus_comment_state(buffer) { var data = buffer.matchUntil('>'); data = data.replace(/\u0000/g, "\uFFFD"); buffer.char(); tokenizer._emitToken({type: 'Comment', data: data}); tokenizer.setState(data_state); return true; } function markup_declaration_open_state(buffer) { var chars = buffer.shift(2); if (chars === '--') { tokenizer._currentToken = {type: 'Comment', data: ''}; tokenizer.setState(comment_start_state); } else { var newchars = buffer.shift(5); if (newchars === InputStream.EOF || chars === InputStream.EOF) { tokenizer._parseError("expected-dashes-or-doctype"); tokenizer.setState(bogus_comment_state); buffer.unget(chars); return true; } chars += newchars; if (chars.toUpperCase() === 'DOCTYPE') { tokenizer._currentToken = {type: 'Doctype', name: '', publicId: null, systemId: null, forceQuirks: false}; tokenizer.setState(doctype_state); } else if (tokenizer._tokenHandler.isCdataSectionAllowed() && chars === '[CDATA[') { tokenizer.setState(cdata_section_state); } else { tokenizer._parseError("expected-dashes-or-doctype"); buffer.unget(chars); tokenizer.setState(bogus_comment_state); } } return true; } function cdata_section_state(buffer) { var data = buffer.matchUntil(']]>'); buffer.shift(3); if (data) { tokenizer._emitToken({type: 'Characters', data: data}); } tokenizer.setState(data_state); return true; } function comment_start_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer.setState(comment_start_dash_state); } else if (data === '>') { tokenizer._parseError("incorrect-comment"); tokenizer._emitToken(tokenizer._currentToken); tokenizer.setState(data_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "\uFFFD"; } else { tokenizer._currentToken.data += data; tokenizer.setState(comment_state); } return true; } function comment_start_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer.setState(comment_end_state); } else if (data === '>') { tokenizer._parseError("incorrect-comment"); tokenizer._emitToken(tokenizer._currentToken); tokenizer.setState(data_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "\uFFFD"; } else { tokenizer._currentToken.data += '-' + data; tokenizer.setState(comment_state); } return true; } function comment_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer.setState(comment_end_dash_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "\uFFFD"; } else { tokenizer._currentToken.data += data; buffer.commit(); } return true; } function comment_end_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment-end-dash"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer.setState(comment_end_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "-\uFFFD"; tokenizer.setState(comment_state); } else { tokenizer._currentToken.data += '-' + data + buffer.matchUntil('\u0000|-'); buffer.char(); } return true; } function comment_end_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment-double-dash"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '>') { tokenizer._emitToken(tokenizer._currentToken); tokenizer.setState(data_state); } else if (data === '!') { tokenizer._parseError("unexpected-bang-after-double-dash-in-comment"); tokenizer.setState(comment_end_bang_state); } else if (data === '-') { tokenizer._parseError("unexpected-dash-after-double-dash-in-comment"); tokenizer._currentToken.data += data; } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "--\uFFFD"; tokenizer.setState(comment_state); } else { tokenizer._parseError("unexpected-char-in-comment"); tokenizer._currentToken.data += '--' + data; tokenizer.setState(comment_state); } return true; } function comment_end_bang_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment-end-bang-state"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '>') { tokenizer._emitToken(tokenizer._currentToken); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._currentToken.data += '--!'; tokenizer.setState(comment_end_dash_state); } else { tokenizer._currentToken.data += '--!' + data; tokenizer.setState(comment_state); } return true; } function doctype_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-doctype-name-but-got-eof"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { tokenizer.setState(before_doctype_name_state); } else { tokenizer._parseError("need-space-after-doctype"); buffer.unget(data); tokenizer.setState(before_doctype_name_state); } return true; } function before_doctype_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-doctype-name-but-got-eof"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { } else if (data === '>') { tokenizer._parseError("expected-doctype-name-but-got-right-bracket"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { if (isAlpha(data)) data = data.toLowerCase(); tokenizer._currentToken.name = data; tokenizer.setState(doctype_name_state); } return true; } function doctype_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer._parseError("eof-in-doctype-name"); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { tokenizer.setState(after_doctype_name_state); } else if (data === '>') { tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { if (isAlpha(data)) data = data.toLowerCase(); tokenizer._currentToken.name += data; buffer.commit(); } return true; } function after_doctype_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer._parseError("eof-in-doctype"); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { } else if (data === '>') { tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { if (['p', 'P'].indexOf(data) > -1) { var expected = [['u', 'U'], ['b', 'B'], ['l', 'L'], ['i', 'I'], ['c', 'C']]; var matched = expected.every(function(expected){ data = buffer.char(); return expected.indexOf(data) > -1; }); if (matched) { tokenizer.setState(after_doctype_public_keyword_state); return true; } } else if (['s', 'S'].indexOf(data) > -1) { var expected = [['y', 'Y'], ['s', 'S'], ['t', 'T'], ['e', 'E'], ['m', 'M']]; var matched = expected.every(function(expected){ data = buffer.char(); return expected.indexOf(data) > -1; }); if (matched) { tokenizer.setState(after_doctype_system_keyword_state); return true; } } buffer.unget(data); tokenizer._currentToken.forceQuirks = true; if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._parseError("expected-space-or-right-bracket-in-doctype", {data: data}); tokenizer.setState(bogus_doctype_state); } } return true; } function after_doctype_public_keyword_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { tokenizer.setState(before_doctype_public_identifier_state); } else if (data === "'" || data === '"') { tokenizer._parseError("unexpected-char-in-doctype"); buffer.unget(data); tokenizer.setState(before_doctype_public_identifier_state); } else { buffer.unget(data); tokenizer.setState(before_doctype_public_identifier_state); } return true; } function before_doctype_public_identifier_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { } else if (data === '"') { tokenizer._currentToken.publicId = ''; tokenizer.setState(doctype_public_identifier_double_quoted_state); } else if (data === "'") { tokenizer._currentToken.publicId = ''; tokenizer.setState(doctype_public_identifier_single_quoted_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(bogus_doctype_state); } return true; } function doctype_public_identifier_double_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (data === '"') { tokenizer.setState(after_doctype_public_identifier_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._currentToken.publicId += data; } return true; } function doctype_public_identifier_single_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (data === "'") { tokenizer.setState(after_doctype_public_identifier_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._currentToken.publicId += data; } return true; } function after_doctype_public_identifier_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(between_doctype_public_and_system_identifiers_state); } else if (data === '>') { tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (data === '"') { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_double_quoted_state); } else if (data === "'") { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_single_quoted_state); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(bogus_doctype_state); } return true; } function between_doctype_public_and_system_identifiers_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { } else if (data === '>') { tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else if (data === '"') { tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_double_quoted_state); } else if (data === "'") { tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_single_quoted_state); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(bogus_doctype_state); } return true; } function after_doctype_system_keyword_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(before_doctype_system_identifier_state); } else if (data === "'" || data === '"') { tokenizer._parseError("unexpected-char-in-doctype"); buffer.unget(data); tokenizer.setState(before_doctype_system_identifier_state); } else { buffer.unget(data); tokenizer.setState(before_doctype_system_identifier_state); } return true; } function before_doctype_system_identifier_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { } else if (data === '"') { tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_double_quoted_state); } else if (data === "'") { tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_single_quoted_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(bogus_doctype_state); } return true; } function doctype_system_identifier_double_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '"') { tokenizer.setState(after_doctype_system_identifier_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else { tokenizer._currentToken.systemId += data; } return true; } function doctype_system_identifier_single_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (data === "'") { tokenizer.setState(after_doctype_system_identifier_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else { tokenizer._currentToken.systemId += data; } return true; } function after_doctype_system_identifier_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { } else if (data === '>') { tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer.setState(bogus_doctype_state); } return true; } function bogus_doctype_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { buffer.unget(data); tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else if (data === '>') { tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } return true; } }; Object.defineProperty(Tokenizer.prototype, 'lineNumber', { get: function() { return this._inputStream.location().line; } }); Object.defineProperty(Tokenizer.prototype, 'columnNumber', { get: function() { return this._inputStream.location().column; } }); exports.Tokenizer = Tokenizer; }, {"./EntityParser":2,"./InputStream":3}], 6:[function(_dereq_,module,exports){ var assert = _dereq_('assert'); var messages = _dereq_('./messages.json'); var constants = _dereq_('./constants'); var EventEmitter = _dereq_('events').EventEmitter; var Tokenizer = _dereq_('./Tokenizer').Tokenizer; var ElementStack = _dereq_('./ElementStack').ElementStack; var StackItem = _dereq_('./StackItem').StackItem; var Marker = {}; function isWhitespace(ch) { return ch === " " || ch === "\n" || ch === "\t" || ch === "\r" || ch === "\f"; } function isWhitespaceOrReplacementCharacter(ch) { return isWhitespace(ch) || ch === '\uFFFD'; } function isAllWhitespace(characters) { for (var i = 0; i < characters.length; i++) { var ch = characters[i]; if (!isWhitespace(ch)) return false; } return true; } function isAllWhitespaceOrReplacementCharacters(characters) { for (var i = 0; i < characters.length; i++) { var ch = characters[i]; if (!isWhitespaceOrReplacementCharacter(ch)) return false; } return true; } function getAttribute(node, name) { for (var i = 0; i < node.attributes.length; i++) { var attribute = node.attributes[i]; if (attribute.nodeName === name) { return attribute; } } return null; } function CharacterBuffer(characters) { this.characters = characters; this.current = 0; this.end = this.characters.length; } CharacterBuffer.prototype.skipAtMostOneLeadingNewline = function() { if (this.characters[this.current] === '\n') this.current++; }; CharacterBuffer.prototype.skipLeadingWhitespace = function() { while (isWhitespace(this.characters[this.current])) { if (++this.current == this.end) return; } }; CharacterBuffer.prototype.skipLeadingNonWhitespace = function() { while (!isWhitespace(this.characters[this.current])) { if (++this.current == this.end) return; } }; CharacterBuffer.prototype.takeRemaining = function() { return this.characters.substring(this.current); }; CharacterBuffer.prototype.takeLeadingWhitespace = function() { var start = this.current; this.skipLeadingWhitespace(); if (start === this.current) return ""; return this.characters.substring(start, this.current - start); }; Object.defineProperty(CharacterBuffer.prototype, 'length', { get: function(){ return this.end - this.current; } }); function TreeBuilder() { this.tokenizer = null; this.errorHandler = null; this.scriptingEnabled = false; this.document = null; this.head = null; this.form = null; this.openElements = new ElementStack(); this.activeFormattingElements = []; this.insertionMode = null; this.insertionModeName = ""; this.originalInsertionMode = ""; this.inQuirksMode = false; // TODO quirks mode this.compatMode = "no quirks"; this.framesetOk = true; this.redirectAttachToFosterParent = false; this.selfClosingFlagAcknowledged = false; this.context = ""; this.pendingTableCharacters = []; this.shouldSkipLeadingNewline = false; var tree = this; var modes = this.insertionModes = {}; modes.base = { end_tag_handlers: {"-default": 'endTagOther'}, start_tag_handlers: {"-default": 'startTagOther'}, processEOF: function() { tree.generateImpliedEndTags(); if (tree.openElements.length > 2) { tree.parseError('expected-closing-tag-but-got-eof'); } else if (tree.openElements.length == 2 && tree.openElements.item(1).localName != 'body') { tree.parseError('expected-closing-tag-but-got-eof'); } else if (tree.context && tree.openElements.length > 1) { } }, processComment: function(data) { tree.insertComment(data, tree.currentStackItem().node); }, processDoctype: function(name, publicId, systemId, forceQuirks) { tree.parseError('unexpected-doctype'); }, processStartTag: function(name, attributes, selfClosing) { if (this[this.start_tag_handlers[name]]) { this[this.start_tag_handlers[name]](name, attributes, selfClosing); } else if (this[this.start_tag_handlers["-default"]]) { this[this.start_tag_handlers["-default"]](name, attributes, selfClosing); } else { throw(new Error("No handler found for "+name)); } }, processEndTag: function(name) { if (this[this.end_tag_handlers[name]]) { this[this.end_tag_handlers[name]](name); } else if (this[this.end_tag_handlers["-default"]]) { this[this.end_tag_handlers["-default"]](name); } else { throw(new Error("No handler found for "+name)); } }, startTagHtml: function(name, attributes) { modes.inBody.startTagHtml(name, attributes); } }; modes.initial = Object.create(modes.base); modes.initial.processEOF = function() { tree.parseError("expected-doctype-but-got-eof"); this.anythingElse(); tree.insertionMode.processEOF(); }; modes.initial.processComment = function(data) { tree.insertComment(data, tree.document); }; modes.initial.processDoctype = function(name, publicId, systemId, forceQuirks) { tree.insertDoctype(name || '', publicId || '', systemId || ''); if (forceQuirks || name != 'html' || (publicId != null && ([ "+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html strict//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//ietf//dtd html//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//", "html" ].some(publicIdStartsWith) || [ "-//w3o//dtd w3 html strict 3.0//en//", "-/w3c/dtd html 4.0 transitional/en", "html" ].indexOf(publicId.toLowerCase()) > -1 || (systemId == null && [ "-//w3c//dtd html 4.01 transitional//", "-//w3c//dtd html 4.01 frameset//" ].some(publicIdStartsWith))) ) || (systemId != null && (systemId.toLowerCase() == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd")) ) { tree.compatMode = "quirks"; tree.parseError("quirky-doctype"); } else if (publicId != null && ([ "-//w3c//dtd xhtml 1.0 transitional//", "-//w3c//dtd xhtml 1.0 frameset//" ].some(publicIdStartsWith) || (systemId != null && [ "-//w3c//dtd html 4.01 transitional//", "-//w3c//dtd html 4.01 frameset//" ].indexOf(publicId.toLowerCase()) > -1)) ) { tree.compatMode = "limited quirks"; tree.parseError("almost-standards-doctype"); } else { if ((publicId == "-//W3C//DTD HTML 4.0//EN" && (systemId == null || systemId == "http://www.w3.org/TR/REC-html40/strict.dtd")) || (publicId == "-//W3C//DTD HTML 4.01//EN" && (systemId == null || systemId == "http://www.w3.org/TR/html4/strict.dtd")) || (publicId == "-//W3C//DTD XHTML 1.0 Strict//EN" && (systemId == "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd")) || (publicId == "-//W3C//DTD XHTML 1.1//EN" && (systemId == "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd")) ) { } else if (!((systemId == null || systemId == "about:legacy-compat") && publicId == null)) { tree.parseError("unknown-doctype"); } } tree.setInsertionMode('beforeHTML'); function publicIdStartsWith(string) { return publicId.toLowerCase().indexOf(string) === 0; } }; modes.initial.processCharacters = function(buffer) { buffer.skipLeadingWhitespace(); if (!buffer.length) return; tree.parseError('expected-doctype-but-got-chars'); this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.initial.processStartTag = function(name, attributes, selfClosing) { tree.parseError('expected-doctype-but-got-start-tag', {name: name}); this.anythingElse(); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.initial.processEndTag = function(name) { tree.parseError('expected-doctype-but-got-end-tag', {name: name}); this.anythingElse(); tree.insertionMode.processEndTag(name); }; modes.initial.anythingElse = function() { tree.compatMode = 'quirks'; tree.setInsertionMode('beforeHTML'); }; modes.beforeHTML = Object.create(modes.base); modes.beforeHTML.start_tag_handlers = { html: 'startTagHtml', '-default': 'startTagOther' }; modes.beforeHTML.processEOF = function() { this.anythingElse(); tree.insertionMode.processEOF(); }; modes.beforeHTML.processComment = function(data) { tree.insertComment(data, tree.document); }; modes.beforeHTML.processCharacters = function(buffer) { buffer.skipLeadingWhitespace(); if (!buffer.length) return; this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.beforeHTML.startTagHtml = function(name, attributes, selfClosing) { tree.insertHtmlElement(attributes); tree.setInsertionMode('beforeHead'); }; modes.beforeHTML.startTagOther = function(name, attributes, selfClosing) { this.anythingElse(); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.beforeHTML.processEndTag = function(name) { this.anythingElse(); tree.insertionMode.processEndTag(name); }; modes.beforeHTML.anythingElse = function() { tree.insertHtmlElement(); tree.setInsertionMode('beforeHead'); }; modes.afterAfterBody = Object.create(modes.base); modes.afterAfterBody.start_tag_handlers = { html: 'startTagHtml', '-default': 'startTagOther' }; modes.afterAfterBody.processComment = function(data) { tree.insertComment(data, tree.document); }; modes.afterAfterBody.processDoctype = function(data) { modes.inBody.processDoctype(data); }; modes.afterAfterBody.startTagHtml = function(data, attributes) { modes.inBody.startTagHtml(data, attributes); }; modes.afterAfterBody.startTagOther = function(name, attributes, selfClosing) { tree.parseError('unexpected-start-tag', {name: name}); tree.setInsertionMode('inBody'); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.afterAfterBody.endTagOther = function(name) { tree.parseError('unexpected-end-tag', {name: name}); tree.setInsertionMode('inBody'); tree.insertionMode.processEndTag(name); }; modes.afterAfterBody.processCharacters = function(data) { if (!isAllWhitespace(data.characters)) { tree.parseError('unexpected-char-after-body'); tree.setInsertionMode('inBody'); return tree.insertionMode.processCharacters(data); } modes.inBody.processCharacters(data); }; modes.afterBody = Object.create(modes.base); modes.afterBody.end_tag_handlers = { html: 'endTagHtml', '-default': 'endTagOther' }; modes.afterBody.processComment = function(data) { tree.insertComment(data, tree.openElements.rootNode); }; modes.afterBody.processCharacters = function(data) { if (!isAllWhitespace(data.characters)) { tree.parseError('unexpected-char-after-body'); tree.setInsertionMode('inBody'); return tree.insertionMode.processCharacters(data); } modes.inBody.processCharacters(data); }; modes.afterBody.processStartTag = function(name, attributes, selfClosing) { tree.parseError('unexpected-start-tag-after-body', {name: name}); tree.setInsertionMode('inBody'); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.afterBody.endTagHtml = function(name) { if (tree.context) { tree.parseError('end-html-in-innerhtml'); } else { tree.setInsertionMode('afterAfterBody'); } }; modes.afterBody.endTagOther = function(name) { tree.parseError('unexpected-end-tag-after-body', {name: name}); tree.setInsertionMode('inBody'); tree.insertionMode.processEndTag(name); }; modes.afterFrameset = Object.create(modes.base); modes.afterFrameset.start_tag_handlers = { html: 'startTagHtml', noframes: 'startTagNoframes', '-default': 'startTagOther' }; modes.afterFrameset.end_tag_handlers = { html: 'endTagHtml', '-default': 'endTagOther' }; modes.afterFrameset.processCharacters = function(buffer) { var characters = buffer.takeRemaining(); var whitespace = ""; for (var i = 0; i < characters.length; i++) { var ch = characters[i]; if (isWhitespace(ch)) whitespace += ch; } if (whitespace) { tree.insertText(whitespace); } if (whitespace.length < characters.length) tree.parseError('expected-eof-but-got-char'); }; modes.afterFrameset.startTagNoframes = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.afterFrameset.startTagOther = function(name, attributes) { tree.parseError("unexpected-start-tag-after-frameset", {name: name}); }; modes.afterFrameset.endTagHtml = function(name) { tree.setInsertionMode('afterAfterFrameset'); }; modes.afterFrameset.endTagOther = function(name) { tree.parseError("unexpected-end-tag-after-frameset", {name: name}); }; modes.beforeHead = Object.create(modes.base); modes.beforeHead.start_tag_handlers = { html: 'startTagHtml', head: 'startTagHead', '-default': 'startTagOther' }; modes.beforeHead.end_tag_handlers = { html: 'endTagImplyHead', head: 'endTagImplyHead', body: 'endTagImplyHead', br: 'endTagImplyHead', '-default': 'endTagOther' }; modes.beforeHead.processEOF = function() { this.startTagHead('head', []); tree.insertionMode.processEOF(); }; modes.beforeHead.processCharacters = function(buffer) { buffer.skipLeadingWhitespace(); if (!buffer.length) return; this.startTagHead('head', []); tree.insertionMode.processCharacters(buffer); }; modes.beforeHead.startTagHead = function(name, attributes) { tree.insertHeadElement(attributes); tree.setInsertionMode('inHead'); }; modes.beforeHead.startTagOther = function(name, attributes, selfClosing) { this.startTagHead('head', []); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.beforeHead.endTagImplyHead = function(name) { this.startTagHead('head', []); tree.insertionMode.processEndTag(name); }; modes.beforeHead.endTagOther = function(name) { tree.parseError('end-tag-after-implied-root', {name: name}); }; modes.inHead = Object.create(modes.base); modes.inHead.start_tag_handlers = { html: 'startTagHtml', head: 'startTagHead', title: 'startTagTitle', script: 'startTagScript', style: 'startTagNoFramesStyle', noscript: 'startTagNoScript', noframes: 'startTagNoFramesStyle', base: 'startTagBaseBasefontBgsoundLink', basefont: 'startTagBaseBasefontBgsoundLink', bgsound: 'startTagBaseBasefontBgsoundLink', link: 'startTagBaseBasefontBgsoundLink', meta: 'startTagMeta', "-default": 'startTagOther' }; modes.inHead.end_tag_handlers = { head: 'endTagHead', html: 'endTagHtmlBodyBr', body: 'endTagHtmlBodyBr', br: 'endTagHtmlBodyBr', "-default": 'endTagOther' }; modes.inHead.processEOF = function() { var name = tree.currentStackItem().localName; if (['title', 'style', 'script'].indexOf(name) != -1) { tree.parseError("expected-named-closing-tag-but-got-eof", {name: name}); tree.popElement(); } this.anythingElse(); tree.insertionMode.processEOF(); }; modes.inHead.processCharacters = function(buffer) { var leadingWhitespace = buffer.takeLeadingWhitespace(); if (leadingWhitespace) tree.insertText(leadingWhitespace); if (!buffer.length) return; this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.inHead.startTagHtml = function(name, attributes) { modes.inBody.processStartTag(name, attributes); }; modes.inHead.startTagHead = function(name, attributes) { tree.parseError('two-heads-are-not-better-than-one'); }; modes.inHead.startTagTitle = function(name, attributes) { tree.processGenericRCDATAStartTag(name, attributes); }; modes.inHead.startTagNoScript = function(name, attributes) { if (tree.scriptingEnabled) return tree.processGenericRawTextStartTag(name, attributes); tree.insertElement(name, attributes); tree.setInsertionMode('inHeadNoscript'); }; modes.inHead.startTagNoFramesStyle = function(name, attributes) { tree.processGenericRawTextStartTag(name, attributes); }; modes.inHead.startTagScript = function(name, attributes) { tree.insertElement(name, attributes); tree.tokenizer.setState(Tokenizer.SCRIPT_DATA); tree.originalInsertionMode = tree.insertionModeName; tree.setInsertionMode('text'); }; modes.inHead.startTagBaseBasefontBgsoundLink = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inHead.startTagMeta = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inHead.startTagOther = function(name, attributes, selfClosing) { this.anythingElse(); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.inHead.endTagHead = function(name) { if (tree.openElements.item(tree.openElements.length - 1).localName == 'head') { tree.openElements.pop(); } else { tree.parseError('unexpected-end-tag', {name: 'head'}); } tree.setInsertionMode('afterHead'); }; modes.inHead.endTagHtmlBodyBr = function(name) { this.anythingElse(); tree.insertionMode.processEndTag(name); }; modes.inHead.endTagOther = function(name) { tree.parseError('unexpected-end-tag', {name: name}); }; modes.inHead.anythingElse = function() { this.endTagHead('head'); }; modes.afterHead = Object.create(modes.base); modes.afterHead.start_tag_handlers = { html: 'startTagHtml', head: 'startTagHead', body: 'startTagBody', frameset: 'startTagFrameset', base: 'startTagFromHead', link: 'startTagFromHead', meta: 'startTagFromHead', script: 'startTagFromHead', style: 'startTagFromHead', title: 'startTagFromHead', "-default": 'startTagOther' }; modes.afterHead.end_tag_handlers = { body: 'endTagBodyHtmlBr', html: 'endTagBodyHtmlBr', br: 'endTagBodyHtmlBr', "-default": 'endTagOther' }; modes.afterHead.processEOF = function() { this.anythingElse(); tree.insertionMode.processEOF(); }; modes.afterHead.processCharacters = function(buffer) { var leadingWhitespace = buffer.takeLeadingWhitespace(); if (leadingWhitespace) tree.insertText(leadingWhitespace); if (!buffer.length) return; this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.afterHead.startTagHtml = function(name, attributes) { modes.inBody.processStartTag(name, attributes); }; modes.afterHead.startTagBody = function(name, attributes) { tree.framesetOk = false; tree.insertBodyElement(attributes); tree.setInsertionMode('inBody'); }; modes.afterHead.startTagFrameset = function(name, attributes) { tree.insertElement(name, attributes); tree.setInsertionMode('inFrameset'); }; modes.afterHead.startTagFromHead = function(name, attributes, selfClosing) { tree.parseError("unexpected-start-tag-out-of-my-head", {name: name}); tree.openElements.push(tree.head); modes.inHead.processStartTag(name, attributes, selfClosing); tree.openElements.remove(tree.head); }; modes.afterHead.startTagHead = function(name, attributes, selfClosing) { tree.parseError('unexpected-start-tag', {name: name}); }; modes.afterHead.startTagOther = function(name, attributes, selfClosing) { this.anythingElse(); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.afterHead.endTagBodyHtmlBr = function(name) { this.anythingElse(); tree.insertionMode.processEndTag(name); }; modes.afterHead.endTagOther = function(name) { tree.parseError('unexpected-end-tag', {name: name}); }; modes.afterHead.anythingElse = function() { tree.insertBodyElement([]); tree.setInsertionMode('inBody'); tree.framesetOk = true; } modes.inBody = Object.create(modes.base); modes.inBody.start_tag_handlers = { html: 'startTagHtml', head: 'startTagMisplaced', base: 'startTagProcessInHead', basefont: 'startTagProcessInHead', bgsound: 'startTagProcessInHead', link: 'startTagProcessInHead', meta: 'startTagProcessInHead', noframes: 'startTagProcessInHead', script: 'startTagProcessInHead', style: 'startTagProcessInHead', title: 'startTagProcessInHead', body: 'startTagBody', form: 'startTagForm', plaintext: 'startTagPlaintext', a: 'startTagA', button: 'startTagButton', xmp: 'startTagXmp', table: 'startTagTable', hr: 'startTagHr', image: 'startTagImage', input: 'startTagInput', textarea: 'startTagTextarea', select: 'startTagSelect', isindex: 'startTagIsindex', applet: 'startTagAppletMarqueeObject', marquee: 'startTagAppletMarqueeObject', object: 'startTagAppletMarqueeObject', li: 'startTagListItem', dd: 'startTagListItem', dt: 'startTagListItem', address: 'startTagCloseP', article: 'startTagCloseP', aside: 'startTagCloseP', blockquote: 'startTagCloseP', center: 'startTagCloseP', details: 'startTagCloseP', dir: 'startTagCloseP', div: 'startTagCloseP', dl: 'startTagCloseP', fieldset: 'startTagCloseP', figcaption: 'startTagCloseP', figure: 'startTagCloseP', footer: 'startTagCloseP', header: 'startTagCloseP', hgroup: 'startTagCloseP', main: 'startTagCloseP', menu: 'startTagCloseP', nav: 'startTagCloseP', ol: 'startTagCloseP', p: 'startTagCloseP', section: 'startTagCloseP', summary: 'startTagCloseP', ul: 'startTagCloseP', listing: 'startTagPreListing', pre: 'startTagPreListing', b: 'startTagFormatting', big: 'startTagFormatting', code: 'startTagFormatting', em: 'startTagFormatting', font: 'startTagFormatting', i: 'startTagFormatting', s: 'startTagFormatting', small: 'startTagFormatting', strike: 'startTagFormatting', strong: 'startTagFormatting', tt: 'startTagFormatting', u: 'startTagFormatting', nobr: 'startTagNobr', area: 'startTagVoidFormatting', br: 'startTagVoidFormatting', embed: 'startTagVoidFormatting', img: 'startTagVoidFormatting', keygen: 'startTagVoidFormatting', wbr: 'startTagVoidFormatting', param: 'startTagParamSourceTrack', source: 'startTagParamSourceTrack', track: 'startTagParamSourceTrack', iframe: 'startTagIFrame', noembed: 'startTagRawText', noscript: 'startTagRawText', h1: 'startTagHeading', h2: 'startTagHeading', h3: 'startTagHeading', h4: 'startTagHeading', h5: 'startTagHeading', h6: 'startTagHeading', caption: 'startTagMisplaced', col: 'startTagMisplaced', colgroup: 'startTagMisplaced', frame: 'startTagMisplaced', frameset: 'startTagFrameset', tbody: 'startTagMisplaced', td: 'startTagMisplaced', tfoot: 'startTagMisplaced', th: 'startTagMisplaced', thead: 'startTagMisplaced', tr: 'startTagMisplaced', option: 'startTagOptionOptgroup', optgroup: 'startTagOptionOptgroup', math: 'startTagMath', svg: 'startTagSVG', rt: 'startTagRpRt', rp: 'startTagRpRt', "-default": 'startTagOther' }; modes.inBody.end_tag_handlers = { p: 'endTagP', body: 'endTagBody', html: 'endTagHtml', address: 'endTagBlock', article: 'endTagBlock', aside: 'endTagBlock', blockquote: 'endTagBlock', button: 'endTagBlock', center: 'endTagBlock', details: 'endTagBlock', dir: 'endTagBlock', div: 'endTagBlock', dl: 'endTagBlock', fieldset: 'endTagBlock', figcaption: 'endTagBlock', figure: 'endTagBlock', footer: 'endTagBlock', header: 'endTagBlock', hgroup: 'endTagBlock', listing: 'endTagBlock', main: 'endTagBlock', menu: 'endTagBlock', nav: 'endTagBlock', ol: 'endTagBlock', pre: 'endTagBlock', section: 'endTagBlock', summary: 'endTagBlock', ul: 'endTagBlock', form: 'endTagForm', applet: 'endTagAppletMarqueeObject', marquee: 'endTagAppletMarqueeObject', object: 'endTagAppletMarqueeObject', dd: 'endTagListItem', dt: 'endTagListItem', li: 'endTagListItem', h1: 'endTagHeading', h2: 'endTagHeading', h3: 'endTagHeading', h4: 'endTagHeading', h5: 'endTagHeading', h6: 'endTagHeading', a: 'endTagFormatting', b: 'endTagFormatting', big: 'endTagFormatting', code: 'endTagFormatting', em: 'endTagFormatting', font: 'endTagFormatting', i: 'endTagFormatting', nobr: 'endTagFormatting', s: 'endTagFormatting', small: 'endTagFormatting', strike: 'endTagFormatting', strong: 'endTagFormatting', tt: 'endTagFormatting', u: 'endTagFormatting', br: 'endTagBr', "-default": 'endTagOther' }; modes.inBody.processCharacters = function(buffer) { if (tree.shouldSkipLeadingNewline) { tree.shouldSkipLeadingNewline = false; buffer.skipAtMostOneLeadingNewline(); } tree.reconstructActiveFormattingElements(); var characters = buffer.takeRemaining(); characters = characters.replace(/\u0000/g, function(match, index){ tree.parseError("invalid-codepoint"); return ''; }); if (!characters) return; tree.insertText(characters); if (tree.framesetOk && !isAllWhitespaceOrReplacementCharacters(characters)) tree.framesetOk = false; }; modes.inBody.startTagHtml = function(name, attributes) { tree.parseError('non-html-root'); tree.addAttributesToElement(tree.openElements.rootNode, attributes); }; modes.inBody.startTagProcessInHead = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.inBody.startTagBody = function(name, attributes) { tree.parseError('unexpected-start-tag', {name: 'body'}); if (tree.openElements.length == 1 || tree.openElements.item(1).localName != 'body') { assert.ok(tree.context); } else { tree.framesetOk = false; tree.addAttributesToElement(tree.openElements.bodyElement, attributes); } }; modes.inBody.startTagFrameset = function(name, attributes) { tree.parseError('unexpected-start-tag', {name: 'frameset'}); if (tree.openElements.length == 1 || tree.openElements.item(1).localName != 'body') { assert.ok(tree.context); } else if (tree.framesetOk) { tree.detachFromParent(tree.openElements.bodyElement); while (tree.openElements.length > 1) tree.openElements.pop(); tree.insertElement(name, attributes); tree.setInsertionMode('inFrameset'); } }; modes.inBody.startTagCloseP = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); }; modes.inBody.startTagPreListing = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); tree.framesetOk = false; tree.shouldSkipLeadingNewline = true; }; modes.inBody.startTagForm = function(name, attributes) { if (tree.form) { tree.parseError('unexpected-start-tag', {name: name}); } else { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); tree.form = tree.currentStackItem(); } }; modes.inBody.startTagRpRt = function(name, attributes) { if (tree.openElements.inScope('ruby')) { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != 'ruby') { tree.parseError('unexpected-start-tag', {name: name}); } } tree.insertElement(name, attributes); }; modes.inBody.startTagListItem = function(name, attributes) { var stopNames = {li: ['li'], dd: ['dd', 'dt'], dt: ['dd', 'dt']}; var stopName = stopNames[name]; var els = tree.openElements; for (var i = els.length - 1; i >= 0; i--) { var node = els.item(i); if (stopName.indexOf(node.localName) != -1) { tree.insertionMode.processEndTag(node.localName); break; } if (node.isSpecial() && node.localName !== 'p' && node.localName !== 'address' && node.localName !== 'div') break; } if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); tree.framesetOk = false; }; modes.inBody.startTagPlaintext = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); tree.tokenizer.setState(Tokenizer.PLAINTEXT); }; modes.inBody.startTagHeading = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); if (tree.currentStackItem().isNumberedHeader()) { tree.parseError('unexpected-start-tag', {name: name}); tree.popElement(); } tree.insertElement(name, attributes); }; modes.inBody.startTagA = function(name, attributes) { var activeA = tree.elementInActiveFormattingElements('a'); if (activeA) { tree.parseError("unexpected-start-tag-implies-end-tag", {startName: "a", endName: "a"}); tree.adoptionAgencyEndTag('a'); if (tree.openElements.contains(activeA)) tree.openElements.remove(activeA); tree.removeElementFromActiveFormattingElements(activeA); } tree.reconstructActiveFormattingElements(); tree.insertFormattingElement(name, attributes); }; modes.inBody.startTagFormatting = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertFormattingElement(name, attributes); }; modes.inBody.startTagNobr = function(name, attributes) { tree.reconstructActiveFormattingElements(); if (tree.openElements.inScope('nobr')) { tree.parseError("unexpected-start-tag-implies-end-tag", {startName: 'nobr', endName: 'nobr'}); this.processEndTag('nobr'); tree.reconstructActiveFormattingElements(); } tree.insertFormattingElement(name, attributes); }; modes.inBody.startTagButton = function(name, attributes) { if (tree.openElements.inScope('button')) { tree.parseError('unexpected-start-tag-implies-end-tag', {startName: 'button', endName: 'button'}); this.processEndTag('button'); tree.insertionMode.processStartTag(name, attributes); } else { tree.framesetOk = false; tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); } }; modes.inBody.startTagAppletMarqueeObject = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); tree.activeFormattingElements.push(Marker); tree.framesetOk = false; }; modes.inBody.endTagAppletMarqueeObject = function(name) { if (!tree.openElements.inScope(name)) { tree.parseError("unexpected-end-tag", {name: name}); } else { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != name) { tree.parseError('end-tag-too-early', {name: name}); } tree.openElements.popUntilPopped(name); tree.clearActiveFormattingElements(); } }; modes.inBody.startTagXmp = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.processEndTag('p'); tree.reconstructActiveFormattingElements(); tree.processGenericRawTextStartTag(name, attributes); tree.framesetOk = false; }; modes.inBody.startTagTable = function(name, attributes) { if (tree.compatMode !== "quirks") if (tree.openElements.inButtonScope('p')) this.processEndTag('p'); tree.insertElement(name, attributes); tree.setInsertionMode('inTable'); tree.framesetOk = false; }; modes.inBody.startTagVoidFormatting = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertSelfClosingElement(name, attributes); tree.framesetOk = false; }; modes.inBody.startTagParamSourceTrack = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inBody.startTagHr = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertSelfClosingElement(name, attributes); tree.framesetOk = false; }; modes.inBody.startTagImage = function(name, attributes) { tree.parseError('unexpected-start-tag-treated-as', {originalName: 'image', newName: 'img'}); this.processStartTag('img', attributes); }; modes.inBody.startTagInput = function(name, attributes) { var currentFramesetOk = tree.framesetOk; this.startTagVoidFormatting(name, attributes); for (var key in attributes) { if (attributes[key].nodeName == 'type') { if (attributes[key].nodeValue.toLowerCase() == 'hidden') tree.framesetOk = currentFramesetOk; break; } } }; modes.inBody.startTagIsindex = function(name, attributes) { tree.parseError('deprecated-tag', {name: 'isindex'}); tree.selfClosingFlagAcknowledged = true; if (tree.form) return; var formAttributes = []; var inputAttributes = []; var prompt = "This is a searchable index. Enter search keywords: "; for (var key in attributes) { switch (attributes[key].nodeName) { case 'action': formAttributes.push({nodeName: 'action', nodeValue: attributes[key].nodeValue}); break; case 'prompt': prompt = attributes[key].nodeValue; break; case 'name': break; default: inputAttributes.push({nodeName: attributes[key].nodeName, nodeValue: attributes[key].nodeValue}); } } inputAttributes.push({nodeName: 'name', nodeValue: 'isindex'}); this.processStartTag('form', formAttributes); this.processStartTag('hr'); this.processStartTag('label'); this.processCharacters(new CharacterBuffer(prompt)); this.processStartTag('input', inputAttributes); this.processEndTag('label'); this.processStartTag('hr'); this.processEndTag('form'); }; modes.inBody.startTagTextarea = function(name, attributes) { tree.insertElement(name, attributes); tree.tokenizer.setState(Tokenizer.RCDATA); tree.originalInsertionMode = tree.insertionModeName; tree.shouldSkipLeadingNewline = true; tree.framesetOk = false; tree.setInsertionMode('text'); }; modes.inBody.startTagIFrame = function(name, attributes) { tree.framesetOk = false; this.startTagRawText(name, attributes); }; modes.inBody.startTagRawText = function(name, attributes) { tree.processGenericRawTextStartTag(name, attributes); }; modes.inBody.startTagSelect = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); tree.framesetOk = false; var insertionModeName = tree.insertionModeName; if (insertionModeName == 'inTable' || insertionModeName == 'inCaption' || insertionModeName == 'inColumnGroup' || insertionModeName == 'inTableBody' || insertionModeName == 'inRow' || insertionModeName == 'inCell') { tree.setInsertionMode('inSelectInTable'); } else { tree.setInsertionMode('inSelect'); } }; modes.inBody.startTagMisplaced = function(name, attributes) { tree.parseError('unexpected-start-tag-ignored', {name: name}); }; modes.inBody.endTagMisplaced = function(name) { tree.parseError("unexpected-end-tag", {name: name}); }; modes.inBody.endTagBr = function(name) { tree.parseError("unexpected-end-tag-treated-as", {originalName: "br", newName: "br element"}); tree.reconstructActiveFormattingElements(); tree.insertElement(name, []); tree.popElement(); }; modes.inBody.startTagOptionOptgroup = function(name, attributes) { if (tree.currentStackItem().localName == 'option') tree.popElement(); tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); }; modes.inBody.startTagOther = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); }; modes.inBody.endTagOther = function(name) { var node; for (var i = tree.openElements.length - 1; i > 0; i--) { node = tree.openElements.item(i); if (node.localName == name) { tree.generateImpliedEndTags(name); if (tree.currentStackItem().localName != name) tree.parseError('unexpected-end-tag', {name: name}); tree.openElements.remove_openElements_until(function(x) {return x === node;}); break; } if (node.isSpecial()) { tree.parseError('unexpected-end-tag', {name: name}); break; } } }; modes.inBody.startTagMath = function(name, attributes, selfClosing) { tree.reconstructActiveFormattingElements(); attributes = tree.adjustMathMLAttributes(attributes); attributes = tree.adjustForeignAttributes(attributes); tree.insertForeignElement(name, attributes, "http://www.w3.org/1998/Math/MathML", selfClosing); }; modes.inBody.startTagSVG = function(name, attributes, selfClosing) { tree.reconstructActiveFormattingElements(); attributes = tree.adjustSVGAttributes(attributes); attributes = tree.adjustForeignAttributes(attributes); tree.insertForeignElement(name, attributes, "http://www.w3.org/2000/svg", selfClosing); }; modes.inBody.endTagP = function(name) { if (!tree.openElements.inButtonScope('p')) { tree.parseError('unexpected-end-tag', {name: 'p'}); this.startTagCloseP('p', []); this.endTagP('p'); } else { tree.generateImpliedEndTags('p'); if (tree.currentStackItem().localName != 'p') tree.parseError('unexpected-implied-end-tag', {name: 'p'}); tree.openElements.popUntilPopped(name); } }; modes.inBody.endTagBody = function(name) { if (!tree.openElements.inScope('body')) { tree.parseError('unexpected-end-tag', {name: name}); return; } if (tree.currentStackItem().localName != 'body') { tree.parseError('expected-one-end-tag-but-got-another', { expectedName: tree.currentStackItem().localName, gotName: name }); } tree.setInsertionMode('afterBody'); }; modes.inBody.endTagHtml = function(name) { if (!tree.openElements.inScope('body')) { tree.parseError('unexpected-end-tag', {name: name}); return; } if (tree.currentStackItem().localName != 'body') { tree.parseError('expected-one-end-tag-but-got-another', { expectedName: tree.currentStackItem().localName, gotName: name }); } tree.setInsertionMode('afterBody'); tree.insertionMode.processEndTag(name); }; modes.inBody.endTagBlock = function(name) { if (!tree.openElements.inScope(name)) { tree.parseError('unexpected-end-tag', {name: name}); } else { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != name) { tree.parseError('end-tag-too-early', {name: name}); } tree.openElements.popUntilPopped(name); } }; modes.inBody.endTagForm = function(name) { var node = tree.form; tree.form = null; if (!node || !tree.openElements.inScope(name)) { tree.parseError('unexpected-end-tag', {name: name}); } else { tree.generateImpliedEndTags(); if (tree.currentStackItem() != node) { tree.parseError('end-tag-too-early-ignored', {name: 'form'}); } tree.openElements.remove(node); } }; modes.inBody.endTagListItem = function(name) { if (!tree.openElements.inListItemScope(name)) { tree.parseError('unexpected-end-tag', {name: name}); } else { tree.generateImpliedEndTags(name); if (tree.currentStackItem().localName != name) tree.parseError('end-tag-too-early', {name: name}); tree.openElements.popUntilPopped(name); } }; modes.inBody.endTagHeading = function(name) { if (!tree.openElements.hasNumberedHeaderElementInScope()) { tree.parseError('unexpected-end-tag', {name: name}); return; } tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != name) tree.parseError('end-tag-too-early', {name: name}); tree.openElements.remove_openElements_until(function(e) { return e.isNumberedHeader(); }); }; modes.inBody.endTagFormatting = function(name, attributes) { if (!tree.adoptionAgencyEndTag(name)) this.endTagOther(name, attributes); }; modes.inCaption = Object.create(modes.base); modes.inCaption.start_tag_handlers = { html: 'startTagHtml', caption: 'startTagTableElement', col: 'startTagTableElement', colgroup: 'startTagTableElement', tbody: 'startTagTableElement', td: 'startTagTableElement', tfoot: 'startTagTableElement', thead: 'startTagTableElement', tr: 'startTagTableElement', '-default': 'startTagOther' }; modes.inCaption.end_tag_handlers = { caption: 'endTagCaption', table: 'endTagTable', body: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', tbody: 'endTagIgnore', td: 'endTagIgnore', tfood: 'endTagIgnore', thead: 'endTagIgnore', tr: 'endTagIgnore', '-default': 'endTagOther' }; modes.inCaption.processCharacters = function(data) { modes.inBody.processCharacters(data); }; modes.inCaption.startTagTableElement = function(name, attributes) { tree.parseError('unexpected-end-tag', {name: name}); var ignoreEndTag = !tree.openElements.inTableScope('caption'); tree.insertionMode.processEndTag('caption'); if (!ignoreEndTag) tree.insertionMode.processStartTag(name, attributes); }; modes.inCaption.startTagOther = function(name, attributes, selfClosing) { modes.inBody.processStartTag(name, attributes, selfClosing); }; modes.inCaption.endTagCaption = function(name) { if (!tree.openElements.inTableScope('caption')) { assert.ok(tree.context); tree.parseError('unexpected-end-tag', {name: name}); } else { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != 'caption') { tree.parseError('expected-one-end-tag-but-got-another', { gotName: "caption", expectedName: tree.currentStackItem().localName }); } tree.openElements.popUntilPopped('caption'); tree.clearActiveFormattingElements(); tree.setInsertionMode('inTable'); } }; modes.inCaption.endTagTable = function(name) { tree.parseError("unexpected-end-table-in-caption"); var ignoreEndTag = !tree.openElements.inTableScope('caption'); tree.insertionMode.processEndTag('caption'); if (!ignoreEndTag) tree.insertionMode.processEndTag(name); }; modes.inCaption.endTagIgnore = function(name) { tree.parseError('unexpected-end-tag', {name: name}); }; modes.inCaption.endTagOther = function(name) { modes.inBody.processEndTag(name); }; modes.inCell = Object.create(modes.base); modes.inCell.start_tag_handlers = { html: 'startTagHtml', caption: 'startTagTableOther', col: 'startTagTableOther', colgroup: 'startTagTableOther', tbody: 'startTagTableOther', td: 'startTagTableOther', tfoot: 'startTagTableOther', th: 'startTagTableOther', thead: 'startTagTableOther', tr: 'startTagTableOther', '-default': 'startTagOther' }; modes.inCell.end_tag_handlers = { td: 'endTagTableCell', th: 'endTagTableCell', body: 'endTagIgnore', caption: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', table: 'endTagImply', tbody: 'endTagImply', tfoot: 'endTagImply', thead: 'endTagImply', tr: 'endTagImply', '-default': 'endTagOther' }; modes.inCell.processCharacters = function(data) { modes.inBody.processCharacters(data); }; modes.inCell.startTagTableOther = function(name, attributes, selfClosing) { if (tree.openElements.inTableScope('td') || tree.openElements.inTableScope('th')) { this.closeCell(); tree.insertionMode.processStartTag(name, attributes, selfClosing); } else { tree.parseError('unexpected-start-tag', {name: name}); } }; modes.inCell.startTagOther = function(name, attributes, selfClosing) { modes.inBody.processStartTag(name, attributes, selfClosing); }; modes.inCell.endTagTableCell = function(name) { if (tree.openElements.inTableScope(name)) { tree.generateImpliedEndTags(name); if (tree.currentStackItem().localName != name.toLowerCase()) { tree.parseError('unexpected-cell-end-tag', {name: name}); tree.openElements.popUntilPopped(name); } else { tree.popElement(); } tree.clearActiveFormattingElements(); tree.setInsertionMode('inRow'); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inCell.endTagIgnore = function(name) { tree.parseError('unexpected-end-tag', {name: name}); }; modes.inCell.endTagImply = function(name) { if (tree.openElements.inTableScope(name)) { this.closeCell(); tree.insertionMode.processEndTag(name); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inCell.endTagOther = function(name) { modes.inBody.processEndTag(name); }; modes.inCell.closeCell = function() { if (tree.openElements.inTableScope('td')) { this.endTagTableCell('td'); } else if (tree.openElements.inTableScope('th')) { this.endTagTableCell('th'); } }; modes.inColumnGroup = Object.create(modes.base); modes.inColumnGroup.start_tag_handlers = { html: 'startTagHtml', col: 'startTagCol', '-default': 'startTagOther' }; modes.inColumnGroup.end_tag_handlers = { colgroup: 'endTagColgroup', col: 'endTagCol', '-default': 'endTagOther' }; modes.inColumnGroup.ignoreEndTagColgroup = function() { return tree.currentStackItem().localName == 'html'; }; modes.inColumnGroup.processCharacters = function(buffer) { var leadingWhitespace = buffer.takeLeadingWhitespace(); if (leadingWhitespace) tree.insertText(leadingWhitespace); if (!buffer.length) return; var ignoreEndTag = this.ignoreEndTagColgroup(); this.endTagColgroup('colgroup'); if (!ignoreEndTag) tree.insertionMode.processCharacters(buffer); }; modes.inColumnGroup.startTagCol = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inColumnGroup.startTagOther = function(name, attributes, selfClosing) { var ignoreEndTag = this.ignoreEndTagColgroup(); this.endTagColgroup('colgroup'); if (!ignoreEndTag) tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.inColumnGroup.endTagColgroup = function(name) { if (this.ignoreEndTagColgroup()) { assert.ok(tree.context); tree.parseError('unexpected-end-tag', {name: name}); } else { tree.popElement(); tree.setInsertionMode('inTable'); } }; modes.inColumnGroup.endTagCol = function(name) { tree.parseError("no-end-tag", {name: 'col'}); }; modes.inColumnGroup.endTagOther = function(name) { var ignoreEndTag = this.ignoreEndTagColgroup(); this.endTagColgroup('colgroup'); if (!ignoreEndTag) tree.insertionMode.processEndTag(name) ; }; modes.inForeignContent = Object.create(modes.base); modes.inForeignContent.processStartTag = function(name, attributes, selfClosing) { if (['b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em', 'embed', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'menu', 'meta', 'nobr', 'ol', 'p', 'pre', 'ruby', 's', 'small', 'span', 'strong', 'strike', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var'].indexOf(name) != -1 || (name == 'font' && attributes.some(function(attr){ return ['color', 'face', 'size'].indexOf(attr.nodeName) >= 0 }))) { tree.parseError('unexpected-html-element-in-foreign-content', {name: name}); while (tree.currentStackItem().isForeign() && !tree.currentStackItem().isHtmlIntegrationPoint() && !tree.currentStackItem().isMathMLTextIntegrationPoint()) { tree.openElements.pop(); } tree.insertionMode.processStartTag(name, attributes, selfClosing); return; } if (tree.currentStackItem().namespaceURI == "http://www.w3.org/1998/Math/MathML") { attributes = tree.adjustMathMLAttributes(attributes); } if (tree.currentStackItem().namespaceURI == "http://www.w3.org/2000/svg") { name = tree.adjustSVGTagNameCase(name); attributes = tree.adjustSVGAttributes(attributes); } attributes = tree.adjustForeignAttributes(attributes); tree.insertForeignElement(name, attributes, tree.currentStackItem().namespaceURI, selfClosing); }; modes.inForeignContent.processEndTag = function(name) { var node = tree.currentStackItem(); var index = tree.openElements.length - 1; if (node.localName.toLowerCase() != name) tree.parseError("unexpected-end-tag", {name: name}); while (true) { if (index === 0) break; if (node.localName.toLowerCase() == name) { while (tree.openElements.pop() != node); break; } index -= 1; node = tree.openElements.item(index); if (node.isForeign()) { continue; } else { tree.insertionMode.processEndTag(name); break; } } }; modes.inForeignContent.processCharacters = function(buffer) { var characters = buffer.takeRemaining(); characters = characters.replace(/\u0000/g, function(match, index){ tree.parseError('invalid-codepoint'); return '\uFFFD'; }); if (tree.framesetOk && !isAllWhitespaceOrReplacementCharacters(characters)) tree.framesetOk = false; tree.insertText(characters); }; modes.inHeadNoscript = Object.create(modes.base); modes.inHeadNoscript.start_tag_handlers = { html: 'startTagHtml', basefont: 'startTagBasefontBgsoundLinkMetaNoframesStyle', bgsound: 'startTagBasefontBgsoundLinkMetaNoframesStyle', link: 'startTagBasefontBgsoundLinkMetaNoframesStyle', meta: 'startTagBasefontBgsoundLinkMetaNoframesStyle', noframes: 'startTagBasefontBgsoundLinkMetaNoframesStyle', style: 'startTagBasefontBgsoundLinkMetaNoframesStyle', head: 'startTagHeadNoscript', noscript: 'startTagHeadNoscript', "-default": 'startTagOther' }; modes.inHeadNoscript.end_tag_handlers = { noscript: 'endTagNoscript', br: 'endTagBr', '-default': 'endTagOther' }; modes.inHeadNoscript.processCharacters = function(buffer) { var leadingWhitespace = buffer.takeLeadingWhitespace(); if (leadingWhitespace) tree.insertText(leadingWhitespace); if (!buffer.length) return; tree.parseError("unexpected-char-in-frameset"); this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.inHeadNoscript.processComment = function(data) { modes.inHead.processComment(data); }; modes.inHeadNoscript.startTagBasefontBgsoundLinkMetaNoframesStyle = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.inHeadNoscript.startTagHeadNoscript = function(name, attributes) { tree.parseError("unexpected-start-tag-in-frameset", {name: name}); }; modes.inHeadNoscript.startTagOther = function(name, attributes) { tree.parseError("unexpected-start-tag-in-frameset", {name: name}); this.anythingElse(); tree.insertionMode.processStartTag(name, attributes); }; modes.inHeadNoscript.endTagBr = function(name, attributes) { tree.parseError("unexpected-end-tag-in-frameset", {name: name}); this.anythingElse(); tree.insertionMode.processEndTag(name, attributes); }; modes.inHeadNoscript.endTagNoscript = function(name, attributes) { tree.popElement(); tree.setInsertionMode('inHead'); }; modes.inHeadNoscript.endTagOther = function(name, attributes) { tree.parseError("unexpected-end-tag-in-frameset", {name: name}); }; modes.inHeadNoscript.anythingElse = function() { tree.popElement(); tree.setInsertionMode('inHead'); }; modes.inFrameset = Object.create(modes.base); modes.inFrameset.start_tag_handlers = { html: 'startTagHtml', frameset: 'startTagFrameset', frame: 'startTagFrame', noframes: 'startTagNoframes', "-default": 'startTagOther' }; modes.inFrameset.end_tag_handlers = { frameset: 'endTagFrameset', noframes: 'endTagNoframes', '-default': 'endTagOther' }; modes.inFrameset.processCharacters = function(data) { tree.parseError("unexpected-char-in-frameset"); }; modes.inFrameset.startTagFrameset = function(name, attributes) { tree.insertElement(name, attributes); }; modes.inFrameset.startTagFrame = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inFrameset.startTagNoframes = function(name, attributes) { modes.inBody.processStartTag(name, attributes); }; modes.inFrameset.startTagOther = function(name, attributes) { tree.parseError("unexpected-start-tag-in-frameset", {name: name}); }; modes.inFrameset.endTagFrameset = function(name, attributes) { if (tree.currentStackItem().localName == 'html') { tree.parseError("unexpected-frameset-in-frameset-innerhtml"); } else { tree.popElement(); } if (!tree.context && tree.currentStackItem().localName != 'frameset') { tree.setInsertionMode('afterFrameset'); } }; modes.inFrameset.endTagNoframes = function(name) { modes.inBody.processEndTag(name); }; modes.inFrameset.endTagOther = function(name) { tree.parseError("unexpected-end-tag-in-frameset", {name: name}); }; modes.inTable = Object.create(modes.base); modes.inTable.start_tag_handlers = { html: 'startTagHtml', caption: 'startTagCaption', colgroup: 'startTagColgroup', col: 'startTagCol', table: 'startTagTable', tbody: 'startTagRowGroup', tfoot: 'startTagRowGroup', thead: 'startTagRowGroup', td: 'startTagImplyTbody', th: 'startTagImplyTbody', tr: 'startTagImplyTbody', style: 'startTagStyleScript', script: 'startTagStyleScript', input: 'startTagInput', form: 'startTagForm', '-default': 'startTagOther' }; modes.inTable.end_tag_handlers = { table: 'endTagTable', body: 'endTagIgnore', caption: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', tbody: 'endTagIgnore', td: 'endTagIgnore', tfoot: 'endTagIgnore', th: 'endTagIgnore', thead: 'endTagIgnore', tr: 'endTagIgnore', '-default': 'endTagOther' }; modes.inTable.processCharacters = function(data) { if (tree.currentStackItem().isFosterParenting()) { var originalInsertionMode = tree.insertionModeName; tree.setInsertionMode('inTableText'); tree.originalInsertionMode = originalInsertionMode; tree.insertionMode.processCharacters(data); } else { tree.redirectAttachToFosterParent = true; modes.inBody.processCharacters(data); tree.redirectAttachToFosterParent = false; } }; modes.inTable.startTagCaption = function(name, attributes) { tree.openElements.popUntilTableScopeMarker(); tree.activeFormattingElements.push(Marker); tree.insertElement(name, attributes); tree.setInsertionMode('inCaption'); }; modes.inTable.startTagColgroup = function(name, attributes) { tree.openElements.popUntilTableScopeMarker(); tree.insertElement(name, attributes); tree.setInsertionMode('inColumnGroup'); }; modes.inTable.startTagCol = function(name, attributes) { this.startTagColgroup('colgroup', []); tree.insertionMode.processStartTag(name, attributes); }; modes.inTable.startTagRowGroup = function(name, attributes) { tree.openElements.popUntilTableScopeMarker(); tree.insertElement(name, attributes); tree.setInsertionMode('inTableBody'); }; modes.inTable.startTagImplyTbody = function(name, attributes) { this.startTagRowGroup('tbody', []); tree.insertionMode.processStartTag(name, attributes); }; modes.inTable.startTagTable = function(name, attributes) { tree.parseError("unexpected-start-tag-implies-end-tag", {startName: "table", endName: "table"}); tree.insertionMode.processEndTag('table'); if (!tree.context) tree.insertionMode.processStartTag(name, attributes); }; modes.inTable.startTagStyleScript = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.inTable.startTagInput = function(name, attributes) { for (var key in attributes) { if (attributes[key].nodeName.toLowerCase() == 'type') { if (attributes[key].nodeValue.toLowerCase() == 'hidden') { tree.parseError("unexpected-hidden-input-in-table"); tree.insertElement(name, attributes); tree.openElements.pop(); return; } break; } } this.startTagOther(name, attributes); }; modes.inTable.startTagForm = function(name, attributes) { tree.parseError("unexpected-form-in-table"); if (!tree.form) { tree.insertElement(name, attributes); tree.form = tree.currentStackItem(); tree.openElements.pop(); } }; modes.inTable.startTagOther = function(name, attributes, selfClosing) { tree.parseError("unexpected-start-tag-implies-table-voodoo", {name: name}); tree.redirectAttachToFosterParent = true; modes.inBody.processStartTag(name, attributes, selfClosing); tree.redirectAttachToFosterParent = false; }; modes.inTable.endTagTable = function(name) { if (tree.openElements.inTableScope(name)) { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != name) { tree.parseError("end-tag-too-early-named", {gotName: 'table', expectedName: tree.currentStackItem().localName}); } tree.openElements.popUntilPopped('table'); tree.resetInsertionMode(); } else { assert.ok(tree.context); tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inTable.endTagIgnore = function(name) { tree.parseError("unexpected-end-tag", {name: name}); }; modes.inTable.endTagOther = function(name) { tree.parseError("unexpected-end-tag-implies-table-voodoo", {name: name}); tree.redirectAttachToFosterParent = true; modes.inBody.processEndTag(name); tree.redirectAttachToFosterParent = false; }; modes.inTableText = Object.create(modes.base); modes.inTableText.flushCharacters = function() { var characters = tree.pendingTableCharacters.join(''); if (!isAllWhitespace(characters)) { tree.redirectAttachToFosterParent = true; tree.reconstructActiveFormattingElements(); tree.insertText(characters); tree.framesetOk = false; tree.redirectAttachToFosterParent = false; } else { tree.insertText(characters); } tree.pendingTableCharacters = []; }; modes.inTableText.processComment = function(data) { this.flushCharacters(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processComment(data); }; modes.inTableText.processEOF = function(data) { this.flushCharacters(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processEOF(); }; modes.inTableText.processCharacters = function(buffer) { var characters = buffer.takeRemaining(); characters = characters.replace(/\u0000/g, function(match, index){ tree.parseError("invalid-codepoint"); return ''; }); if (!characters) return; tree.pendingTableCharacters.push(characters); }; modes.inTableText.processStartTag = function(name, attributes, selfClosing) { this.flushCharacters(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.inTableText.processEndTag = function(name, attributes) { this.flushCharacters(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processEndTag(name, attributes); }; modes.inTableBody = Object.create(modes.base); modes.inTableBody.start_tag_handlers = { html: 'startTagHtml', tr: 'startTagTr', td: 'startTagTableCell', th: 'startTagTableCell', caption: 'startTagTableOther', col: 'startTagTableOther', colgroup: 'startTagTableOther', tbody: 'startTagTableOther', tfoot: 'startTagTableOther', thead: 'startTagTableOther', '-default': 'startTagOther' }; modes.inTableBody.end_tag_handlers = { table: 'endTagTable', tbody: 'endTagTableRowGroup', tfoot: 'endTagTableRowGroup', thead: 'endTagTableRowGroup', body: 'endTagIgnore', caption: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', td: 'endTagIgnore', th: 'endTagIgnore', tr: 'endTagIgnore', '-default': 'endTagOther' }; modes.inTableBody.processCharacters = function(data) { modes.inTable.processCharacters(data); }; modes.inTableBody.startTagTr = function(name, attributes) { tree.openElements.popUntilTableBodyScopeMarker(); tree.insertElement(name, attributes); tree.setInsertionMode('inRow'); }; modes.inTableBody.startTagTableCell = function(name, attributes) { tree.parseError("unexpected-cell-in-table-body", {name: name}); this.startTagTr('tr', []); tree.insertionMode.processStartTag(name, attributes); }; modes.inTableBody.startTagTableOther = function(name, attributes) { if (tree.openElements.inTableScope('tbody') || tree.openElements.inTableScope('thead') || tree.openElements.inTableScope('tfoot')) { tree.openElements.popUntilTableBodyScopeMarker(); this.endTagTableRowGroup(tree.currentStackItem().localName); tree.insertionMode.processStartTag(name, attributes); } else { tree.parseError('unexpected-start-tag', {name: name}); } }; modes.inTableBody.startTagOther = function(name, attributes) { modes.inTable.processStartTag(name, attributes); }; modes.inTableBody.endTagTableRowGroup = function(name) { if (tree.openElements.inTableScope(name)) { tree.openElements.popUntilTableBodyScopeMarker(); tree.popElement(); tree.setInsertionMode('inTable'); } else { tree.parseError('unexpected-end-tag-in-table-body', {name: name}); } }; modes.inTableBody.endTagTable = function(name) { if (tree.openElements.inTableScope('tbody') || tree.openElements.inTableScope('thead') || tree.openElements.inTableScope('tfoot')) { tree.openElements.popUntilTableBodyScopeMarker(); this.endTagTableRowGroup(tree.currentStackItem().localName); tree.insertionMode.processEndTag(name); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inTableBody.endTagIgnore = function(name) { tree.parseError("unexpected-end-tag-in-table-body", {name: name}); }; modes.inTableBody.endTagOther = function(name) { modes.inTable.processEndTag(name); }; modes.inSelect = Object.create(modes.base); modes.inSelect.start_tag_handlers = { html: 'startTagHtml', option: 'startTagOption', optgroup: 'startTagOptgroup', select: 'startTagSelect', input: 'startTagInput', keygen: 'startTagInput', textarea: 'startTagInput', script: 'startTagScript', '-default': 'startTagOther' }; modes.inSelect.end_tag_handlers = { option: 'endTagOption', optgroup: 'endTagOptgroup', select: 'endTagSelect', caption: 'endTagTableElements', table: 'endTagTableElements', tbody: 'endTagTableElements', tfoot: 'endTagTableElements', thead: 'endTagTableElements', tr: 'endTagTableElements', td: 'endTagTableElements', th: 'endTagTableElements', '-default': 'endTagOther' }; modes.inSelect.processCharacters = function(buffer) { var data = buffer.takeRemaining(); data = data.replace(/\u0000/g, function(match, index){ tree.parseError("invalid-codepoint"); return ''; }); if (!data) return; tree.insertText(data); }; modes.inSelect.startTagOption = function(name, attributes) { if (tree.currentStackItem().localName == 'option') tree.popElement(); tree.insertElement(name, attributes); }; modes.inSelect.startTagOptgroup = function(name, attributes) { if (tree.currentStackItem().localName == 'option') tree.popElement(); if (tree.currentStackItem().localName == 'optgroup') tree.popElement(); tree.insertElement(name, attributes); }; modes.inSelect.endTagOption = function(name) { if (tree.currentStackItem().localName !== 'option') { tree.parseError('unexpected-end-tag-in-select', {name: name}); return; } tree.popElement(); }; modes.inSelect.endTagOptgroup = function(name) { if (tree.currentStackItem().localName == 'option' && tree.openElements.item(tree.openElements.length - 2).localName == 'optgroup') { tree.popElement(); } if (tree.currentStackItem().localName == 'optgroup') { tree.popElement(); } else { tree.parseError('unexpected-end-tag-in-select', {name: 'optgroup'}); } }; modes.inSelect.startTagSelect = function(name) { tree.parseError("unexpected-select-in-select"); this.endTagSelect('select'); }; modes.inSelect.endTagSelect = function(name) { if (tree.openElements.inTableScope('select')) { tree.openElements.popUntilPopped('select'); tree.resetInsertionMode(); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inSelect.startTagInput = function(name, attributes) { tree.parseError("unexpected-input-in-select"); if (tree.openElements.inSelectScope('select')) { this.endTagSelect('select'); tree.insertionMode.processStartTag(name, attributes); } }; modes.inSelect.startTagScript = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.inSelect.endTagTableElements = function(name) { tree.parseError('unexpected-end-tag-in-select', {name: name}); if (tree.openElements.inTableScope(name)) { this.endTagSelect('select'); tree.insertionMode.processEndTag(name); } }; modes.inSelect.startTagOther = function(name, attributes) { tree.parseError("unexpected-start-tag-in-select", {name: name}); }; modes.inSelect.endTagOther = function(name) { tree.parseError('unexpected-end-tag-in-select', {name: name}); }; modes.inSelectInTable = Object.create(modes.base); modes.inSelectInTable.start_tag_handlers = { caption: 'startTagTable', table: 'startTagTable', tbody: 'startTagTable', tfoot: 'startTagTable', thead: 'startTagTable', tr: 'startTagTable', td: 'startTagTable', th: 'startTagTable', '-default': 'startTagOther' }; modes.inSelectInTable.end_tag_handlers = { caption: 'endTagTable', table: 'endTagTable', tbody: 'endTagTable', tfoot: 'endTagTable', thead: 'endTagTable', tr: 'endTagTable', td: 'endTagTable', th: 'endTagTable', '-default': 'endTagOther' }; modes.inSelectInTable.processCharacters = function(data) { modes.inSelect.processCharacters(data); }; modes.inSelectInTable.startTagTable = function(name, attributes) { tree.parseError("unexpected-table-element-start-tag-in-select-in-table", {name: name}); this.endTagOther("select"); tree.insertionMode.processStartTag(name, attributes); }; modes.inSelectInTable.startTagOther = function(name, attributes, selfClosing) { modes.inSelect.processStartTag(name, attributes, selfClosing); }; modes.inSelectInTable.endTagTable = function(name) { tree.parseError("unexpected-table-element-end-tag-in-select-in-table", {name: name}); if (tree.openElements.inTableScope(name)) { this.endTagOther("select"); tree.insertionMode.processEndTag(name); } }; modes.inSelectInTable.endTagOther = function(name) { modes.inSelect.processEndTag(name); }; modes.inRow = Object.create(modes.base); modes.inRow.start_tag_handlers = { html: 'startTagHtml', td: 'startTagTableCell', th: 'startTagTableCell', caption: 'startTagTableOther', col: 'startTagTableOther', colgroup: 'startTagTableOther', tbody: 'startTagTableOther', tfoot: 'startTagTableOther', thead: 'startTagTableOther', tr: 'startTagTableOther', '-default': 'startTagOther' }; modes.inRow.end_tag_handlers = { tr: 'endTagTr', table: 'endTagTable', tbody: 'endTagTableRowGroup', tfoot: 'endTagTableRowGroup', thead: 'endTagTableRowGroup', body: 'endTagIgnore', caption: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', td: 'endTagIgnore', th: 'endTagIgnore', '-default': 'endTagOther' }; modes.inRow.processCharacters = function(data) { modes.inTable.processCharacters(data); }; modes.inRow.startTagTableCell = function(name, attributes) { tree.openElements.popUntilTableRowScopeMarker(); tree.insertElement(name, attributes); tree.setInsertionMode('inCell'); tree.activeFormattingElements.push(Marker); }; modes.inRow.startTagTableOther = function(name, attributes) { var ignoreEndTag = this.ignoreEndTagTr(); this.endTagTr('tr'); if (!ignoreEndTag) tree.insertionMode.processStartTag(name, attributes); }; modes.inRow.startTagOther = function(name, attributes, selfClosing) { modes.inTable.processStartTag(name, attributes, selfClosing); }; modes.inRow.endTagTr = function(name) { if (this.ignoreEndTagTr()) { assert.ok(tree.context); tree.parseError('unexpected-end-tag', {name: name}); } else { tree.openElements.popUntilTableRowScopeMarker(); tree.popElement(); tree.setInsertionMode('inTableBody'); } }; modes.inRow.endTagTable = function(name) { var ignoreEndTag = this.ignoreEndTagTr(); this.endTagTr('tr'); if (!ignoreEndTag) tree.insertionMode.processEndTag(name); }; modes.inRow.endTagTableRowGroup = function(name) { if (tree.openElements.inTableScope(name)) { this.endTagTr('tr'); tree.insertionMode.processEndTag(name); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inRow.endTagIgnore = function(name) { tree.parseError("unexpected-end-tag-in-table-row", {name: name}); }; modes.inRow.endTagOther = function(name) { modes.inTable.processEndTag(name); }; modes.inRow.ignoreEndTagTr = function() { return !tree.openElements.inTableScope('tr'); }; modes.afterAfterFrameset = Object.create(modes.base); modes.afterAfterFrameset.start_tag_handlers = { html: 'startTagHtml', noframes: 'startTagNoFrames', '-default': 'startTagOther' }; modes.afterAfterFrameset.processEOF = function() {}; modes.afterAfterFrameset.processComment = function(data) { tree.insertComment(data, tree.document); }; modes.afterAfterFrameset.processCharacters = function(buffer) { var characters = buffer.takeRemaining(); var whitespace = ""; for (var i = 0; i < characters.length; i++) { var ch = characters[i]; if (isWhitespace(ch)) whitespace += ch; } if (whitespace) { tree.reconstructActiveFormattingElements(); tree.insertText(whitespace); } if (whitespace.length < characters.length) tree.parseError('expected-eof-but-got-char'); }; modes.afterAfterFrameset.startTagNoFrames = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.afterAfterFrameset.startTagOther = function(name, attributes, selfClosing) { tree.parseError('expected-eof-but-got-start-tag', {name: name}); }; modes.afterAfterFrameset.processEndTag = function(name, attributes) { tree.parseError('expected-eof-but-got-end-tag', {name: name}); }; modes.text = Object.create(modes.base); modes.text.start_tag_handlers = { '-default': 'startTagOther' }; modes.text.end_tag_handlers = { script: 'endTagScript', '-default': 'endTagOther' }; modes.text.processCharacters = function(buffer) { if (tree.shouldSkipLeadingNewline) { tree.shouldSkipLeadingNewline = false; buffer.skipAtMostOneLeadingNewline(); } var data = buffer.takeRemaining(); if (!data) return; tree.insertText(data); }; modes.text.processEOF = function() { tree.parseError("expected-named-closing-tag-but-got-eof", {name: tree.currentStackItem().localName}); tree.openElements.pop(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processEOF(); }; modes.text.startTagOther = function(name) { throw "Tried to process start tag " + name + " in RCDATA/RAWTEXT mode"; }; modes.text.endTagScript = function(name) { var node = tree.openElements.pop(); assert.ok(node.localName == 'script'); tree.setInsertionMode(tree.originalInsertionMode); }; modes.text.endTagOther = function(name) { tree.openElements.pop(); tree.setInsertionMode(tree.originalInsertionMode); }; } TreeBuilder.prototype.setInsertionMode = function(name) { this.insertionMode = this.insertionModes[name]; this.insertionModeName = name; }; TreeBuilder.prototype.adoptionAgencyEndTag = function(name) { var outerIterationLimit = 8; var innerIterationLimit = 3; var formattingElement; function isActiveFormattingElement(el) { return el === formattingElement; } var outerLoopCounter = 0; while (outerLoopCounter++ < outerIterationLimit) { formattingElement = this.elementInActiveFormattingElements(name); if (!formattingElement || (this.openElements.contains(formattingElement) && !this.openElements.inScope(formattingElement.localName))) { this.parseError('adoption-agency-1.1', {name: name}); return false; } if (!this.openElements.contains(formattingElement)) { this.parseError('adoption-agency-1.2', {name: name}); this.removeElementFromActiveFormattingElements(formattingElement); return true; } if (!this.openElements.inScope(formattingElement.localName)) { this.parseError('adoption-agency-4.4', {name: name}); } if (formattingElement != this.currentStackItem()) { this.parseError('adoption-agency-1.3', {name: name}); } var furthestBlock = this.openElements.furthestBlockForFormattingElement(formattingElement.node); if (!furthestBlock) { this.openElements.remove_openElements_until(isActiveFormattingElement); this.removeElementFromActiveFormattingElements(formattingElement); return true; } var afeIndex = this.openElements.elements.indexOf(formattingElement); var commonAncestor = this.openElements.item(afeIndex - 1); var bookmark = this.activeFormattingElements.indexOf(formattingElement); var node = furthestBlock; var lastNode = furthestBlock; var index = this.openElements.elements.indexOf(node); var innerLoopCounter = 0; while (innerLoopCounter++ < innerIterationLimit) { index -= 1; node = this.openElements.item(index); if (this.activeFormattingElements.indexOf(node) < 0) { this.openElements.elements.splice(index, 1); continue; } if (node == formattingElement) break; if (lastNode == furthestBlock) bookmark = this.activeFormattingElements.indexOf(node) + 1; var clone = this.createElement(node.namespaceURI, node.localName, node.attributes); var newNode = new StackItem(node.namespaceURI, node.localName, node.attributes, clone); this.activeFormattingElements[this.activeFormattingElements.indexOf(node)] = newNode; this.openElements.elements[this.openElements.elements.indexOf(node)] = newNode; node = newNode; this.detachFromParent(lastNode.node); this.attachNode(lastNode.node, node.node); lastNode = node; } this.detachFromParent(lastNode.node); if (commonAncestor.isFosterParenting()) { this.insertIntoFosterParent(lastNode.node); } else { this.attachNode(lastNode.node, commonAncestor.node); } var clone = this.createElement("http://www.w3.org/1999/xhtml", formattingElement.localName, formattingElement.attributes); var formattingClone = new StackItem(formattingElement.namespaceURI, formattingElement.localName, formattingElement.attributes, clone); this.reparentChildren(furthestBlock.node, clone); this.attachNode(clone, furthestBlock.node); this.removeElementFromActiveFormattingElements(formattingElement); this.activeFormattingElements.splice(Math.min(bookmark, this.activeFormattingElements.length), 0, formattingClone); this.openElements.remove(formattingElement); this.openElements.elements.splice(this.openElements.elements.indexOf(furthestBlock) + 1, 0, formattingClone); } return true; }; TreeBuilder.prototype.start = function() { throw "Not mplemented"; }; TreeBuilder.prototype.startTokenization = function(tokenizer) { this.tokenizer = tokenizer; this.compatMode = "no quirks"; this.originalInsertionMode = "initial"; this.framesetOk = true; this.openElements = new ElementStack(); this.activeFormattingElements = []; this.start(); if (this.context) { switch(this.context) { case 'title': case 'textarea': this.tokenizer.setState(Tokenizer.RCDATA); break; case 'style': case 'xmp': case 'iframe': case 'noembed': case 'noframes': this.tokenizer.setState(Tokenizer.RAWTEXT); break; case 'script': this.tokenizer.setState(Tokenizer.SCRIPT_DATA); break; case 'noscript': if (this.scriptingEnabled) this.tokenizer.setState(Tokenizer.RAWTEXT); break; case 'plaintext': this.tokenizer.setState(Tokenizer.PLAINTEXT); break; } this.insertHtmlElement(); this.resetInsertionMode(); } else { this.setInsertionMode('initial'); } }; TreeBuilder.prototype.processToken = function(token) { this.selfClosingFlagAcknowledged = false; var currentNode = this.openElements.top || null; var insertionMode; if (!currentNode || !currentNode.isForeign() || (currentNode.isMathMLTextIntegrationPoint() && ((token.type == 'StartTag' && !(token.name in {mglyph:0, malignmark:0})) || (token.type === 'Characters')) ) || (currentNode.namespaceURI == "http://www.w3.org/1998/Math/MathML" && currentNode.localName == 'annotation-xml' && token.type == 'StartTag' && token.name == 'svg' ) || (currentNode.isHtmlIntegrationPoint() && token.type in {StartTag:0, Characters:0} ) || token.type == 'EOF' ) { insertionMode = this.insertionMode; } else { insertionMode = this.insertionModes.inForeignContent; } switch(token.type) { case 'Characters': var buffer = new CharacterBuffer(token.data); insertionMode.processCharacters(buffer); break; case 'Comment': insertionMode.processComment(token.data); break; case 'StartTag': insertionMode.processStartTag(token.name, token.data, token.selfClosing); break; case 'EndTag': insertionMode.processEndTag(token.name); break; case 'Doctype': insertionMode.processDoctype(token.name, token.publicId, token.systemId, token.forceQuirks); break; case 'EOF': insertionMode.processEOF(); break; } }; TreeBuilder.prototype.isCdataSectionAllowed = function() { return this.openElements.length > 0 && this.currentStackItem().isForeign(); }; TreeBuilder.prototype.isSelfClosingFlagAcknowledged = function() { return this.selfClosingFlagAcknowledged; }; TreeBuilder.prototype.createElement = function(namespaceURI, localName, attributes) { throw new Error("Not implemented"); }; TreeBuilder.prototype.attachNode = function(child, parent) { throw new Error("Not implemented"); }; TreeBuilder.prototype.attachNodeToFosterParent = function(child, table, stackParent) { throw new Error("Not implemented"); }; TreeBuilder.prototype.detachFromParent = function(node) { throw new Error("Not implemented"); }; TreeBuilder.prototype.addAttributesToElement = function(element, attributes) { throw new Error("Not implemented"); }; TreeBuilder.prototype.insertHtmlElement = function(attributes) { var root = this.createElement("http://www.w3.org/1999/xhtml", 'html', attributes); this.attachNode(root, this.document); this.openElements.pushHtmlElement(new StackItem("http://www.w3.org/1999/xhtml", 'html', attributes, root)); return root; }; TreeBuilder.prototype.insertHeadElement = function(attributes) { var element = this.createElement("http://www.w3.org/1999/xhtml", "head", attributes); this.head = new StackItem("http://www.w3.org/1999/xhtml", "head", attributes, element); this.attachNode(element, this.openElements.top.node); this.openElements.pushHeadElement(this.head); return element; }; TreeBuilder.prototype.insertBodyElement = function(attributes) { var element = this.createElement("http://www.w3.org/1999/xhtml", "body", attributes); this.attachNode(element, this.openElements.top.node); this.openElements.pushBodyElement(new StackItem("http://www.w3.org/1999/xhtml", "body", attributes, element)); return element; }; TreeBuilder.prototype.insertIntoFosterParent = function(node) { var tableIndex = this.openElements.findIndex('table'); var tableElement = this.openElements.item(tableIndex).node; if (tableIndex === 0) return this.attachNode(node, tableElement); this.attachNodeToFosterParent(node, tableElement, this.openElements.item(tableIndex - 1).node); }; TreeBuilder.prototype.insertElement = function(name, attributes, namespaceURI, selfClosing) { if (!namespaceURI) namespaceURI = "http://www.w3.org/1999/xhtml"; var element = this.createElement(namespaceURI, name, attributes); if (this.shouldFosterParent()) this.insertIntoFosterParent(element); else this.attachNode(element, this.openElements.top.node); if (!selfClosing) this.openElements.push(new StackItem(namespaceURI, name, attributes, element)); }; TreeBuilder.prototype.insertFormattingElement = function(name, attributes) { this.insertElement(name, attributes, "http://www.w3.org/1999/xhtml"); this.appendElementToActiveFormattingElements(this.currentStackItem()); }; TreeBuilder.prototype.insertSelfClosingElement = function(name, attributes) { this.selfClosingFlagAcknowledged = true; this.insertElement(name, attributes, "http://www.w3.org/1999/xhtml", true); }; TreeBuilder.prototype.insertForeignElement = function(name, attributes, namespaceURI, selfClosing) { if (selfClosing) this.selfClosingFlagAcknowledged = true; this.insertElement(name, attributes, namespaceURI, selfClosing); }; TreeBuilder.prototype.insertComment = function(data, parent) { throw new Error("Not implemented"); }; TreeBuilder.prototype.insertDoctype = function(name, publicId, systemId) { throw new Error("Not implemented"); }; TreeBuilder.prototype.insertText = function(data) { throw new Error("Not implemented"); }; TreeBuilder.prototype.currentStackItem = function() { return this.openElements.top; }; TreeBuilder.prototype.popElement = function() { return this.openElements.pop(); }; TreeBuilder.prototype.shouldFosterParent = function() { return this.redirectAttachToFosterParent && this.currentStackItem().isFosterParenting(); }; TreeBuilder.prototype.generateImpliedEndTags = function(exclude) { var name = this.openElements.top.localName; if (['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'].indexOf(name) != -1 && name != exclude) { this.popElement(); this.generateImpliedEndTags(exclude); } }; TreeBuilder.prototype.reconstructActiveFormattingElements = function() { if (this.activeFormattingElements.length === 0) return; var i = this.activeFormattingElements.length - 1; var entry = this.activeFormattingElements[i]; if (entry == Marker || this.openElements.contains(entry)) return; while (entry != Marker && !this.openElements.contains(entry)) { i -= 1; entry = this.activeFormattingElements[i]; if (!entry) break; } while (true) { i += 1; entry = this.activeFormattingElements[i]; this.insertElement(entry.localName, entry.attributes); var element = this.currentStackItem(); this.activeFormattingElements[i] = element; if (element == this.activeFormattingElements[this.activeFormattingElements.length -1]) break; } }; TreeBuilder.prototype.ensureNoahsArkCondition = function(item) { var kNoahsArkCapacity = 3; if (this.activeFormattingElements.length < kNoahsArkCapacity) return; var candidates = []; var newItemAttributeCount = item.attributes.length; for (var i = this.activeFormattingElements.length - 1; i >= 0; i--) { var candidate = this.activeFormattingElements[i]; if (candidate === Marker) break; if (item.localName !== candidate.localName || item.namespaceURI !== candidate.namespaceURI) continue; if (candidate.attributes.length != newItemAttributeCount) continue; candidates.push(candidate); } if (candidates.length < kNoahsArkCapacity) return; var remainingCandidates = []; var attributes = item.attributes; for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; for (var j = 0; j < candidates.length; j++) { var candidate = candidates[j]; var candidateAttribute = getAttribute(candidate, attribute.nodeName); if (candidateAttribute && candidateAttribute.nodeValue === attribute.nodeValue) remainingCandidates.push(candidate); } if (remainingCandidates.length < kNoahsArkCapacity) return; candidates = remainingCandidates; remainingCandidates = []; } for (var i = kNoahsArkCapacity - 1; i < candidates.length; i++) this.removeElementFromActiveFormattingElements(candidates[i]); }; TreeBuilder.prototype.appendElementToActiveFormattingElements = function(item) { this.ensureNoahsArkCondition(item); this.activeFormattingElements.push(item); }; TreeBuilder.prototype.removeElementFromActiveFormattingElements = function(item) { var index = this.activeFormattingElements.indexOf(item); if (index >= 0) this.activeFormattingElements.splice(index, 1); }; TreeBuilder.prototype.elementInActiveFormattingElements = function(name) { var els = this.activeFormattingElements; for (var i = els.length - 1; i >= 0; i--) { if (els[i] == Marker) break; if (els[i].localName == name) return els[i]; } return false; }; TreeBuilder.prototype.clearActiveFormattingElements = function() { while (!(this.activeFormattingElements.length === 0 || this.activeFormattingElements.pop() == Marker)); }; TreeBuilder.prototype.reparentChildren = function(oldParent, newParent) { throw new Error("Not implemented"); }; TreeBuilder.prototype.setFragmentContext = function(context) { this.context = context; }; TreeBuilder.prototype.parseError = function(code, args) { if (!this.errorHandler) return; var message = formatMessage(messages[code], args); this.errorHandler.error(message, this.tokenizer._inputStream.location(), code); }; TreeBuilder.prototype.resetInsertionMode = function() { var last = false; var node = null; for (var i = this.openElements.length - 1; i >= 0; i--) { node = this.openElements.item(i); if (i === 0) { assert.ok(this.context); last = true; node = new StackItem("http://www.w3.org/1999/xhtml", this.context, [], null); } if (node.namespaceURI === "http://www.w3.org/1999/xhtml") { if (node.localName === 'select') return this.setInsertionMode('inSelect'); if (node.localName === 'td' || node.localName === 'th') return this.setInsertionMode('inCell'); if (node.localName === 'tr') return this.setInsertionMode('inRow'); if (node.localName === 'tbody' || node.localName === 'thead' || node.localName === 'tfoot') return this.setInsertionMode('inTableBody'); if (node.localName === 'caption') return this.setInsertionMode('inCaption'); if (node.localName === 'colgroup') return this.setInsertionMode('inColumnGroup'); if (node.localName === 'table') return this.setInsertionMode('inTable'); if (node.localName === 'head' && !last) return this.setInsertionMode('inHead'); if (node.localName === 'body') return this.setInsertionMode('inBody'); if (node.localName === 'frameset') return this.setInsertionMode('inFrameset'); if (node.localName === 'html') if (!this.openElements.headElement) return this.setInsertionMode('beforeHead'); else return this.setInsertionMode('afterHead'); } if (last) return this.setInsertionMode('inBody'); } }; TreeBuilder.prototype.processGenericRCDATAStartTag = function(name, attributes) { this.insertElement(name, attributes); this.tokenizer.setState(Tokenizer.RCDATA); this.originalInsertionMode = this.insertionModeName; this.setInsertionMode('text'); }; TreeBuilder.prototype.processGenericRawTextStartTag = function(name, attributes) { this.insertElement(name, attributes); this.tokenizer.setState(Tokenizer.RAWTEXT); this.originalInsertionMode = this.insertionModeName; this.setInsertionMode('text'); }; TreeBuilder.prototype.adjustMathMLAttributes = function(attributes) { attributes.forEach(function(a) { a.namespaceURI = "http://www.w3.org/1998/Math/MathML"; if (constants.MATHMLAttributeMap[a.nodeName]) a.nodeName = constants.MATHMLAttributeMap[a.nodeName]; }); return attributes; }; TreeBuilder.prototype.adjustSVGTagNameCase = function(name) { return constants.SVGTagMap[name] || name; }; TreeBuilder.prototype.adjustSVGAttributes = function(attributes) { attributes.forEach(function(a) { a.namespaceURI = "http://www.w3.org/2000/svg"; if (constants.SVGAttributeMap[a.nodeName]) a.nodeName = constants.SVGAttributeMap[a.nodeName]; }); return attributes; }; TreeBuilder.prototype.adjustForeignAttributes = function(attributes) { for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; var adjusted = constants.ForeignAttributeMap[attribute.nodeName]; if (adjusted) { attribute.nodeName = adjusted.localName; attribute.prefix = adjusted.prefix; attribute.namespaceURI = adjusted.namespaceURI; } } return attributes; }; function formatMessage(format, args) { return format.replace(new RegExp('{[0-9a-z-]+}', 'gi'), function(match) { return args[match.slice(1, -1)] || match; }); } exports.TreeBuilder = TreeBuilder; }, {"./ElementStack":1,"./StackItem":4,"./Tokenizer":5,"./constants":7,"./messages.json":8,"assert":13,"events":16}], 7:[function(_dereq_,module,exports){ exports.SVGTagMap = { "altglyph": "altGlyph", "altglyphdef": "altGlyphDef", "altglyphitem": "altGlyphItem", "animatecolor": "animateColor", "animatemotion": "animateMotion", "animatetransform": "animateTransform", "clippath": "clipPath", "feblend": "feBlend", "fecolormatrix": "feColorMatrix", "fecomponenttransfer": "feComponentTransfer", "fecomposite": "feComposite", "feconvolvematrix": "feConvolveMatrix", "fediffuselighting": "feDiffuseLighting", "fedisplacementmap": "feDisplacementMap", "fedistantlight": "feDistantLight", "feflood": "feFlood", "fefunca": "feFuncA", "fefuncb": "feFuncB", "fefuncg": "feFuncG", "fefuncr": "feFuncR", "fegaussianblur": "feGaussianBlur", "feimage": "feImage", "femerge": "feMerge", "femergenode": "feMergeNode", "femorphology": "feMorphology", "feoffset": "feOffset", "fepointlight": "fePointLight", "fespecularlighting": "feSpecularLighting", "fespotlight": "feSpotLight", "fetile": "feTile", "feturbulence": "feTurbulence", "foreignobject": "foreignObject", "glyphref": "glyphRef", "lineargradient": "linearGradient", "radialgradient": "radialGradient", "textpath": "textPath" }; exports.MATHMLAttributeMap = { definitionurl: 'definitionURL' }; exports.SVGAttributeMap = { attributename: 'attributeName', attributetype: 'attributeType', basefrequency: 'baseFrequency', baseprofile: 'baseProfile', calcmode: 'calcMode', clippathunits: 'clipPathUnits', contentscripttype: 'contentScriptType', contentstyletype: 'contentStyleType', diffuseconstant: 'diffuseConstant', edgemode: 'edgeMode', externalresourcesrequired: 'externalResourcesRequired', filterres: 'filterRes', filterunits: 'filterUnits', glyphref: 'glyphRef', gradienttransform: 'gradientTransform', gradientunits: 'gradientUnits', kernelmatrix: 'kernelMatrix', kernelunitlength: 'kernelUnitLength', keypoints: 'keyPoints', keysplines: 'keySplines', keytimes: 'keyTimes', lengthadjust: 'lengthAdjust', limitingconeangle: 'limitingConeAngle', markerheight: 'markerHeight', markerunits: 'markerUnits', markerwidth: 'markerWidth', maskcontentunits: 'maskContentUnits', maskunits: 'maskUnits', numoctaves: 'numOctaves', pathlength: 'pathLength', patterncontentunits: 'patternContentUnits', patterntransform: 'patternTransform', patternunits: 'patternUnits', pointsatx: 'pointsAtX', pointsaty: 'pointsAtY', pointsatz: 'pointsAtZ', preservealpha: 'preserveAlpha', preserveaspectratio: 'preserveAspectRatio', primitiveunits: 'primitiveUnits', refx: 'refX', refy: 'refY', repeatcount: 'repeatCount', repeatdur: 'repeatDur', requiredextensions: 'requiredExtensions', requiredfeatures: 'requiredFeatures', specularconstant: 'specularConstant', specularexponent: 'specularExponent', spreadmethod: 'spreadMethod', startoffset: 'startOffset', stddeviation: 'stdDeviation', stitchtiles: 'stitchTiles', surfacescale: 'surfaceScale', systemlanguage: 'systemLanguage', tablevalues: 'tableValues', targetx: 'targetX', targety: 'targetY', textlength: 'textLength', viewbox: 'viewBox', viewtarget: 'viewTarget', xchannelselector: 'xChannelSelector', ychannelselector: 'yChannelSelector', zoomandpan: 'zoomAndPan' }; exports.ForeignAttributeMap = { "xlink:actuate": {prefix: "xlink", localName: "actuate", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:arcrole": {prefix: "xlink", localName: "arcrole", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:href": {prefix: "xlink", localName: "href", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:role": {prefix: "xlink", localName: "role", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:show": {prefix: "xlink", localName: "show", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:title": {prefix: "xlink", localName: "title", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:type": {prefix: "xlink", localName: "title", namespaceURI: "http://www.w3.org/1999/xlink"}, "xml:base": {prefix: "xml", localName: "base", namespaceURI: "http://www.w3.org/XML/1998/namespace"}, "xml:lang": {prefix: "xml", localName: "lang", namespaceURI: "http://www.w3.org/XML/1998/namespace"}, "xml:space": {prefix: "xml", localName: "space", namespaceURI: "http://www.w3.org/XML/1998/namespace"}, "xmlns": {prefix: null, localName: "xmlns", namespaceURI: "http://www.w3.org/2000/xmlns/"}, "xmlns:xlink": {prefix: "xmlns", localName: "xlink", namespaceURI: "http://www.w3.org/2000/xmlns/"}, }; }, {}], 8:[function(_dereq_,module,exports){ module.exports={ "null-character": "Null character in input stream, replaced with U+FFFD.", "invalid-codepoint": "Invalid codepoint in stream", "incorrectly-placed-solidus": "Solidus (/) incorrectly placed in tag.", "incorrect-cr-newline-entity": "Incorrect CR newline entity, replaced with LF.", "illegal-windows-1252-entity": "Entity used with illegal number (windows-1252 reference).", "cant-convert-numeric-entity": "Numeric entity couldn't be converted to character (codepoint U+{charAsInt}).", "invalid-numeric-entity-replaced": "Numeric entity represents an illegal codepoint. Expanded to the C1 controls range.", "numeric-entity-without-semicolon": "Numeric entity didn't end with ';'.", "expected-numeric-entity-but-got-eof": "Numeric entity expected. Got end of file instead.", "expected-numeric-entity": "Numeric entity expected but none found.", "named-entity-without-semicolon": "Named entity didn't end with ';'.", "expected-named-entity": "Named entity expected. Got none.", "attributes-in-end-tag": "End tag contains unexpected attributes.", "self-closing-flag-on-end-tag": "End tag contains unexpected self-closing flag.", "bare-less-than-sign-at-eof": "End of file after <.", "expected-tag-name-but-got-right-bracket": "Expected tag name. Got '>' instead.", "expected-tag-name-but-got-question-mark": "Expected tag name. Got '?' instead. (HTML doesn't support processing instructions.)", "expected-tag-name": "Expected tag name. Got something else instead.", "expected-closing-tag-but-got-right-bracket": "Expected closing tag. Got '>' instead. Ignoring '</>'.", "expected-closing-tag-but-got-eof": "Expected closing tag. Unexpected end of file.", "expected-closing-tag-but-got-char": "Expected closing tag. Unexpected character '{data}' found.", "eof-in-tag-name": "Unexpected end of file in the tag name.", "expected-attribute-name-but-got-eof": "Unexpected end of file. Expected attribute name instead.", "eof-in-attribute-name": "Unexpected end of file in attribute name.", "invalid-character-in-attribute-name": "Invalid character in attribute name.", "duplicate-attribute": "Dropped duplicate attribute '{name}' on tag.", "expected-end-of-tag-but-got-eof": "Unexpected end of file. Expected = or end of tag.", "expected-attribute-value-but-got-eof": "Unexpected end of file. Expected attribute value.", "expected-attribute-value-but-got-right-bracket": "Expected attribute value. Got '>' instead.", "unexpected-character-in-unquoted-attribute-value": "Unexpected character in unquoted attribute", "invalid-character-after-attribute-name": "Unexpected character after attribute name.", "unexpected-character-after-attribute-value": "Unexpected character after attribute value.", "eof-in-attribute-value-double-quote": "Unexpected end of file in attribute value (\").", "eof-in-attribute-value-single-quote": "Unexpected end of file in attribute value (').", "eof-in-attribute-value-no-quotes": "Unexpected end of file in attribute value.", "eof-after-attribute-value": "Unexpected end of file after attribute value.", "unexpected-eof-after-solidus-in-tag": "Unexpected end of file in tag. Expected >.", "unexpected-character-after-solidus-in-tag": "Unexpected character after / in tag. Expected >.", "expected-dashes-or-doctype": "Expected '--' or 'DOCTYPE'. Not found.", "unexpected-bang-after-double-dash-in-comment": "Unexpected ! after -- in comment.", "incorrect-comment": "Incorrect comment.", "eof-in-comment": "Unexpected end of file in comment.", "eof-in-comment-end-dash": "Unexpected end of file in comment (-).", "unexpected-dash-after-double-dash-in-comment": "Unexpected '-' after '--' found in comment.", "eof-in-comment-double-dash": "Unexpected end of file in comment (--).", "eof-in-comment-end-bang-state": "Unexpected end of file in comment.", "unexpected-char-in-comment": "Unexpected character in comment found.", "need-space-after-doctype": "No space after literal string 'DOCTYPE'.", "expected-doctype-name-but-got-right-bracket": "Unexpected > character. Expected DOCTYPE name.", "expected-doctype-name-but-got-eof": "Unexpected end of file. Expected DOCTYPE name.", "eof-in-doctype-name": "Unexpected end of file in DOCTYPE name.", "eof-in-doctype": "Unexpected end of file in DOCTYPE.", "expected-space-or-right-bracket-in-doctype": "Expected space or '>'. Got '{data}'.", "unexpected-end-of-doctype": "Unexpected end of DOCTYPE.", "unexpected-char-in-doctype": "Unexpected character in DOCTYPE.", "eof-in-bogus-doctype": "Unexpected end of file in bogus doctype.", "eof-in-innerhtml": "Unexpected EOF in inner html mode.", "unexpected-doctype": "Unexpected DOCTYPE. Ignored.", "non-html-root": "html needs to be the first start tag.", "expected-doctype-but-got-eof": "Unexpected End of file. Expected DOCTYPE.", "unknown-doctype": "Erroneous DOCTYPE. Expected <!DOCTYPE html>.", "quirky-doctype": "Quirky doctype. Expected <!DOCTYPE html>.", "almost-standards-doctype": "Almost standards mode doctype. Expected <!DOCTYPE html>.", "obsolete-doctype": "Obsolete doctype. Expected <!DOCTYPE html>.", "expected-doctype-but-got-chars": "Non-space characters found without seeing a doctype first. Expected e.g. <!DOCTYPE html>.", "expected-doctype-but-got-start-tag": "Start tag seen without seeing a doctype first. Expected e.g. <!DOCTYPE html>.", "expected-doctype-but-got-end-tag": "End tag seen without seeing a doctype first. Expected e.g. <!DOCTYPE html>.", "end-tag-after-implied-root": "Unexpected end tag ({name}) after the (implied) root element.", "expected-named-closing-tag-but-got-eof": "Unexpected end of file. Expected end tag ({name}).", "two-heads-are-not-better-than-one": "Unexpected start tag head in existing head. Ignored.", "unexpected-end-tag": "Unexpected end tag ({name}). Ignored.", "unexpected-implied-end-tag": "End tag {name} implied, but there were open elements.", "unexpected-start-tag-out-of-my-head": "Unexpected start tag ({name}) that can be in head. Moved.", "unexpected-start-tag": "Unexpected start tag ({name}).", "missing-end-tag": "Missing end tag ({name}).", "missing-end-tags": "Missing end tags ({name}).", "unexpected-start-tag-implies-end-tag": "Unexpected start tag ({startName}) implies end tag ({endName}).", "unexpected-start-tag-treated-as": "Unexpected start tag ({originalName}). Treated as {newName}.", "deprecated-tag": "Unexpected start tag {name}. Don't use it!", "unexpected-start-tag-ignored": "Unexpected start tag {name}. Ignored.", "expected-one-end-tag-but-got-another": "Unexpected end tag ({gotName}). Missing end tag ({expectedName}).", "end-tag-too-early": "End tag ({name}) seen too early. Expected other end tag.", "end-tag-too-early-named": "Unexpected end tag ({gotName}). Expected end tag ({expectedName}.", "end-tag-too-early-ignored": "End tag ({name}) seen too early. Ignored.", "adoption-agency-1.1": "End tag ({name}) violates step 1, paragraph 1 of the adoption agency algorithm.", "adoption-agency-1.2": "End tag ({name}) violates step 1, paragraph 2 of the adoption agency algorithm.", "adoption-agency-1.3": "End tag ({name}) violates step 1, paragraph 3 of the adoption agency algorithm.", "adoption-agency-4.4": "End tag ({name}) violates step 4, paragraph 4 of the adoption agency algorithm.", "unexpected-end-tag-treated-as": "Unexpected end tag ({originalName}). Treated as {newName}.", "no-end-tag": "This element ({name}) has no end tag.", "unexpected-implied-end-tag-in-table": "Unexpected implied end tag ({name}) in the table phase.", "unexpected-implied-end-tag-in-table-body": "Unexpected implied end tag ({name}) in the table body phase.", "unexpected-char-implies-table-voodoo": "Unexpected non-space characters in table context caused voodoo mode.", "unexpected-hidden-input-in-table": "Unexpected input with type hidden in table context.", "unexpected-form-in-table": "Unexpected form in table context.", "unexpected-start-tag-implies-table-voodoo": "Unexpected start tag ({name}) in table context caused voodoo mode.", "unexpected-end-tag-implies-table-voodoo": "Unexpected end tag ({name}) in table context caused voodoo mode.", "unexpected-cell-in-table-body": "Unexpected table cell start tag ({name}) in the table body phase.", "unexpected-cell-end-tag": "Got table cell end tag ({name}) while required end tags are missing.", "unexpected-end-tag-in-table-body": "Unexpected end tag ({name}) in the table body phase. Ignored.", "unexpected-implied-end-tag-in-table-row": "Unexpected implied end tag ({name}) in the table row phase.", "unexpected-end-tag-in-table-row": "Unexpected end tag ({name}) in the table row phase. Ignored.", "unexpected-select-in-select": "Unexpected select start tag in the select phase treated as select end tag.", "unexpected-input-in-select": "Unexpected input start tag in the select phase.", "unexpected-start-tag-in-select": "Unexpected start tag token ({name}) in the select phase. Ignored.", "unexpected-end-tag-in-select": "Unexpected end tag ({name}) in the select phase. Ignored.", "unexpected-table-element-start-tag-in-select-in-table": "Unexpected table element start tag ({name}) in the select in table phase.", "unexpected-table-element-end-tag-in-select-in-table": "Unexpected table element end tag ({name}) in the select in table phase.", "unexpected-char-after-body": "Unexpected non-space characters in the after body phase.", "unexpected-start-tag-after-body": "Unexpected start tag token ({name}) in the after body phase.", "unexpected-end-tag-after-body": "Unexpected end tag token ({name}) in the after body phase.", "unexpected-char-in-frameset": "Unepxected characters in the frameset phase. Characters ignored.", "unexpected-start-tag-in-frameset": "Unexpected start tag token ({name}) in the frameset phase. Ignored.", "unexpected-frameset-in-frameset-innerhtml": "Unexpected end tag token (frameset in the frameset phase (innerHTML).", "unexpected-end-tag-in-frameset": "Unexpected end tag token ({name}) in the frameset phase. Ignored.", "unexpected-char-after-frameset": "Unexpected non-space characters in the after frameset phase. Ignored.", "unexpected-start-tag-after-frameset": "Unexpected start tag ({name}) in the after frameset phase. Ignored.", "unexpected-end-tag-after-frameset": "Unexpected end tag ({name}) in the after frameset phase. Ignored.", "expected-eof-but-got-char": "Unexpected non-space characters. Expected end of file.", "expected-eof-but-got-start-tag": "Unexpected start tag ({name}). Expected end of file.", "expected-eof-but-got-end-tag": "Unexpected end tag ({name}). Expected end of file.", "unexpected-end-table-in-caption": "Unexpected end table tag in caption. Generates implied end caption.", "end-html-in-innerhtml": "Unexpected html end tag in inner html mode.", "eof-in-table": "Unexpected end of file. Expected table content.", "eof-in-script": "Unexpected end of file. Expected script content.", "non-void-element-with-trailing-solidus": "Trailing solidus not allowed on element {name}.", "unexpected-html-element-in-foreign-content": "HTML start tag \"{name}\" in a foreign namespace context.", "unexpected-start-tag-in-table": "Unexpected {name}. Expected table content." } }, {}], 9:[function(_dereq_,module,exports){ var SAXTreeBuilder = _dereq_('./SAXTreeBuilder').SAXTreeBuilder; var Tokenizer = _dereq_('../Tokenizer').Tokenizer; var TreeParser = _dereq_('./TreeParser').TreeParser; function SAXParser() { this.contentHandler = null; this._errorHandler = null; this._treeBuilder = new SAXTreeBuilder(); this._tokenizer = new Tokenizer(this._treeBuilder); this._scriptingEnabled = false; } SAXParser.prototype.parse = function(source) { this._tokenizer.tokenize(source); var document = this._treeBuilder.document; if (document) { new TreeParser(this.contentHandler).parse(document); } }; SAXParser.prototype.parseFragment = function(source, context) { this._treeBuilder.setFragmentContext(context); this._tokenizer.tokenize(source); var fragment = this._treeBuilder.getFragment(); if (fragment) { new TreeParser(this.contentHandler).parse(fragment); } }; Object.defineProperty(SAXParser.prototype, 'scriptingEnabled', { get: function() { return this._scriptingEnabled; }, set: function(value) { this._scriptingEnabled = value; this._treeBuilder.scriptingEnabled = value; } }); Object.defineProperty(SAXParser.prototype, 'errorHandler', { get: function() { return this._errorHandler; }, set: function(value) { this._errorHandler = value; this._treeBuilder.errorHandler = value; } }); exports.SAXParser = SAXParser; }, {"../Tokenizer":5,"./SAXTreeBuilder":10,"./TreeParser":11}], 10:[function(_dereq_,module,exports){ var util = _dereq_('util'); var TreeBuilder = _dereq_('../TreeBuilder').TreeBuilder; function SAXTreeBuilder() { TreeBuilder.call(this); } util.inherits(SAXTreeBuilder, TreeBuilder); SAXTreeBuilder.prototype.start = function(tokenizer) { this.document = new Document(this.tokenizer); }; SAXTreeBuilder.prototype.end = function() { this.document.endLocator = this.tokenizer; }; SAXTreeBuilder.prototype.insertDoctype = function(name, publicId, systemId) { var doctype = new DTD(this.tokenizer, name, publicId, systemId); doctype.endLocator = this.tokenizer; this.document.appendChild(doctype); }; SAXTreeBuilder.prototype.createElement = function(namespaceURI, localName, attributes) { var element = new Element(this.tokenizer, namespaceURI, localName, localName, attributes || []); return element; }; SAXTreeBuilder.prototype.insertComment = function(data, parent) { if (!parent) parent = this.currentStackItem(); var comment = new Comment(this.tokenizer, data); parent.appendChild(comment); }; SAXTreeBuilder.prototype.appendCharacters = function(parent, data) { var text = new Characters(this.tokenizer, data); parent.appendChild(text); }; SAXTreeBuilder.prototype.insertText = function(data) { if (this.redirectAttachToFosterParent && this.openElements.top.isFosterParenting()) { var tableIndex = this.openElements.findIndex('table'); var tableItem = this.openElements.item(tableIndex); var table = tableItem.node; if (tableIndex === 0) { return this.appendCharacters(table, data); } var text = new Characters(this.tokenizer, data); var parent = table.parentNode; if (parent) { parent.insertBetween(text, table.previousSibling, table); return; } var stackParent = this.openElements.item(tableIndex - 1).node; stackParent.appendChild(text); return; } this.appendCharacters(this.currentStackItem().node, data); }; SAXTreeBuilder.prototype.attachNode = function(node, parent) { parent.appendChild(node); }; SAXTreeBuilder.prototype.attachNodeToFosterParent = function(child, table, stackParent) { var parent = table.parentNode; if (parent) parent.insertBetween(child, table.previousSibling, table); else stackParent.appendChild(child); }; SAXTreeBuilder.prototype.detachFromParent = function(element) { element.detach(); }; SAXTreeBuilder.prototype.reparentChildren = function(oldParent, newParent) { newParent.appendChildren(oldParent.firstChild); }; SAXTreeBuilder.prototype.getFragment = function() { var fragment = new DocumentFragment(); this.reparentChildren(this.openElements.rootNode, fragment); return fragment; }; function getAttribute(node, name) { for (var i = 0; i < node.attributes.length; i++) { var attribute = node.attributes[i]; if (attribute.nodeName === name) return attribute.nodeValue; } } SAXTreeBuilder.prototype.addAttributesToElement = function(element, attributes) { for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; if (!getAttribute(element, attribute.nodeName)) element.attributes.push(attribute); } }; var NodeType = { CDATA: 1, CHARACTERS: 2, COMMENT: 3, DOCUMENT: 4, DOCUMENT_FRAGMENT: 5, DTD: 6, ELEMENT: 7, ENTITY: 8, IGNORABLE_WHITESPACE: 9, PROCESSING_INSTRUCTION: 10, SKIPPED_ENTITY: 11 }; function Node(locator) { if (!locator) { this.columnNumber = -1; this.lineNumber = -1; } else { this.columnNumber = locator.columnNumber; this.lineNumber = locator.lineNumber; } this.parentNode = null; this.nextSibling = null; this.firstChild = null; } Node.prototype.visit = function(treeParser) { throw new Error("Not Implemented"); }; Node.prototype.revisit = function(treeParser) { return; }; Node.prototype.detach = function() { if (this.parentNode !== null) { this.parentNode.removeChild(this); this.parentNode = null; } }; Object.defineProperty(Node.prototype, 'previousSibling', { get: function() { var prev = null; var next = this.parentNode.firstChild; for(;;) { if (this == next) { return prev; } prev = next; next = next.nextSibling; } } }); function ParentNode(locator) { Node.call(this, locator); this.lastChild = null; this._endLocator = null; } ParentNode.prototype = Object.create(Node.prototype); ParentNode.prototype.insertBefore = function(child, sibling) { if (!sibling) { return this.appendChild(child); } child.detach(); child.parentNode = this; if (this.firstChild == sibling) { child.nextSibling = sibling; this.firstChild = child; } else { var prev = this.firstChild; var next = this.firstChild.nextSibling; while (next != sibling) { prev = next; next = next.nextSibling; } prev.nextSibling = child; child.nextSibling = next; } return child; }; ParentNode.prototype.insertBetween = function(child, prev, next) { if (!next) { return this.appendChild(child); } child.detach(); child.parentNode = this; child.nextSibling = next; if (!prev) { firstChild = child; } else { prev.nextSibling = child; } return child; }; ParentNode.prototype.appendChild = function(child) { child.detach(); child.parentNode = this; if (!this.firstChild) { this.firstChild = child; } else { this.lastChild.nextSibling = child; } this.lastChild = child; return child; }; ParentNode.prototype.appendChildren = function(parent) { var child = parent.firstChild; if (!child) { return; } var another = parent; if (!this.firstChild) { this.firstChild = child; } else { this.lastChild.nextSibling = child; } this.lastChild = another.lastChild; do { child.parentNode = this; } while ((child = child.nextSibling)); another.firstChild = null; another.lastChild = null; }; ParentNode.prototype.removeChild = function(node) { if (this.firstChild == node) { this.firstChild = node.nextSibling; if (this.lastChild == node) { this.lastChild = null; } } else { var prev = this.firstChild; var next = this.firstChild.nextSibling; while (next != node) { prev = next; next = next.nextSibling; } prev.nextSibling = node.nextSibling; if (this.lastChild == node) { this.lastChild = prev; } } node.parentNode = null; return node; }; Object.defineProperty(ParentNode.prototype, 'endLocator', { get: function() { return this._endLocator; }, set: function(endLocator) { this._endLocator = { lineNumber: endLocator.lineNumber, columnNumber: endLocator.columnNumber }; } }); function Document (locator) { ParentNode.call(this, locator); this.nodeType = NodeType.DOCUMENT; } Document.prototype = Object.create(ParentNode.prototype); Document.prototype.visit = function(treeParser) { treeParser.startDocument(this); }; Document.prototype.revisit = function(treeParser) { treeParser.endDocument(this.endLocator); }; function DocumentFragment() { ParentNode.call(this, new Locator()); this.nodeType = NodeType.DOCUMENT_FRAGMENT; } DocumentFragment.prototype = Object.create(ParentNode.prototype); DocumentFragment.prototype.visit = function(treeParser) { }; function Element(locator, uri, localName, qName, atts, prefixMappings) { ParentNode.call(this, locator); this.uri = uri; this.localName = localName; this.qName = qName; this.attributes = atts; this.prefixMappings = prefixMappings; this.nodeType = NodeType.ELEMENT; } Element.prototype = Object.create(ParentNode.prototype); Element.prototype.visit = function(treeParser) { if (this.prefixMappings) { for (var key in prefixMappings) { var mapping = prefixMappings[key]; treeParser.startPrefixMapping(mapping.getPrefix(), mapping.getUri(), this); } } treeParser.startElement(this.uri, this.localName, this.qName, this.attributes, this); }; Element.prototype.revisit = function(treeParser) { treeParser.endElement(this.uri, this.localName, this.qName, this.endLocator); if (this.prefixMappings) { for (var key in prefixMappings) { var mapping = prefixMappings[key]; treeParser.endPrefixMapping(mapping.getPrefix(), this.endLocator); } } }; function Characters(locator, data){ Node.call(this, locator); this.data = data; this.nodeType = NodeType.CHARACTERS; } Characters.prototype = Object.create(Node.prototype); Characters.prototype.visit = function (treeParser) { treeParser.characters(this.data, 0, this.data.length, this); }; function IgnorableWhitespace(locator, data) { Node.call(this, locator); this.data = data; this.nodeType = NodeType.IGNORABLE_WHITESPACE; } IgnorableWhitespace.prototype = Object.create(Node.prototype); IgnorableWhitespace.prototype.visit = function(treeParser) { treeParser.ignorableWhitespace(this.data, 0, this.data.length, this); }; function Comment(locator, data) { Node.call(this, locator); this.data = data; this.nodeType = NodeType.COMMENT; } Comment.prototype = Object.create(Node.prototype); Comment.prototype.visit = function(treeParser) { treeParser.comment(this.data, 0, this.data.length, this); }; function CDATA(locator) { ParentNode.call(this, locator); this.nodeType = NodeType.CDATA; } CDATA.prototype = Object.create(ParentNode.prototype); CDATA.prototype.visit = function(treeParser) { treeParser.startCDATA(this); }; CDATA.prototype.revisit = function(treeParser) { treeParser.endCDATA(this.endLocator); }; function Entity(name) { ParentNode.call(this); this.name = name; this.nodeType = NodeType.ENTITY; } Entity.prototype = Object.create(ParentNode.prototype); Entity.prototype.visit = function(treeParser) { treeParser.startEntity(this.name, this); }; Entity.prototype.revisit = function(treeParser) { treeParser.endEntity(this.name); }; function SkippedEntity(name) { Node.call(this); this.name = name; this.nodeType = NodeType.SKIPPED_ENTITY; } SkippedEntity.prototype = Object.create(Node.prototype); SkippedEntity.prototype.visit = function(treeParser) { treeParser.skippedEntity(this.name, this); }; function ProcessingInstruction(target, data) { Node.call(this); this.target = target; this.data = data; } ProcessingInstruction.prototype = Object.create(Node.prototype); ProcessingInstruction.prototype.visit = function(treeParser) { treeParser.processingInstruction(this.target, this.data, this); }; ProcessingInstruction.prototype.getNodeType = function() { return NodeType.PROCESSING_INSTRUCTION; }; function DTD(name, publicIdentifier, systemIdentifier) { ParentNode.call(this); this.name = name; this.publicIdentifier = publicIdentifier; this.systemIdentifier = systemIdentifier; this.nodeType = NodeType.DTD; } DTD.prototype = Object.create(ParentNode.prototype); DTD.prototype.visit = function(treeParser) { treeParser.startDTD(this.name, this.publicIdentifier, this.systemIdentifier, this); }; DTD.prototype.revisit = function(treeParser) { treeParser.endDTD(); }; exports.SAXTreeBuilder = SAXTreeBuilder; }, {"../TreeBuilder":6,"util":20}], 11:[function(_dereq_,module,exports){ function TreeParser(contentHandler, lexicalHandler){ this.contentHandler; this.lexicalHandler; this.locatorDelegate; if (!contentHandler) { throw new IllegalArgumentException("contentHandler was null."); } this.contentHandler = contentHandler; if (!lexicalHandler) { this.lexicalHandler = new NullLexicalHandler(); } else { this.lexicalHandler = lexicalHandler; } } TreeParser.prototype.parse = function(node) { this.contentHandler.documentLocator = this; var current = node; var next; for (;;) { current.visit(this); if (next = current.firstChild) { current = next; continue; } for (;;) { current.revisit(this); if (current == node) { return; } if (next = current.nextSibling) { current = next; break; } current = current.parentNode; } } }; TreeParser.prototype.characters = function(ch, start, length, locator) { this.locatorDelegate = locator; this.contentHandler.characters(ch, start, length); }; TreeParser.prototype.endDocument = function(locator) { this.locatorDelegate = locator; this.contentHandler.endDocument(); }; TreeParser.prototype.endElement = function(uri, localName, qName, locator) { this.locatorDelegate = locator; this.contentHandler.endElement(uri, localName, qName); }; TreeParser.prototype.endPrefixMapping = function(prefix, locator) { this.locatorDelegate = locator; this.contentHandler.endPrefixMapping(prefix); }; TreeParser.prototype.ignorableWhitespace = function(ch, start, length, locator) { this.locatorDelegate = locator; this.contentHandler.ignorableWhitespace(ch, start, length); }; TreeParser.prototype.processingInstruction = function(target, data, locator) { this.locatorDelegate = locator; this.contentHandler.processingInstruction(target, data); }; TreeParser.prototype.skippedEntity = function(name, locator) { this.locatorDelegate = locator; this.contentHandler.skippedEntity(name); }; TreeParser.prototype.startDocument = function(locator) { this.locatorDelegate = locator; this.contentHandler.startDocument(); }; TreeParser.prototype.startElement = function(uri, localName, qName, atts, locator) { this.locatorDelegate = locator; this.contentHandler.startElement(uri, localName, qName, atts); }; TreeParser.prototype.startPrefixMapping = function(prefix, uri, locator) { this.locatorDelegate = locator; this.contentHandler.startPrefixMapping(prefix, uri); }; TreeParser.prototype.comment = function(ch, start, length, locator) { this.locatorDelegate = locator; this.lexicalHandler.comment(ch, start, length); }; TreeParser.prototype.endCDATA = function(locator) { this.locatorDelegate = locator; this.lexicalHandler.endCDATA(); }; TreeParser.prototype.endDTD = function(locator) { this.locatorDelegate = locator; this.lexicalHandler.endDTD(); }; TreeParser.prototype.endEntity = function(name, locator) { this.locatorDelegate = locator; this.lexicalHandler.endEntity(name); }; TreeParser.prototype.startCDATA = function(locator) { this.locatorDelegate = locator; this.lexicalHandler.startCDATA(); }; TreeParser.prototype.startDTD = function(name, publicId, systemId, locator) { this.locatorDelegate = locator; this.lexicalHandler.startDTD(name, publicId, systemId); }; TreeParser.prototype.startEntity = function(name, locator) { this.locatorDelegate = locator; this.lexicalHandler.startEntity(name); }; Object.defineProperty(TreeParser.prototype, 'columnNumber', { get: function() { if (!this.locatorDelegate) return -1; else return this.locatorDelegate.columnNumber; } }); Object.defineProperty(TreeParser.prototype, 'lineNumber', { get: function() { if (!this.locatorDelegate) return -1; else return this.locatorDelegate.lineNumber; } }); function NullLexicalHandler() { } NullLexicalHandler.prototype.comment = function() {}; NullLexicalHandler.prototype.endCDATA = function() {}; NullLexicalHandler.prototype.endDTD = function() {}; NullLexicalHandler.prototype.endEntity = function() {}; NullLexicalHandler.prototype.startCDATA = function() {}; NullLexicalHandler.prototype.startDTD = function() {}; NullLexicalHandler.prototype.startEntity = function() {}; exports.TreeParser = TreeParser; }, {}], 12:[function(_dereq_,module,exports){ module.exports = { "Aacute;": "\u00C1", "Aacute": "\u00C1", "aacute;": "\u00E1", "aacute": "\u00E1", "Abreve;": "\u0102", "abreve;": "\u0103", "ac;": "\u223E", "acd;": "\u223F", "acE;": "\u223E\u0333", "Acirc;": "\u00C2", "Acirc": "\u00C2", "acirc;": "\u00E2", "acirc": "\u00E2", "acute;": "\u00B4", "acute": "\u00B4", "Acy;": "\u0410", "acy;": "\u0430", "AElig;": "\u00C6", "AElig": "\u00C6", "aelig;": "\u00E6", "aelig": "\u00E6", "af;": "\u2061", "Afr;": "\uD835\uDD04", "afr;": "\uD835\uDD1E", "Agrave;": "\u00C0", "Agrave": "\u00C0", "agrave;": "\u00E0", "agrave": "\u00E0", "alefsym;": "\u2135", "aleph;": "\u2135", "Alpha;": "\u0391", "alpha;": "\u03B1", "Amacr;": "\u0100", "amacr;": "\u0101", "amalg;": "\u2A3F", "amp;": "\u0026", "amp": "\u0026", "AMP;": "\u0026", "AMP": "\u0026", "andand;": "\u2A55", "And;": "\u2A53", "and;": "\u2227", "andd;": "\u2A5C", "andslope;": "\u2A58", "andv;": "\u2A5A", "ang;": "\u2220", "ange;": "\u29A4", "angle;": "\u2220", "angmsdaa;": "\u29A8", "angmsdab;": "\u29A9", "angmsdac;": "\u29AA", "angmsdad;": "\u29AB", "angmsdae;": "\u29AC", "angmsdaf;": "\u29AD", "angmsdag;": "\u29AE", "angmsdah;": "\u29AF", "angmsd;": "\u2221", "angrt;": "\u221F", "angrtvb;": "\u22BE", "angrtvbd;": "\u299D", "angsph;": "\u2222", "angst;": "\u00C5", "angzarr;": "\u237C", "Aogon;": "\u0104", "aogon;": "\u0105", "Aopf;": "\uD835\uDD38", "aopf;": "\uD835\uDD52", "apacir;": "\u2A6F", "ap;": "\u2248", "apE;": "\u2A70", "ape;": "\u224A", "apid;": "\u224B", "apos;": "\u0027", "ApplyFunction;": "\u2061", "approx;": "\u2248", "approxeq;": "\u224A", "Aring;": "\u00C5", "Aring": "\u00C5", "aring;": "\u00E5", "aring": "\u00E5", "Ascr;": "\uD835\uDC9C", "ascr;": "\uD835\uDCB6", "Assign;": "\u2254", "ast;": "\u002A", "asymp;": "\u2248", "asympeq;": "\u224D", "Atilde;": "\u00C3", "Atilde": "\u00C3", "atilde;": "\u00E3", "atilde": "\u00E3", "Auml;": "\u00C4", "Auml": "\u00C4", "auml;": "\u00E4", "auml": "\u00E4", "awconint;": "\u2233", "awint;": "\u2A11", "backcong;": "\u224C", "backepsilon;": "\u03F6", "backprime;": "\u2035", "backsim;": "\u223D", "backsimeq;": "\u22CD", "Backslash;": "\u2216", "Barv;": "\u2AE7", "barvee;": "\u22BD", "barwed;": "\u2305", "Barwed;": "\u2306", "barwedge;": "\u2305", "bbrk;": "\u23B5", "bbrktbrk;": "\u23B6", "bcong;": "\u224C", "Bcy;": "\u0411", "bcy;": "\u0431", "bdquo;": "\u201E", "becaus;": "\u2235", "because;": "\u2235", "Because;": "\u2235", "bemptyv;": "\u29B0", "bepsi;": "\u03F6", "bernou;": "\u212C", "Bernoullis;": "\u212C", "Beta;": "\u0392", "beta;": "\u03B2", "beth;": "\u2136", "between;": "\u226C", "Bfr;": "\uD835\uDD05", "bfr;": "\uD835\uDD1F", "bigcap;": "\u22C2", "bigcirc;": "\u25EF", "bigcup;": "\u22C3", "bigodot;": "\u2A00", "bigoplus;": "\u2A01", "bigotimes;": "\u2A02", "bigsqcup;": "\u2A06", "bigstar;": "\u2605", "bigtriangledown;": "\u25BD", "bigtriangleup;": "\u25B3", "biguplus;": "\u2A04", "bigvee;": "\u22C1", "bigwedge;": "\u22C0", "bkarow;": "\u290D", "blacklozenge;": "\u29EB", "blacksquare;": "\u25AA", "blacktriangle;": "\u25B4", "blacktriangledown;": "\u25BE", "blacktriangleleft;": "\u25C2", "blacktriangleright;": "\u25B8", "blank;": "\u2423", "blk12;": "\u2592", "blk14;": "\u2591", "blk34;": "\u2593", "block;": "\u2588", "bne;": "\u003D\u20E5", "bnequiv;": "\u2261\u20E5", "bNot;": "\u2AED", "bnot;": "\u2310", "Bopf;": "\uD835\uDD39", "bopf;": "\uD835\uDD53", "bot;": "\u22A5", "bottom;": "\u22A5", "bowtie;": "\u22C8", "boxbox;": "\u29C9", "boxdl;": "\u2510", "boxdL;": "\u2555", "boxDl;": "\u2556", "boxDL;": "\u2557", "boxdr;": "\u250C", "boxdR;": "\u2552", "boxDr;": "\u2553", "boxDR;": "\u2554", "boxh;": "\u2500", "boxH;": "\u2550", "boxhd;": "\u252C", "boxHd;": "\u2564", "boxhD;": "\u2565", "boxHD;": "\u2566", "boxhu;": "\u2534", "boxHu;": "\u2567", "boxhU;": "\u2568", "boxHU;": "\u2569", "boxminus;": "\u229F", "boxplus;": "\u229E", "boxtimes;": "\u22A0", "boxul;": "\u2518", "boxuL;": "\u255B", "boxUl;": "\u255C", "boxUL;": "\u255D", "boxur;": "\u2514", "boxuR;": "\u2558", "boxUr;": "\u2559", "boxUR;": "\u255A", "boxv;": "\u2502", "boxV;": "\u2551", "boxvh;": "\u253C", "boxvH;": "\u256A", "boxVh;": "\u256B", "boxVH;": "\u256C", "boxvl;": "\u2524", "boxvL;": "\u2561", "boxVl;": "\u2562", "boxVL;": "\u2563", "boxvr;": "\u251C", "boxvR;": "\u255E", "boxVr;": "\u255F", "boxVR;": "\u2560", "bprime;": "\u2035", "breve;": "\u02D8", "Breve;": "\u02D8", "brvbar;": "\u00A6", "brvbar": "\u00A6", "bscr;": "\uD835\uDCB7", "Bscr;": "\u212C", "bsemi;": "\u204F", "bsim;": "\u223D", "bsime;": "\u22CD", "bsolb;": "\u29C5", "bsol;": "\u005C", "bsolhsub;": "\u27C8", "bull;": "\u2022", "bullet;": "\u2022", "bump;": "\u224E", "bumpE;": "\u2AAE", "bumpe;": "\u224F", "Bumpeq;": "\u224E", "bumpeq;": "\u224F", "Cacute;": "\u0106", "cacute;": "\u0107", "capand;": "\u2A44", "capbrcup;": "\u2A49", "capcap;": "\u2A4B", "cap;": "\u2229", "Cap;": "\u22D2", "capcup;": "\u2A47", "capdot;": "\u2A40", "CapitalDifferentialD;": "\u2145", "caps;": "\u2229\uFE00", "caret;": "\u2041", "caron;": "\u02C7", "Cayleys;": "\u212D", "ccaps;": "\u2A4D", "Ccaron;": "\u010C", "ccaron;": "\u010D", "Ccedil;": "\u00C7", "Ccedil": "\u00C7", "ccedil;": "\u00E7", "ccedil": "\u00E7", "Ccirc;": "\u0108", "ccirc;": "\u0109", "Cconint;": "\u2230", "ccups;": "\u2A4C", "ccupssm;": "\u2A50", "Cdot;": "\u010A", "cdot;": "\u010B", "cedil;": "\u00B8", "cedil": "\u00B8", "Cedilla;": "\u00B8", "cemptyv;": "\u29B2", "cent;": "\u00A2", "cent": "\u00A2", "centerdot;": "\u00B7", "CenterDot;": "\u00B7", "cfr;": "\uD835\uDD20", "Cfr;": "\u212D", "CHcy;": "\u0427", "chcy;": "\u0447", "check;": "\u2713", "checkmark;": "\u2713", "Chi;": "\u03A7", "chi;": "\u03C7", "circ;": "\u02C6", "circeq;": "\u2257", "circlearrowleft;": "\u21BA", "circlearrowright;": "\u21BB", "circledast;": "\u229B", "circledcirc;": "\u229A", "circleddash;": "\u229D", "CircleDot;": "\u2299", "circledR;": "\u00AE", "circledS;": "\u24C8", "CircleMinus;": "\u2296", "CirclePlus;": "\u2295", "CircleTimes;": "\u2297", "cir;": "\u25CB", "cirE;": "\u29C3", "cire;": "\u2257", "cirfnint;": "\u2A10", "cirmid;": "\u2AEF", "cirscir;": "\u29C2", "ClockwiseContourIntegral;": "\u2232", "CloseCurlyDoubleQuote;": "\u201D", "CloseCurlyQuote;": "\u2019", "clubs;": "\u2663", "clubsuit;": "\u2663", "colon;": "\u003A", "Colon;": "\u2237", "Colone;": "\u2A74", "colone;": "\u2254", "coloneq;": "\u2254", "comma;": "\u002C", "commat;": "\u0040", "comp;": "\u2201", "compfn;": "\u2218", "complement;": "\u2201", "complexes;": "\u2102", "cong;": "\u2245", "congdot;": "\u2A6D", "Congruent;": "\u2261", "conint;": "\u222E", "Conint;": "\u222F", "ContourIntegral;": "\u222E", "copf;": "\uD835\uDD54", "Copf;": "\u2102", "coprod;": "\u2210", "Coproduct;": "\u2210", "copy;": "\u00A9", "copy": "\u00A9", "COPY;": "\u00A9", "COPY": "\u00A9", "copysr;": "\u2117", "CounterClockwiseContourIntegral;": "\u2233", "crarr;": "\u21B5", "cross;": "\u2717", "Cross;": "\u2A2F", "Cscr;": "\uD835\uDC9E", "cscr;": "\uD835\uDCB8", "csub;": "\u2ACF", "csube;": "\u2AD1", "csup;": "\u2AD0", "csupe;": "\u2AD2", "ctdot;": "\u22EF", "cudarrl;": "\u2938", "cudarrr;": "\u2935", "cuepr;": "\u22DE", "cuesc;": "\u22DF", "cularr;": "\u21B6", "cularrp;": "\u293D", "cupbrcap;": "\u2A48", "cupcap;": "\u2A46", "CupCap;": "\u224D", "cup;": "\u222A", "Cup;": "\u22D3", "cupcup;": "\u2A4A", "cupdot;": "\u228D", "cupor;": "\u2A45", "cups;": "\u222A\uFE00", "curarr;": "\u21B7", "curarrm;": "\u293C", "curlyeqprec;": "\u22DE", "curlyeqsucc;": "\u22DF", "curlyvee;": "\u22CE", "curlywedge;": "\u22CF", "curren;": "\u00A4", "curren": "\u00A4", "curvearrowleft;": "\u21B6", "curvearrowright;": "\u21B7", "cuvee;": "\u22CE", "cuwed;": "\u22CF", "cwconint;": "\u2232", "cwint;": "\u2231", "cylcty;": "\u232D", "dagger;": "\u2020", "Dagger;": "\u2021", "daleth;": "\u2138", "darr;": "\u2193", "Darr;": "\u21A1", "dArr;": "\u21D3", "dash;": "\u2010", "Dashv;": "\u2AE4", "dashv;": "\u22A3", "dbkarow;": "\u290F", "dblac;": "\u02DD", "Dcaron;": "\u010E", "dcaron;": "\u010F", "Dcy;": "\u0414", "dcy;": "\u0434", "ddagger;": "\u2021", "ddarr;": "\u21CA", "DD;": "\u2145", "dd;": "\u2146", "DDotrahd;": "\u2911", "ddotseq;": "\u2A77", "deg;": "\u00B0", "deg": "\u00B0", "Del;": "\u2207", "Delta;": "\u0394", "delta;": "\u03B4", "demptyv;": "\u29B1", "dfisht;": "\u297F", "Dfr;": "\uD835\uDD07", "dfr;": "\uD835\uDD21", "dHar;": "\u2965", "dharl;": "\u21C3", "dharr;": "\u21C2", "DiacriticalAcute;": "\u00B4", "DiacriticalDot;": "\u02D9", "DiacriticalDoubleAcute;": "\u02DD", "DiacriticalGrave;": "\u0060", "DiacriticalTilde;": "\u02DC", "diam;": "\u22C4", "diamond;": "\u22C4", "Diamond;": "\u22C4", "diamondsuit;": "\u2666", "diams;": "\u2666", "die;": "\u00A8", "DifferentialD;": "\u2146", "digamma;": "\u03DD", "disin;": "\u22F2", "div;": "\u00F7", "divide;": "\u00F7", "divide": "\u00F7", "divideontimes;": "\u22C7", "divonx;": "\u22C7", "DJcy;": "\u0402", "djcy;": "\u0452", "dlcorn;": "\u231E", "dlcrop;": "\u230D", "dollar;": "\u0024", "Dopf;": "\uD835\uDD3B", "dopf;": "\uD835\uDD55", "Dot;": "\u00A8", "dot;": "\u02D9", "DotDot;": "\u20DC", "doteq;": "\u2250", "doteqdot;": "\u2251", "DotEqual;": "\u2250", "dotminus;": "\u2238", "dotplus;": "\u2214", "dotsquare;": "\u22A1", "doublebarwedge;": "\u2306", "DoubleContourIntegral;": "\u222F", "DoubleDot;": "\u00A8", "DoubleDownArrow;": "\u21D3", "DoubleLeftArrow;": "\u21D0", "DoubleLeftRightArrow;": "\u21D4", "DoubleLeftTee;": "\u2AE4", "DoubleLongLeftArrow;": "\u27F8", "DoubleLongLeftRightArrow;": "\u27FA", "DoubleLongRightArrow;": "\u27F9", "DoubleRightArrow;": "\u21D2", "DoubleRightTee;": "\u22A8", "DoubleUpArrow;": "\u21D1", "DoubleUpDownArrow;": "\u21D5", "DoubleVerticalBar;": "\u2225", "DownArrowBar;": "\u2913", "downarrow;": "\u2193", "DownArrow;": "\u2193", "Downarrow;": "\u21D3", "DownArrowUpArrow;": "\u21F5", "DownBreve;": "\u0311", "downdownarrows;": "\u21CA", "downharpoonleft;": "\u21C3", "downharpoonright;": "\u21C2", "DownLeftRightVector;": "\u2950", "DownLeftTeeVector;": "\u295E", "DownLeftVectorBar;": "\u2956", "DownLeftVector;": "\u21BD", "DownRightTeeVector;": "\u295F", "DownRightVectorBar;": "\u2957", "DownRightVector;": "\u21C1", "DownTeeArrow;": "\u21A7", "DownTee;": "\u22A4", "drbkarow;": "\u2910", "drcorn;": "\u231F", "drcrop;": "\u230C", "Dscr;": "\uD835\uDC9F", "dscr;": "\uD835\uDCB9", "DScy;": "\u0405", "dscy;": "\u0455", "dsol;": "\u29F6", "Dstrok;": "\u0110", "dstrok;": "\u0111", "dtdot;": "\u22F1", "dtri;": "\u25BF", "dtrif;": "\u25BE", "duarr;": "\u21F5", "duhar;": "\u296F", "dwangle;": "\u29A6", "DZcy;": "\u040F", "dzcy;": "\u045F", "dzigrarr;": "\u27FF", "Eacute;": "\u00C9", "Eacute": "\u00C9", "eacute;": "\u00E9", "eacute": "\u00E9", "easter;": "\u2A6E", "Ecaron;": "\u011A", "ecaron;": "\u011B", "Ecirc;": "\u00CA", "Ecirc": "\u00CA", "ecirc;": "\u00EA", "ecirc": "\u00EA", "ecir;": "\u2256", "ecolon;": "\u2255", "Ecy;": "\u042D", "ecy;": "\u044D", "eDDot;": "\u2A77", "Edot;": "\u0116", "edot;": "\u0117", "eDot;": "\u2251", "ee;": "\u2147", "efDot;": "\u2252", "Efr;": "\uD835\uDD08", "efr;": "\uD835\uDD22", "eg;": "\u2A9A", "Egrave;": "\u00C8", "Egrave": "\u00C8", "egrave;": "\u00E8", "egrave": "\u00E8", "egs;": "\u2A96", "egsdot;": "\u2A98", "el;": "\u2A99", "Element;": "\u2208", "elinters;": "\u23E7", "ell;": "\u2113", "els;": "\u2A95", "elsdot;": "\u2A97", "Emacr;": "\u0112", "emacr;": "\u0113", "empty;": "\u2205", "emptyset;": "\u2205", "EmptySmallSquare;": "\u25FB", "emptyv;": "\u2205", "EmptyVerySmallSquare;": "\u25AB", "emsp13;": "\u2004", "emsp14;": "\u2005", "emsp;": "\u2003", "ENG;": "\u014A", "eng;": "\u014B", "ensp;": "\u2002", "Eogon;": "\u0118", "eogon;": "\u0119", "Eopf;": "\uD835\uDD3C", "eopf;": "\uD835\uDD56", "epar;": "\u22D5", "eparsl;": "\u29E3", "eplus;": "\u2A71", "epsi;": "\u03B5", "Epsilon;": "\u0395", "epsilon;": "\u03B5", "epsiv;": "\u03F5", "eqcirc;": "\u2256", "eqcolon;": "\u2255", "eqsim;": "\u2242", "eqslantgtr;": "\u2A96", "eqslantless;": "\u2A95", "Equal;": "\u2A75", "equals;": "\u003D", "EqualTilde;": "\u2242", "equest;": "\u225F", "Equilibrium;": "\u21CC", "equiv;": "\u2261", "equivDD;": "\u2A78", "eqvparsl;": "\u29E5", "erarr;": "\u2971", "erDot;": "\u2253", "escr;": "\u212F", "Escr;": "\u2130", "esdot;": "\u2250", "Esim;": "\u2A73", "esim;": "\u2242", "Eta;": "\u0397", "eta;": "\u03B7", "ETH;": "\u00D0", "ETH": "\u00D0", "eth;": "\u00F0", "eth": "\u00F0", "Euml;": "\u00CB", "Euml": "\u00CB", "euml;": "\u00EB", "euml": "\u00EB", "euro;": "\u20AC", "excl;": "\u0021", "exist;": "\u2203", "Exists;": "\u2203", "expectation;": "\u2130", "exponentiale;": "\u2147", "ExponentialE;": "\u2147", "fallingdotseq;": "\u2252", "Fcy;": "\u0424", "fcy;": "\u0444", "female;": "\u2640", "ffilig;": "\uFB03", "fflig;": "\uFB00", "ffllig;": "\uFB04", "Ffr;": "\uD835\uDD09", "ffr;": "\uD835\uDD23", "filig;": "\uFB01", "FilledSmallSquare;": "\u25FC", "FilledVerySmallSquare;": "\u25AA", "fjlig;": "\u0066\u006A", "flat;": "\u266D", "fllig;": "\uFB02", "fltns;": "\u25B1", "fnof;": "\u0192", "Fopf;": "\uD835\uDD3D", "fopf;": "\uD835\uDD57", "forall;": "\u2200", "ForAll;": "\u2200", "fork;": "\u22D4", "forkv;": "\u2AD9", "Fouriertrf;": "\u2131", "fpartint;": "\u2A0D", "frac12;": "\u00BD", "frac12": "\u00BD", "frac13;": "\u2153", "frac14;": "\u00BC", "frac14": "\u00BC", "frac15;": "\u2155", "frac16;": "\u2159", "frac18;": "\u215B", "frac23;": "\u2154", "frac25;": "\u2156", "frac34;": "\u00BE", "frac34": "\u00BE", "frac35;": "\u2157", "frac38;": "\u215C", "frac45;": "\u2158", "frac56;": "\u215A", "frac58;": "\u215D", "frac78;": "\u215E", "frasl;": "\u2044", "frown;": "\u2322", "fscr;": "\uD835\uDCBB", "Fscr;": "\u2131", "gacute;": "\u01F5", "Gamma;": "\u0393", "gamma;": "\u03B3", "Gammad;": "\u03DC", "gammad;": "\u03DD", "gap;": "\u2A86", "Gbreve;": "\u011E", "gbreve;": "\u011F", "Gcedil;": "\u0122", "Gcirc;": "\u011C", "gcirc;": "\u011D", "Gcy;": "\u0413", "gcy;": "\u0433", "Gdot;": "\u0120", "gdot;": "\u0121", "ge;": "\u2265", "gE;": "\u2267", "gEl;": "\u2A8C", "gel;": "\u22DB", "geq;": "\u2265", "geqq;": "\u2267", "geqslant;": "\u2A7E", "gescc;": "\u2AA9", "ges;": "\u2A7E", "gesdot;": "\u2A80", "gesdoto;": "\u2A82", "gesdotol;": "\u2A84", "gesl;": "\u22DB\uFE00", "gesles;": "\u2A94", "Gfr;": "\uD835\uDD0A", "gfr;": "\uD835\uDD24", "gg;": "\u226B", "Gg;": "\u22D9", "ggg;": "\u22D9", "gimel;": "\u2137", "GJcy;": "\u0403", "gjcy;": "\u0453", "gla;": "\u2AA5", "gl;": "\u2277", "glE;": "\u2A92", "glj;": "\u2AA4", "gnap;": "\u2A8A", "gnapprox;": "\u2A8A", "gne;": "\u2A88", "gnE;": "\u2269", "gneq;": "\u2A88", "gneqq;": "\u2269", "gnsim;": "\u22E7", "Gopf;": "\uD835\uDD3E", "gopf;": "\uD835\uDD58", "grave;": "\u0060", "GreaterEqual;": "\u2265", "GreaterEqualLess;": "\u22DB", "GreaterFullEqual;": "\u2267", "GreaterGreater;": "\u2AA2", "GreaterLess;": "\u2277", "GreaterSlantEqual;": "\u2A7E", "GreaterTilde;": "\u2273", "Gscr;": "\uD835\uDCA2", "gscr;": "\u210A", "gsim;": "\u2273", "gsime;": "\u2A8E", "gsiml;": "\u2A90", "gtcc;": "\u2AA7", "gtcir;": "\u2A7A", "gt;": "\u003E", "gt": "\u003E", "GT;": "\u003E", "GT": "\u003E", "Gt;": "\u226B", "gtdot;": "\u22D7", "gtlPar;": "\u2995", "gtquest;": "\u2A7C", "gtrapprox;": "\u2A86", "gtrarr;": "\u2978", "gtrdot;": "\u22D7", "gtreqless;": "\u22DB", "gtreqqless;": "\u2A8C", "gtrless;": "\u2277", "gtrsim;": "\u2273", "gvertneqq;": "\u2269\uFE00", "gvnE;": "\u2269\uFE00", "Hacek;": "\u02C7", "hairsp;": "\u200A", "half;": "\u00BD", "hamilt;": "\u210B", "HARDcy;": "\u042A", "hardcy;": "\u044A", "harrcir;": "\u2948", "harr;": "\u2194", "hArr;": "\u21D4", "harrw;": "\u21AD", "Hat;": "\u005E", "hbar;": "\u210F", "Hcirc;": "\u0124", "hcirc;": "\u0125", "hearts;": "\u2665", "heartsuit;": "\u2665", "hellip;": "\u2026", "hercon;": "\u22B9", "hfr;": "\uD835\uDD25", "Hfr;": "\u210C", "HilbertSpace;": "\u210B", "hksearow;": "\u2925", "hkswarow;": "\u2926", "hoarr;": "\u21FF", "homtht;": "\u223B", "hookleftarrow;": "\u21A9", "hookrightarrow;": "\u21AA", "hopf;": "\uD835\uDD59", "Hopf;": "\u210D", "horbar;": "\u2015", "HorizontalLine;": "\u2500", "hscr;": "\uD835\uDCBD", "Hscr;": "\u210B", "hslash;": "\u210F", "Hstrok;": "\u0126", "hstrok;": "\u0127", "HumpDownHump;": "\u224E", "HumpEqual;": "\u224F", "hybull;": "\u2043", "hyphen;": "\u2010", "Iacute;": "\u00CD", "Iacute": "\u00CD", "iacute;": "\u00ED", "iacute": "\u00ED", "ic;": "\u2063", "Icirc;": "\u00CE", "Icirc": "\u00CE", "icirc;": "\u00EE", "icirc": "\u00EE", "Icy;": "\u0418", "icy;": "\u0438", "Idot;": "\u0130", "IEcy;": "\u0415", "iecy;": "\u0435", "iexcl;": "\u00A1", "iexcl": "\u00A1", "iff;": "\u21D4", "ifr;": "\uD835\uDD26", "Ifr;": "\u2111", "Igrave;": "\u00CC", "Igrave": "\u00CC", "igrave;": "\u00EC", "igrave": "\u00EC", "ii;": "\u2148", "iiiint;": "\u2A0C", "iiint;": "\u222D", "iinfin;": "\u29DC", "iiota;": "\u2129", "IJlig;": "\u0132", "ijlig;": "\u0133", "Imacr;": "\u012A", "imacr;": "\u012B", "image;": "\u2111", "ImaginaryI;": "\u2148", "imagline;": "\u2110", "imagpart;": "\u2111", "imath;": "\u0131", "Im;": "\u2111", "imof;": "\u22B7", "imped;": "\u01B5", "Implies;": "\u21D2", "incare;": "\u2105", "in;": "\u2208", "infin;": "\u221E", "infintie;": "\u29DD", "inodot;": "\u0131", "intcal;": "\u22BA", "int;": "\u222B", "Int;": "\u222C", "integers;": "\u2124", "Integral;": "\u222B", "intercal;": "\u22BA", "Intersection;": "\u22C2", "intlarhk;": "\u2A17", "intprod;": "\u2A3C", "InvisibleComma;": "\u2063", "InvisibleTimes;": "\u2062", "IOcy;": "\u0401", "iocy;": "\u0451", "Iogon;": "\u012E", "iogon;": "\u012F", "Iopf;": "\uD835\uDD40", "iopf;": "\uD835\uDD5A", "Iota;": "\u0399", "iota;": "\u03B9", "iprod;": "\u2A3C", "iquest;": "\u00BF", "iquest": "\u00BF", "iscr;": "\uD835\uDCBE", "Iscr;": "\u2110", "isin;": "\u2208", "isindot;": "\u22F5", "isinE;": "\u22F9", "isins;": "\u22F4", "isinsv;": "\u22F3", "isinv;": "\u2208", "it;": "\u2062", "Itilde;": "\u0128", "itilde;": "\u0129", "Iukcy;": "\u0406", "iukcy;": "\u0456", "Iuml;": "\u00CF", "Iuml": "\u00CF", "iuml;": "\u00EF", "iuml": "\u00EF", "Jcirc;": "\u0134", "jcirc;": "\u0135", "Jcy;": "\u0419", "jcy;": "\u0439", "Jfr;": "\uD835\uDD0D", "jfr;": "\uD835\uDD27", "jmath;": "\u0237", "Jopf;": "\uD835\uDD41", "jopf;": "\uD835\uDD5B", "Jscr;": "\uD835\uDCA5", "jscr;": "\uD835\uDCBF", "Jsercy;": "\u0408", "jsercy;": "\u0458", "Jukcy;": "\u0404", "jukcy;": "\u0454", "Kappa;": "\u039A", "kappa;": "\u03BA", "kappav;": "\u03F0", "Kcedil;": "\u0136", "kcedil;": "\u0137", "Kcy;": "\u041A", "kcy;": "\u043A", "Kfr;": "\uD835\uDD0E", "kfr;": "\uD835\uDD28", "kgreen;": "\u0138", "KHcy;": "\u0425", "khcy;": "\u0445", "KJcy;": "\u040C", "kjcy;": "\u045C", "Kopf;": "\uD835\uDD42", "kopf;": "\uD835\uDD5C", "Kscr;": "\uD835\uDCA6", "kscr;": "\uD835\uDCC0", "lAarr;": "\u21DA", "Lacute;": "\u0139", "lacute;": "\u013A", "laemptyv;": "\u29B4", "lagran;": "\u2112", "Lambda;": "\u039B", "lambda;": "\u03BB", "lang;": "\u27E8", "Lang;": "\u27EA", "langd;": "\u2991", "langle;": "\u27E8", "lap;": "\u2A85", "Laplacetrf;": "\u2112", "laquo;": "\u00AB", "laquo": "\u00AB", "larrb;": "\u21E4", "larrbfs;": "\u291F", "larr;": "\u2190", "Larr;": "\u219E", "lArr;": "\u21D0", "larrfs;": "\u291D", "larrhk;": "\u21A9", "larrlp;": "\u21AB", "larrpl;": "\u2939", "larrsim;": "\u2973", "larrtl;": "\u21A2", "latail;": "\u2919", "lAtail;": "\u291B", "lat;": "\u2AAB", "late;": "\u2AAD", "lates;": "\u2AAD\uFE00", "lbarr;": "\u290C", "lBarr;": "\u290E", "lbbrk;": "\u2772", "lbrace;": "\u007B", "lbrack;": "\u005B", "lbrke;": "\u298B", "lbrksld;": "\u298F", "lbrkslu;": "\u298D", "Lcaron;": "\u013D", "lcaron;": "\u013E", "Lcedil;": "\u013B", "lcedil;": "\u013C", "lceil;": "\u2308", "lcub;": "\u007B", "Lcy;": "\u041B", "lcy;": "\u043B", "ldca;": "\u2936", "ldquo;": "\u201C", "ldquor;": "\u201E", "ldrdhar;": "\u2967", "ldrushar;": "\u294B", "ldsh;": "\u21B2", "le;": "\u2264", "lE;": "\u2266", "LeftAngleBracket;": "\u27E8", "LeftArrowBar;": "\u21E4", "leftarrow;": "\u2190", "LeftArrow;": "\u2190", "Leftarrow;": "\u21D0", "LeftArrowRightArrow;": "\u21C6", "leftarrowtail;": "\u21A2", "LeftCeiling;": "\u2308", "LeftDoubleBracket;": "\u27E6", "LeftDownTeeVector;": "\u2961", "LeftDownVectorBar;": "\u2959", "LeftDownVector;": "\u21C3", "LeftFloor;": "\u230A", "leftharpoondown;": "\u21BD", "leftharpoonup;": "\u21BC", "leftleftarrows;": "\u21C7", "leftrightarrow;": "\u2194", "LeftRightArrow;": "\u2194", "Leftrightarrow;": "\u21D4", "leftrightarrows;": "\u21C6", "leftrightharpoons;": "\u21CB", "leftrightsquigarrow;": "\u21AD", "LeftRightVector;": "\u294E", "LeftTeeArrow;": "\u21A4", "LeftTee;": "\u22A3", "LeftTeeVector;": "\u295A", "leftthreetimes;": "\u22CB", "LeftTriangleBar;": "\u29CF", "LeftTriangle;": "\u22B2", "LeftTriangleEqual;": "\u22B4", "LeftUpDownVector;": "\u2951", "LeftUpTeeVector;": "\u2960", "LeftUpVectorBar;": "\u2958", "LeftUpVector;": "\u21BF", "LeftVectorBar;": "\u2952", "LeftVector;": "\u21BC", "lEg;": "\u2A8B", "leg;": "\u22DA", "leq;": "\u2264", "leqq;": "\u2266", "leqslant;": "\u2A7D", "lescc;": "\u2AA8", "les;": "\u2A7D", "lesdot;": "\u2A7F", "lesdoto;": "\u2A81", "lesdotor;": "\u2A83", "lesg;": "\u22DA\uFE00", "lesges;": "\u2A93", "lessapprox;": "\u2A85", "lessdot;": "\u22D6", "lesseqgtr;": "\u22DA", "lesseqqgtr;": "\u2A8B", "LessEqualGreater;": "\u22DA", "LessFullEqual;": "\u2266", "LessGreater;": "\u2276", "lessgtr;": "\u2276", "LessLess;": "\u2AA1", "lesssim;": "\u2272", "LessSlantEqual;": "\u2A7D", "LessTilde;": "\u2272", "lfisht;": "\u297C", "lfloor;": "\u230A", "Lfr;": "\uD835\uDD0F", "lfr;": "\uD835\uDD29", "lg;": "\u2276", "lgE;": "\u2A91", "lHar;": "\u2962", "lhard;": "\u21BD", "lharu;": "\u21BC", "lharul;": "\u296A", "lhblk;": "\u2584", "LJcy;": "\u0409", "ljcy;": "\u0459", "llarr;": "\u21C7", "ll;": "\u226A", "Ll;": "\u22D8", "llcorner;": "\u231E", "Lleftarrow;": "\u21DA", "llhard;": "\u296B", "lltri;": "\u25FA", "Lmidot;": "\u013F", "lmidot;": "\u0140", "lmoustache;": "\u23B0", "lmoust;": "\u23B0", "lnap;": "\u2A89", "lnapprox;": "\u2A89", "lne;": "\u2A87", "lnE;": "\u2268", "lneq;": "\u2A87", "lneqq;": "\u2268", "lnsim;": "\u22E6", "loang;": "\u27EC", "loarr;": "\u21FD", "lobrk;": "\u27E6", "longleftarrow;": "\u27F5", "LongLeftArrow;": "\u27F5", "Longleftarrow;": "\u27F8", "longleftrightarrow;": "\u27F7", "LongLeftRightArrow;": "\u27F7", "Longleftrightarrow;": "\u27FA", "longmapsto;": "\u27FC", "longrightarrow;": "\u27F6", "LongRightArrow;": "\u27F6", "Longrightarrow;": "\u27F9", "looparrowleft;": "\u21AB", "looparrowright;": "\u21AC", "lopar;": "\u2985", "Lopf;": "\uD835\uDD43", "lopf;": "\uD835\uDD5D", "loplus;": "\u2A2D", "lotimes;": "\u2A34", "lowast;": "\u2217", "lowbar;": "\u005F", "LowerLeftArrow;": "\u2199", "LowerRightArrow;": "\u2198", "loz;": "\u25CA", "lozenge;": "\u25CA", "lozf;": "\u29EB", "lpar;": "\u0028", "lparlt;": "\u2993", "lrarr;": "\u21C6", "lrcorner;": "\u231F", "lrhar;": "\u21CB", "lrhard;": "\u296D", "lrm;": "\u200E", "lrtri;": "\u22BF", "lsaquo;": "\u2039", "lscr;": "\uD835\uDCC1", "Lscr;": "\u2112", "lsh;": "\u21B0", "Lsh;": "\u21B0", "lsim;": "\u2272", "lsime;": "\u2A8D", "lsimg;": "\u2A8F", "lsqb;": "\u005B", "lsquo;": "\u2018", "lsquor;": "\u201A", "Lstrok;": "\u0141", "lstrok;": "\u0142", "ltcc;": "\u2AA6", "ltcir;": "\u2A79", "lt;": "\u003C", "lt": "\u003C", "LT;": "\u003C", "LT": "\u003C", "Lt;": "\u226A", "ltdot;": "\u22D6", "lthree;": "\u22CB", "ltimes;": "\u22C9", "ltlarr;": "\u2976", "ltquest;": "\u2A7B", "ltri;": "\u25C3", "ltrie;": "\u22B4", "ltrif;": "\u25C2", "ltrPar;": "\u2996", "lurdshar;": "\u294A", "luruhar;": "\u2966", "lvertneqq;": "\u2268\uFE00", "lvnE;": "\u2268\uFE00", "macr;": "\u00AF", "macr": "\u00AF", "male;": "\u2642", "malt;": "\u2720", "maltese;": "\u2720", "Map;": "\u2905", "map;": "\u21A6", "mapsto;": "\u21A6", "mapstodown;": "\u21A7", "mapstoleft;": "\u21A4", "mapstoup;": "\u21A5", "marker;": "\u25AE", "mcomma;": "\u2A29", "Mcy;": "\u041C", "mcy;": "\u043C", "mdash;": "\u2014", "mDDot;": "\u223A", "measuredangle;": "\u2221", "MediumSpace;": "\u205F", "Mellintrf;": "\u2133", "Mfr;": "\uD835\uDD10", "mfr;": "\uD835\uDD2A", "mho;": "\u2127", "micro;": "\u00B5", "micro": "\u00B5", "midast;": "\u002A", "midcir;": "\u2AF0", "mid;": "\u2223", "middot;": "\u00B7", "middot": "\u00B7", "minusb;": "\u229F", "minus;": "\u2212", "minusd;": "\u2238", "minusdu;": "\u2A2A", "MinusPlus;": "\u2213", "mlcp;": "\u2ADB", "mldr;": "\u2026", "mnplus;": "\u2213", "models;": "\u22A7", "Mopf;": "\uD835\uDD44", "mopf;": "\uD835\uDD5E", "mp;": "\u2213", "mscr;": "\uD835\uDCC2", "Mscr;": "\u2133", "mstpos;": "\u223E", "Mu;": "\u039C", "mu;": "\u03BC", "multimap;": "\u22B8", "mumap;": "\u22B8", "nabla;": "\u2207", "Nacute;": "\u0143", "nacute;": "\u0144", "nang;": "\u2220\u20D2", "nap;": "\u2249", "napE;": "\u2A70\u0338", "napid;": "\u224B\u0338", "napos;": "\u0149", "napprox;": "\u2249", "natural;": "\u266E", "naturals;": "\u2115", "natur;": "\u266E", "nbsp;": "\u00A0", "nbsp": "\u00A0", "nbump;": "\u224E\u0338", "nbumpe;": "\u224F\u0338", "ncap;": "\u2A43", "Ncaron;": "\u0147", "ncaron;": "\u0148", "Ncedil;": "\u0145", "ncedil;": "\u0146", "ncong;": "\u2247", "ncongdot;": "\u2A6D\u0338", "ncup;": "\u2A42", "Ncy;": "\u041D", "ncy;": "\u043D", "ndash;": "\u2013", "nearhk;": "\u2924", "nearr;": "\u2197", "neArr;": "\u21D7", "nearrow;": "\u2197", "ne;": "\u2260", "nedot;": "\u2250\u0338", "NegativeMediumSpace;": "\u200B", "NegativeThickSpace;": "\u200B", "NegativeThinSpace;": "\u200B", "NegativeVeryThinSpace;": "\u200B", "nequiv;": "\u2262", "nesear;": "\u2928", "nesim;": "\u2242\u0338", "NestedGreaterGreater;": "\u226B", "NestedLessLess;": "\u226A", "NewLine;": "\u000A", "nexist;": "\u2204", "nexists;": "\u2204", "Nfr;": "\uD835\uDD11", "nfr;": "\uD835\uDD2B", "ngE;": "\u2267\u0338", "nge;": "\u2271", "ngeq;": "\u2271", "ngeqq;": "\u2267\u0338", "ngeqslant;": "\u2A7E\u0338", "nges;": "\u2A7E\u0338", "nGg;": "\u22D9\u0338", "ngsim;": "\u2275", "nGt;": "\u226B\u20D2", "ngt;": "\u226F", "ngtr;": "\u226F", "nGtv;": "\u226B\u0338", "nharr;": "\u21AE", "nhArr;": "\u21CE", "nhpar;": "\u2AF2", "ni;": "\u220B", "nis;": "\u22FC", "nisd;": "\u22FA", "niv;": "\u220B", "NJcy;": "\u040A", "njcy;": "\u045A", "nlarr;": "\u219A", "nlArr;": "\u21CD", "nldr;": "\u2025", "nlE;": "\u2266\u0338", "nle;": "\u2270", "nleftarrow;": "\u219A", "nLeftarrow;": "\u21CD", "nleftrightarrow;": "\u21AE", "nLeftrightarrow;": "\u21CE", "nleq;": "\u2270", "nleqq;": "\u2266\u0338", "nleqslant;": "\u2A7D\u0338", "nles;": "\u2A7D\u0338", "nless;": "\u226E", "nLl;": "\u22D8\u0338", "nlsim;": "\u2274", "nLt;": "\u226A\u20D2", "nlt;": "\u226E", "nltri;": "\u22EA", "nltrie;": "\u22EC", "nLtv;": "\u226A\u0338", "nmid;": "\u2224", "NoBreak;": "\u2060", "NonBreakingSpace;": "\u00A0", "nopf;": "\uD835\uDD5F", "Nopf;": "\u2115", "Not;": "\u2AEC", "not;": "\u00AC", "not": "\u00AC", "NotCongruent;": "\u2262", "NotCupCap;": "\u226D", "NotDoubleVerticalBar;": "\u2226", "NotElement;": "\u2209", "NotEqual;": "\u2260", "NotEqualTilde;": "\u2242\u0338", "NotExists;": "\u2204", "NotGreater;": "\u226F", "NotGreaterEqual;": "\u2271", "NotGreaterFullEqual;": "\u2267\u0338", "NotGreaterGreater;": "\u226B\u0338", "NotGreaterLess;": "\u2279", "NotGreaterSlantEqual;": "\u2A7E\u0338", "NotGreaterTilde;": "\u2275", "NotHumpDownHump;": "\u224E\u0338", "NotHumpEqual;": "\u224F\u0338", "notin;": "\u2209", "notindot;": "\u22F5\u0338", "notinE;": "\u22F9\u0338", "notinva;": "\u2209", "notinvb;": "\u22F7", "notinvc;": "\u22F6", "NotLeftTriangleBar;": "\u29CF\u0338", "NotLeftTriangle;": "\u22EA", "NotLeftTriangleEqual;": "\u22EC", "NotLess;": "\u226E", "NotLessEqual;": "\u2270", "NotLessGreater;": "\u2278", "NotLessLess;": "\u226A\u0338", "NotLessSlantEqual;": "\u2A7D\u0338", "NotLessTilde;": "\u2274", "NotNestedGreaterGreater;": "\u2AA2\u0338", "NotNestedLessLess;": "\u2AA1\u0338", "notni;": "\u220C", "notniva;": "\u220C", "notnivb;": "\u22FE", "notnivc;": "\u22FD", "NotPrecedes;": "\u2280", "NotPrecedesEqual;": "\u2AAF\u0338", "NotPrecedesSlantEqual;": "\u22E0", "NotReverseElement;": "\u220C", "NotRightTriangleBar;": "\u29D0\u0338", "NotRightTriangle;": "\u22EB", "NotRightTriangleEqual;": "\u22ED", "NotSquareSubset;": "\u228F\u0338", "NotSquareSubsetEqual;": "\u22E2", "NotSquareSuperset;": "\u2290\u0338", "NotSquareSupersetEqual;": "\u22E3", "NotSubset;": "\u2282\u20D2", "NotSubsetEqual;": "\u2288", "NotSucceeds;": "\u2281", "NotSucceedsEqual;": "\u2AB0\u0338", "NotSucceedsSlantEqual;": "\u22E1", "NotSucceedsTilde;": "\u227F\u0338", "NotSuperset;": "\u2283\u20D2", "NotSupersetEqual;": "\u2289", "NotTilde;": "\u2241", "NotTildeEqual;": "\u2244", "NotTildeFullEqual;": "\u2247", "NotTildeTilde;": "\u2249", "NotVerticalBar;": "\u2224", "nparallel;": "\u2226", "npar;": "\u2226", "nparsl;": "\u2AFD\u20E5", "npart;": "\u2202\u0338", "npolint;": "\u2A14", "npr;": "\u2280", "nprcue;": "\u22E0", "nprec;": "\u2280", "npreceq;": "\u2AAF\u0338", "npre;": "\u2AAF\u0338", "nrarrc;": "\u2933\u0338", "nrarr;": "\u219B", "nrArr;": "\u21CF", "nrarrw;": "\u219D\u0338", "nrightarrow;": "\u219B", "nRightarrow;": "\u21CF", "nrtri;": "\u22EB", "nrtrie;": "\u22ED", "nsc;": "\u2281", "nsccue;": "\u22E1", "nsce;": "\u2AB0\u0338", "Nscr;": "\uD835\uDCA9", "nscr;": "\uD835\uDCC3", "nshortmid;": "\u2224", "nshortparallel;": "\u2226", "nsim;": "\u2241", "nsime;": "\u2244", "nsimeq;": "\u2244", "nsmid;": "\u2224", "nspar;": "\u2226", "nsqsube;": "\u22E2", "nsqsupe;": "\u22E3", "nsub;": "\u2284", "nsubE;": "\u2AC5\u0338", "nsube;": "\u2288", "nsubset;": "\u2282\u20D2", "nsubseteq;": "\u2288", "nsubseteqq;": "\u2AC5\u0338", "nsucc;": "\u2281", "nsucceq;": "\u2AB0\u0338", "nsup;": "\u2285", "nsupE;": "\u2AC6\u0338", "nsupe;": "\u2289", "nsupset;": "\u2283\u20D2", "nsupseteq;": "\u2289", "nsupseteqq;": "\u2AC6\u0338", "ntgl;": "\u2279", "Ntilde;": "\u00D1", "Ntilde": "\u00D1", "ntilde;": "\u00F1", "ntilde": "\u00F1", "ntlg;": "\u2278", "ntriangleleft;": "\u22EA", "ntrianglelefteq;": "\u22EC", "ntriangleright;": "\u22EB", "ntrianglerighteq;": "\u22ED", "Nu;": "\u039D", "nu;": "\u03BD", "num;": "\u0023", "numero;": "\u2116", "numsp;": "\u2007", "nvap;": "\u224D\u20D2", "nvdash;": "\u22AC", "nvDash;": "\u22AD", "nVdash;": "\u22AE", "nVDash;": "\u22AF", "nvge;": "\u2265\u20D2", "nvgt;": "\u003E\u20D2", "nvHarr;": "\u2904", "nvinfin;": "\u29DE", "nvlArr;": "\u2902", "nvle;": "\u2264\u20D2", "nvlt;": "\u003C\u20D2", "nvltrie;": "\u22B4\u20D2", "nvrArr;": "\u2903", "nvrtrie;": "\u22B5\u20D2", "nvsim;": "\u223C\u20D2", "nwarhk;": "\u2923", "nwarr;": "\u2196", "nwArr;": "\u21D6", "nwarrow;": "\u2196", "nwnear;": "\u2927", "Oacute;": "\u00D3", "Oacute": "\u00D3", "oacute;": "\u00F3", "oacute": "\u00F3", "oast;": "\u229B", "Ocirc;": "\u00D4", "Ocirc": "\u00D4", "ocirc;": "\u00F4", "ocirc": "\u00F4", "ocir;": "\u229A", "Ocy;": "\u041E", "ocy;": "\u043E", "odash;": "\u229D", "Odblac;": "\u0150", "odblac;": "\u0151", "odiv;": "\u2A38", "odot;": "\u2299", "odsold;": "\u29BC", "OElig;": "\u0152", "oelig;": "\u0153", "ofcir;": "\u29BF", "Ofr;": "\uD835\uDD12", "ofr;": "\uD835\uDD2C", "ogon;": "\u02DB", "Ograve;": "\u00D2", "Ograve": "\u00D2", "ograve;": "\u00F2", "ograve": "\u00F2", "ogt;": "\u29C1", "ohbar;": "\u29B5", "ohm;": "\u03A9", "oint;": "\u222E", "olarr;": "\u21BA", "olcir;": "\u29BE", "olcross;": "\u29BB", "oline;": "\u203E", "olt;": "\u29C0", "Omacr;": "\u014C", "omacr;": "\u014D", "Omega;": "\u03A9", "omega;": "\u03C9", "Omicron;": "\u039F", "omicron;": "\u03BF", "omid;": "\u29B6", "ominus;": "\u2296", "Oopf;": "\uD835\uDD46", "oopf;": "\uD835\uDD60", "opar;": "\u29B7", "OpenCurlyDoubleQuote;": "\u201C", "OpenCurlyQuote;": "\u2018", "operp;": "\u29B9", "oplus;": "\u2295", "orarr;": "\u21BB", "Or;": "\u2A54", "or;": "\u2228", "ord;": "\u2A5D", "order;": "\u2134", "orderof;": "\u2134", "ordf;": "\u00AA", "ordf": "\u00AA", "ordm;": "\u00BA", "ordm": "\u00BA", "origof;": "\u22B6", "oror;": "\u2A56", "orslope;": "\u2A57", "orv;": "\u2A5B", "oS;": "\u24C8", "Oscr;": "\uD835\uDCAA", "oscr;": "\u2134", "Oslash;": "\u00D8", "Oslash": "\u00D8", "oslash;": "\u00F8", "oslash": "\u00F8", "osol;": "\u2298", "Otilde;": "\u00D5", "Otilde": "\u00D5", "otilde;": "\u00F5", "otilde": "\u00F5", "otimesas;": "\u2A36", "Otimes;": "\u2A37", "otimes;": "\u2297", "Ouml;": "\u00D6", "Ouml": "\u00D6", "ouml;": "\u00F6", "ouml": "\u00F6", "ovbar;": "\u233D", "OverBar;": "\u203E", "OverBrace;": "\u23DE", "OverBracket;": "\u23B4", "OverParenthesis;": "\u23DC", "para;": "\u00B6", "para": "\u00B6", "parallel;": "\u2225", "par;": "\u2225", "parsim;": "\u2AF3", "parsl;": "\u2AFD", "part;": "\u2202", "PartialD;": "\u2202", "Pcy;": "\u041F", "pcy;": "\u043F", "percnt;": "\u0025", "period;": "\u002E", "permil;": "\u2030", "perp;": "\u22A5", "pertenk;": "\u2031", "Pfr;": "\uD835\uDD13", "pfr;": "\uD835\uDD2D", "Phi;": "\u03A6", "phi;": "\u03C6", "phiv;": "\u03D5", "phmmat;": "\u2133", "phone;": "\u260E", "Pi;": "\u03A0", "pi;": "\u03C0", "pitchfork;": "\u22D4", "piv;": "\u03D6", "planck;": "\u210F", "planckh;": "\u210E", "plankv;": "\u210F", "plusacir;": "\u2A23", "plusb;": "\u229E", "pluscir;": "\u2A22", "plus;": "\u002B", "plusdo;": "\u2214", "plusdu;": "\u2A25", "pluse;": "\u2A72", "PlusMinus;": "\u00B1", "plusmn;": "\u00B1", "plusmn": "\u00B1", "plussim;": "\u2A26", "plustwo;": "\u2A27", "pm;": "\u00B1", "Poincareplane;": "\u210C", "pointint;": "\u2A15", "popf;": "\uD835\uDD61", "Popf;": "\u2119", "pound;": "\u00A3", "pound": "\u00A3", "prap;": "\u2AB7", "Pr;": "\u2ABB", "pr;": "\u227A", "prcue;": "\u227C", "precapprox;": "\u2AB7", "prec;": "\u227A", "preccurlyeq;": "\u227C", "Precedes;": "\u227A", "PrecedesEqual;": "\u2AAF", "PrecedesSlantEqual;": "\u227C", "PrecedesTilde;": "\u227E", "preceq;": "\u2AAF", "precnapprox;": "\u2AB9", "precneqq;": "\u2AB5", "precnsim;": "\u22E8", "pre;": "\u2AAF", "prE;": "\u2AB3", "precsim;": "\u227E", "prime;": "\u2032", "Prime;": "\u2033", "primes;": "\u2119", "prnap;": "\u2AB9", "prnE;": "\u2AB5", "prnsim;": "\u22E8", "prod;": "\u220F", "Product;": "\u220F", "profalar;": "\u232E", "profline;": "\u2312", "profsurf;": "\u2313", "prop;": "\u221D", "Proportional;": "\u221D", "Proportion;": "\u2237", "propto;": "\u221D", "prsim;": "\u227E", "prurel;": "\u22B0", "Pscr;": "\uD835\uDCAB", "pscr;": "\uD835\uDCC5", "Psi;": "\u03A8", "psi;": "\u03C8", "puncsp;": "\u2008", "Qfr;": "\uD835\uDD14", "qfr;": "\uD835\uDD2E", "qint;": "\u2A0C", "qopf;": "\uD835\uDD62", "Qopf;": "\u211A", "qprime;": "\u2057", "Qscr;": "\uD835\uDCAC", "qscr;": "\uD835\uDCC6", "quaternions;": "\u210D", "quatint;": "\u2A16", "quest;": "\u003F", "questeq;": "\u225F", "quot;": "\u0022", "quot": "\u0022", "QUOT;": "\u0022", "QUOT": "\u0022", "rAarr;": "\u21DB", "race;": "\u223D\u0331", "Racute;": "\u0154", "racute;": "\u0155", "radic;": "\u221A", "raemptyv;": "\u29B3", "rang;": "\u27E9", "Rang;": "\u27EB", "rangd;": "\u2992", "range;": "\u29A5", "rangle;": "\u27E9", "raquo;": "\u00BB", "raquo": "\u00BB", "rarrap;": "\u2975", "rarrb;": "\u21E5", "rarrbfs;": "\u2920", "rarrc;": "\u2933", "rarr;": "\u2192", "Rarr;": "\u21A0", "rArr;": "\u21D2", "rarrfs;": "\u291E", "rarrhk;": "\u21AA", "rarrlp;": "\u21AC", "rarrpl;": "\u2945", "rarrsim;": "\u2974", "Rarrtl;": "\u2916", "rarrtl;": "\u21A3", "rarrw;": "\u219D", "ratail;": "\u291A", "rAtail;": "\u291C", "ratio;": "\u2236", "rationals;": "\u211A", "rbarr;": "\u290D", "rBarr;": "\u290F", "RBarr;": "\u2910", "rbbrk;": "\u2773", "rbrace;": "\u007D", "rbrack;": "\u005D", "rbrke;": "\u298C", "rbrksld;": "\u298E", "rbrkslu;": "\u2990", "Rcaron;": "\u0158", "rcaron;": "\u0159", "Rcedil;": "\u0156", "rcedil;": "\u0157", "rceil;": "\u2309", "rcub;": "\u007D", "Rcy;": "\u0420", "rcy;": "\u0440", "rdca;": "\u2937", "rdldhar;": "\u2969", "rdquo;": "\u201D", "rdquor;": "\u201D", "rdsh;": "\u21B3", "real;": "\u211C", "realine;": "\u211B", "realpart;": "\u211C", "reals;": "\u211D", "Re;": "\u211C", "rect;": "\u25AD", "reg;": "\u00AE", "reg": "\u00AE", "REG;": "\u00AE", "REG": "\u00AE", "ReverseElement;": "\u220B", "ReverseEquilibrium;": "\u21CB", "ReverseUpEquilibrium;": "\u296F", "rfisht;": "\u297D", "rfloor;": "\u230B", "rfr;": "\uD835\uDD2F", "Rfr;": "\u211C", "rHar;": "\u2964", "rhard;": "\u21C1", "rharu;": "\u21C0", "rharul;": "\u296C", "Rho;": "\u03A1", "rho;": "\u03C1", "rhov;": "\u03F1", "RightAngleBracket;": "\u27E9", "RightArrowBar;": "\u21E5", "rightarrow;": "\u2192", "RightArrow;": "\u2192", "Rightarrow;": "\u21D2", "RightArrowLeftArrow;": "\u21C4", "rightarrowtail;": "\u21A3", "RightCeiling;": "\u2309", "RightDoubleBracket;": "\u27E7", "RightDownTeeVector;": "\u295D", "RightDownVectorBar;": "\u2955", "RightDownVector;": "\u21C2", "RightFloor;": "\u230B", "rightharpoondown;": "\u21C1", "rightharpoonup;": "\u21C0", "rightleftarrows;": "\u21C4", "rightleftharpoons;": "\u21CC", "rightrightarrows;": "\u21C9", "rightsquigarrow;": "\u219D", "RightTeeArrow;": "\u21A6", "RightTee;": "\u22A2", "RightTeeVector;": "\u295B", "rightthreetimes;": "\u22CC", "RightTriangleBar;": "\u29D0", "RightTriangle;": "\u22B3", "RightTriangleEqual;": "\u22B5", "RightUpDownVector;": "\u294F", "RightUpTeeVector;": "\u295C", "RightUpVectorBar;": "\u2954", "RightUpVector;": "\u21BE", "RightVectorBar;": "\u2953", "RightVector;": "\u21C0", "ring;": "\u02DA", "risingdotseq;": "\u2253", "rlarr;": "\u21C4", "rlhar;": "\u21CC", "rlm;": "\u200F", "rmoustache;": "\u23B1", "rmoust;": "\u23B1", "rnmid;": "\u2AEE", "roang;": "\u27ED", "roarr;": "\u21FE", "robrk;": "\u27E7", "ropar;": "\u2986", "ropf;": "\uD835\uDD63", "Ropf;": "\u211D", "roplus;": "\u2A2E", "rotimes;": "\u2A35", "RoundImplies;": "\u2970", "rpar;": "\u0029", "rpargt;": "\u2994", "rppolint;": "\u2A12", "rrarr;": "\u21C9", "Rrightarrow;": "\u21DB", "rsaquo;": "\u203A", "rscr;": "\uD835\uDCC7", "Rscr;": "\u211B", "rsh;": "\u21B1", "Rsh;": "\u21B1", "rsqb;": "\u005D", "rsquo;": "\u2019", "rsquor;": "\u2019", "rthree;": "\u22CC", "rtimes;": "\u22CA", "rtri;": "\u25B9", "rtrie;": "\u22B5", "rtrif;": "\u25B8", "rtriltri;": "\u29CE", "RuleDelayed;": "\u29F4", "ruluhar;": "\u2968", "rx;": "\u211E", "Sacute;": "\u015A", "sacute;": "\u015B", "sbquo;": "\u201A", "scap;": "\u2AB8", "Scaron;": "\u0160", "scaron;": "\u0161", "Sc;": "\u2ABC", "sc;": "\u227B", "sccue;": "\u227D", "sce;": "\u2AB0", "scE;": "\u2AB4", "Scedil;": "\u015E", "scedil;": "\u015F", "Scirc;": "\u015C", "scirc;": "\u015D", "scnap;": "\u2ABA", "scnE;": "\u2AB6", "scnsim;": "\u22E9", "scpolint;": "\u2A13", "scsim;": "\u227F", "Scy;": "\u0421", "scy;": "\u0441", "sdotb;": "\u22A1", "sdot;": "\u22C5", "sdote;": "\u2A66", "searhk;": "\u2925", "searr;": "\u2198", "seArr;": "\u21D8", "searrow;": "\u2198", "sect;": "\u00A7", "sect": "\u00A7", "semi;": "\u003B", "seswar;": "\u2929", "setminus;": "\u2216", "setmn;": "\u2216", "sext;": "\u2736", "Sfr;": "\uD835\uDD16", "sfr;": "\uD835\uDD30", "sfrown;": "\u2322", "sharp;": "\u266F", "SHCHcy;": "\u0429", "shchcy;": "\u0449", "SHcy;": "\u0428", "shcy;": "\u0448", "ShortDownArrow;": "\u2193", "ShortLeftArrow;": "\u2190", "shortmid;": "\u2223", "shortparallel;": "\u2225", "ShortRightArrow;": "\u2192", "ShortUpArrow;": "\u2191", "shy;": "\u00AD", "shy": "\u00AD", "Sigma;": "\u03A3", "sigma;": "\u03C3", "sigmaf;": "\u03C2", "sigmav;": "\u03C2", "sim;": "\u223C", "simdot;": "\u2A6A", "sime;": "\u2243", "simeq;": "\u2243", "simg;": "\u2A9E", "simgE;": "\u2AA0", "siml;": "\u2A9D", "simlE;": "\u2A9F", "simne;": "\u2246", "simplus;": "\u2A24", "simrarr;": "\u2972", "slarr;": "\u2190", "SmallCircle;": "\u2218", "smallsetminus;": "\u2216", "smashp;": "\u2A33", "smeparsl;": "\u29E4", "smid;": "\u2223", "smile;": "\u2323", "smt;": "\u2AAA", "smte;": "\u2AAC", "smtes;": "\u2AAC\uFE00", "SOFTcy;": "\u042C", "softcy;": "\u044C", "solbar;": "\u233F", "solb;": "\u29C4", "sol;": "\u002F", "Sopf;": "\uD835\uDD4A", "sopf;": "\uD835\uDD64", "spades;": "\u2660", "spadesuit;": "\u2660", "spar;": "\u2225", "sqcap;": "\u2293", "sqcaps;": "\u2293\uFE00", "sqcup;": "\u2294", "sqcups;": "\u2294\uFE00", "Sqrt;": "\u221A", "sqsub;": "\u228F", "sqsube;": "\u2291", "sqsubset;": "\u228F", "sqsubseteq;": "\u2291", "sqsup;": "\u2290", "sqsupe;": "\u2292", "sqsupset;": "\u2290", "sqsupseteq;": "\u2292", "square;": "\u25A1", "Square;": "\u25A1", "SquareIntersection;": "\u2293", "SquareSubset;": "\u228F", "SquareSubsetEqual;": "\u2291", "SquareSuperset;": "\u2290", "SquareSupersetEqual;": "\u2292", "SquareUnion;": "\u2294", "squarf;": "\u25AA", "squ;": "\u25A1", "squf;": "\u25AA", "srarr;": "\u2192", "Sscr;": "\uD835\uDCAE", "sscr;": "\uD835\uDCC8", "ssetmn;": "\u2216", "ssmile;": "\u2323", "sstarf;": "\u22C6", "Star;": "\u22C6", "star;": "\u2606", "starf;": "\u2605", "straightepsilon;": "\u03F5", "straightphi;": "\u03D5", "strns;": "\u00AF", "sub;": "\u2282", "Sub;": "\u22D0", "subdot;": "\u2ABD", "subE;": "\u2AC5", "sube;": "\u2286", "subedot;": "\u2AC3", "submult;": "\u2AC1", "subnE;": "\u2ACB", "subne;": "\u228A", "subplus;": "\u2ABF", "subrarr;": "\u2979", "subset;": "\u2282", "Subset;": "\u22D0", "subseteq;": "\u2286", "subseteqq;": "\u2AC5", "SubsetEqual;": "\u2286", "subsetneq;": "\u228A", "subsetneqq;": "\u2ACB", "subsim;": "\u2AC7", "subsub;": "\u2AD5", "subsup;": "\u2AD3", "succapprox;": "\u2AB8", "succ;": "\u227B", "succcurlyeq;": "\u227D", "Succeeds;": "\u227B", "SucceedsEqual;": "\u2AB0", "SucceedsSlantEqual;": "\u227D", "SucceedsTilde;": "\u227F", "succeq;": "\u2AB0", "succnapprox;": "\u2ABA", "succneqq;": "\u2AB6", "succnsim;": "\u22E9", "succsim;": "\u227F", "SuchThat;": "\u220B", "sum;": "\u2211", "Sum;": "\u2211", "sung;": "\u266A", "sup1;": "\u00B9", "sup1": "\u00B9", "sup2;": "\u00B2", "sup2": "\u00B2", "sup3;": "\u00B3", "sup3": "\u00B3", "sup;": "\u2283", "Sup;": "\u22D1", "supdot;": "\u2ABE", "supdsub;": "\u2AD8", "supE;": "\u2AC6", "supe;": "\u2287", "supedot;": "\u2AC4", "Superset;": "\u2283", "SupersetEqual;": "\u2287", "suphsol;": "\u27C9", "suphsub;": "\u2AD7", "suplarr;": "\u297B", "supmult;": "\u2AC2", "supnE;": "\u2ACC", "supne;": "\u228B", "supplus;": "\u2AC0", "supset;": "\u2283", "Supset;": "\u22D1", "supseteq;": "\u2287", "supseteqq;": "\u2AC6", "supsetneq;": "\u228B", "supsetneqq;": "\u2ACC", "supsim;": "\u2AC8", "supsub;": "\u2AD4", "supsup;": "\u2AD6", "swarhk;": "\u2926", "swarr;": "\u2199", "swArr;": "\u21D9", "swarrow;": "\u2199", "swnwar;": "\u292A", "szlig;": "\u00DF", "szlig": "\u00DF", "Tab;": "\u0009", "target;": "\u2316", "Tau;": "\u03A4", "tau;": "\u03C4", "tbrk;": "\u23B4", "Tcaron;": "\u0164", "tcaron;": "\u0165", "Tcedil;": "\u0162", "tcedil;": "\u0163", "Tcy;": "\u0422", "tcy;": "\u0442", "tdot;": "\u20DB", "telrec;": "\u2315", "Tfr;": "\uD835\uDD17", "tfr;": "\uD835\uDD31", "there4;": "\u2234", "therefore;": "\u2234", "Therefore;": "\u2234", "Theta;": "\u0398", "theta;": "\u03B8", "thetasym;": "\u03D1", "thetav;": "\u03D1", "thickapprox;": "\u2248", "thicksim;": "\u223C", "ThickSpace;": "\u205F\u200A", "ThinSpace;": "\u2009", "thinsp;": "\u2009", "thkap;": "\u2248", "thksim;": "\u223C", "THORN;": "\u00DE", "THORN": "\u00DE", "thorn;": "\u00FE", "thorn": "\u00FE", "tilde;": "\u02DC", "Tilde;": "\u223C", "TildeEqual;": "\u2243", "TildeFullEqual;": "\u2245", "TildeTilde;": "\u2248", "timesbar;": "\u2A31", "timesb;": "\u22A0", "times;": "\u00D7", "times": "\u00D7", "timesd;": "\u2A30", "tint;": "\u222D", "toea;": "\u2928", "topbot;": "\u2336", "topcir;": "\u2AF1", "top;": "\u22A4", "Topf;": "\uD835\uDD4B", "topf;": "\uD835\uDD65", "topfork;": "\u2ADA", "tosa;": "\u2929", "tprime;": "\u2034", "trade;": "\u2122", "TRADE;": "\u2122", "triangle;": "\u25B5", "triangledown;": "\u25BF", "triangleleft;": "\u25C3", "trianglelefteq;": "\u22B4", "triangleq;": "\u225C", "triangleright;": "\u25B9", "trianglerighteq;": "\u22B5", "tridot;": "\u25EC", "trie;": "\u225C", "triminus;": "\u2A3A", "TripleDot;": "\u20DB", "triplus;": "\u2A39", "trisb;": "\u29CD", "tritime;": "\u2A3B", "trpezium;": "\u23E2", "Tscr;": "\uD835\uDCAF", "tscr;": "\uD835\uDCC9", "TScy;": "\u0426", "tscy;": "\u0446", "TSHcy;": "\u040B", "tshcy;": "\u045B", "Tstrok;": "\u0166", "tstrok;": "\u0167", "twixt;": "\u226C", "twoheadleftarrow;": "\u219E", "twoheadrightarrow;": "\u21A0", "Uacute;": "\u00DA", "Uacute": "\u00DA", "uacute;": "\u00FA", "uacute": "\u00FA", "uarr;": "\u2191", "Uarr;": "\u219F", "uArr;": "\u21D1", "Uarrocir;": "\u2949", "Ubrcy;": "\u040E", "ubrcy;": "\u045E", "Ubreve;": "\u016C", "ubreve;": "\u016D", "Ucirc;": "\u00DB", "Ucirc": "\u00DB", "ucirc;": "\u00FB", "ucirc": "\u00FB", "Ucy;": "\u0423", "ucy;": "\u0443", "udarr;": "\u21C5", "Udblac;": "\u0170", "udblac;": "\u0171", "udhar;": "\u296E", "ufisht;": "\u297E", "Ufr;": "\uD835\uDD18", "ufr;": "\uD835\uDD32", "Ugrave;": "\u00D9", "Ugrave": "\u00D9", "ugrave;": "\u00F9", "ugrave": "\u00F9", "uHar;": "\u2963", "uharl;": "\u21BF", "uharr;": "\u21BE", "uhblk;": "\u2580", "ulcorn;": "\u231C", "ulcorner;": "\u231C", "ulcrop;": "\u230F", "ultri;": "\u25F8", "Umacr;": "\u016A", "umacr;": "\u016B", "uml;": "\u00A8", "uml": "\u00A8", "UnderBar;": "\u005F", "UnderBrace;": "\u23DF", "UnderBracket;": "\u23B5", "UnderParenthesis;": "\u23DD", "Union;": "\u22C3", "UnionPlus;": "\u228E", "Uogon;": "\u0172", "uogon;": "\u0173", "Uopf;": "\uD835\uDD4C", "uopf;": "\uD835\uDD66", "UpArrowBar;": "\u2912", "uparrow;": "\u2191", "UpArrow;": "\u2191", "Uparrow;": "\u21D1", "UpArrowDownArrow;": "\u21C5", "updownarrow;": "\u2195", "UpDownArrow;": "\u2195", "Updownarrow;": "\u21D5", "UpEquilibrium;": "\u296E", "upharpoonleft;": "\u21BF", "upharpoonright;": "\u21BE", "uplus;": "\u228E", "UpperLeftArrow;": "\u2196", "UpperRightArrow;": "\u2197", "upsi;": "\u03C5", "Upsi;": "\u03D2", "upsih;": "\u03D2", "Upsilon;": "\u03A5", "upsilon;": "\u03C5", "UpTeeArrow;": "\u21A5", "UpTee;": "\u22A5", "upuparrows;": "\u21C8", "urcorn;": "\u231D", "urcorner;": "\u231D", "urcrop;": "\u230E", "Uring;": "\u016E", "uring;": "\u016F", "urtri;": "\u25F9", "Uscr;": "\uD835\uDCB0", "uscr;": "\uD835\uDCCA", "utdot;": "\u22F0", "Utilde;": "\u0168", "utilde;": "\u0169", "utri;": "\u25B5", "utrif;": "\u25B4", "uuarr;": "\u21C8", "Uuml;": "\u00DC", "Uuml": "\u00DC", "uuml;": "\u00FC", "uuml": "\u00FC", "uwangle;": "\u29A7", "vangrt;": "\u299C", "varepsilon;": "\u03F5", "varkappa;": "\u03F0", "varnothing;": "\u2205", "varphi;": "\u03D5", "varpi;": "\u03D6", "varpropto;": "\u221D", "varr;": "\u2195", "vArr;": "\u21D5", "varrho;": "\u03F1", "varsigma;": "\u03C2", "varsubsetneq;": "\u228A\uFE00", "varsubsetneqq;": "\u2ACB\uFE00", "varsupsetneq;": "\u228B\uFE00", "varsupsetneqq;": "\u2ACC\uFE00", "vartheta;": "\u03D1", "vartriangleleft;": "\u22B2", "vartriangleright;": "\u22B3", "vBar;": "\u2AE8", "Vbar;": "\u2AEB", "vBarv;": "\u2AE9", "Vcy;": "\u0412", "vcy;": "\u0432", "vdash;": "\u22A2", "vDash;": "\u22A8", "Vdash;": "\u22A9", "VDash;": "\u22AB", "Vdashl;": "\u2AE6", "veebar;": "\u22BB", "vee;": "\u2228", "Vee;": "\u22C1", "veeeq;": "\u225A", "vellip;": "\u22EE", "verbar;": "\u007C", "Verbar;": "\u2016", "vert;": "\u007C", "Vert;": "\u2016", "VerticalBar;": "\u2223", "VerticalLine;": "\u007C", "VerticalSeparator;": "\u2758", "VerticalTilde;": "\u2240", "VeryThinSpace;": "\u200A", "Vfr;": "\uD835\uDD19", "vfr;": "\uD835\uDD33", "vltri;": "\u22B2", "vnsub;": "\u2282\u20D2", "vnsup;": "\u2283\u20D2", "Vopf;": "\uD835\uDD4D", "vopf;": "\uD835\uDD67", "vprop;": "\u221D", "vrtri;": "\u22B3", "Vscr;": "\uD835\uDCB1", "vscr;": "\uD835\uDCCB", "vsubnE;": "\u2ACB\uFE00", "vsubne;": "\u228A\uFE00", "vsupnE;": "\u2ACC\uFE00", "vsupne;": "\u228B\uFE00", "Vvdash;": "\u22AA", "vzigzag;": "\u299A", "Wcirc;": "\u0174", "wcirc;": "\u0175", "wedbar;": "\u2A5F", "wedge;": "\u2227", "Wedge;": "\u22C0", "wedgeq;": "\u2259", "weierp;": "\u2118", "Wfr;": "\uD835\uDD1A", "wfr;": "\uD835\uDD34", "Wopf;": "\uD835\uDD4E", "wopf;": "\uD835\uDD68", "wp;": "\u2118", "wr;": "\u2240", "wreath;": "\u2240", "Wscr;": "\uD835\uDCB2", "wscr;": "\uD835\uDCCC", "xcap;": "\u22C2", "xcirc;": "\u25EF", "xcup;": "\u22C3", "xdtri;": "\u25BD", "Xfr;": "\uD835\uDD1B", "xfr;": "\uD835\uDD35", "xharr;": "\u27F7", "xhArr;": "\u27FA", "Xi;": "\u039E", "xi;": "\u03BE", "xlarr;": "\u27F5", "xlArr;": "\u27F8", "xmap;": "\u27FC", "xnis;": "\u22FB", "xodot;": "\u2A00", "Xopf;": "\uD835\uDD4F", "xopf;": "\uD835\uDD69", "xoplus;": "\u2A01", "xotime;": "\u2A02", "xrarr;": "\u27F6", "xrArr;": "\u27F9", "Xscr;": "\uD835\uDCB3", "xscr;": "\uD835\uDCCD", "xsqcup;": "\u2A06", "xuplus;": "\u2A04", "xutri;": "\u25B3", "xvee;": "\u22C1", "xwedge;": "\u22C0", "Yacute;": "\u00DD", "Yacute": "\u00DD", "yacute;": "\u00FD", "yacute": "\u00FD", "YAcy;": "\u042F", "yacy;": "\u044F", "Ycirc;": "\u0176", "ycirc;": "\u0177", "Ycy;": "\u042B", "ycy;": "\u044B", "yen;": "\u00A5", "yen": "\u00A5", "Yfr;": "\uD835\uDD1C", "yfr;": "\uD835\uDD36", "YIcy;": "\u0407", "yicy;": "\u0457", "Yopf;": "\uD835\uDD50", "yopf;": "\uD835\uDD6A", "Yscr;": "\uD835\uDCB4", "yscr;": "\uD835\uDCCE", "YUcy;": "\u042E", "yucy;": "\u044E", "yuml;": "\u00FF", "yuml": "\u00FF", "Yuml;": "\u0178", "Zacute;": "\u0179", "zacute;": "\u017A", "Zcaron;": "\u017D", "zcaron;": "\u017E", "Zcy;": "\u0417", "zcy;": "\u0437", "Zdot;": "\u017B", "zdot;": "\u017C", "zeetrf;": "\u2128", "ZeroWidthSpace;": "\u200B", "Zeta;": "\u0396", "zeta;": "\u03B6", "zfr;": "\uD835\uDD37", "Zfr;": "\u2128", "ZHcy;": "\u0416", "zhcy;": "\u0436", "zigrarr;": "\u21DD", "zopf;": "\uD835\uDD6B", "Zopf;": "\u2124", "Zscr;": "\uD835\uDCB5", "zscr;": "\uD835\uDCCF", "zwj;": "\u200D", "zwnj;": "\u200C" }; }, {}], 13:[function(_dereq_,module,exports){ var util = _dereq_('util/'); var pSlice = Array.prototype.slice; var hasOwn = Object.prototype.hasOwnProperty; var assert = module.exports = ok; assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { var err = new Error(); if (err.stack) { var out = err.stack; var fn_name = stackStartFunction.name; var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (util.isUndefined(value)) { return '' + value; } if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; } function truncate(s, n) { if (util.isString(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } assert.fail = fail; function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; function _deepEqual(actual, expected) { if (actual === expected) { return true; } else if (util.isBuffer(actual) && util.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; } else if (!util.isObject(actual) && !util.isObject(expected)) { return actual == expected; } else { return objEquiv(actual, expected); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) return false; if (a.prototype !== b.prototype) return false; if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try { var ka = objectKeys(a), kb = objectKeys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } if (ka.length != kb.length) return false; ka.sort(); kb.sort(); for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (util.isString(expected)) { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; }, {"util/":15}], 14:[function(_dereq_,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } }, {}], 15:[function(_dereq_,module,exports){ (function (process,global){ var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; exports.deprecate = function(fn, msg) { if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; function inspect(obj, opts) { var ctx = { seen: [], stylize: stylizeNoColor }; if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { ctx.showHidden = opts; } else if (opts) { exports._extend(ctx, opts); } if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { if (ctx.customInspect && value && isFunction(value.inspect) && value.inspect !== exports.inspect && !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; if (isArray(value)) { array = true; braces = ['[', ']']; } if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = _dereq_('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; exports.inherits = _dereq_('inherits'); exports._extend = function(origin, add) { if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,_dereq_("/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) }, {"./support/isBuffer":14,"/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":18,"inherits":17}], 16:[function(_dereq_,module,exports){ function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; EventEmitter.defaultMaxListeners = 10; EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) this._events[type] = listener; else if (isObject(this._events[type])) this._events[type].push(listener); else this._events[type] = [this._events[type], listener]; if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } }, {}], 17:[function(_dereq_,module,exports){ if (typeof Object.create === 'function') { module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } }, {}], 18:[function(_dereq_,module,exports){ var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.once = noop; process.off = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); } process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; }, {}], 19:[function(_dereq_,module,exports){ module.exports=_dereq_(14) }, {}], 20:[function(_dereq_,module,exports){ module.exports=_dereq_(15) }, {"./support/isBuffer":19,"/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":18,"inherits":17}]},{},[9]) (9) }); ace.define("ace/mode/html_worker",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/worker/mirror","ace/mode/html/saxparser"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var Mirror = require("../worker/mirror").Mirror; var SAXParser = require("./html/saxparser").SAXParser; var errorTypes = { "expected-doctype-but-got-start-tag": "info", "expected-doctype-but-got-chars": "info", "non-html-root": "info" } var Worker = exports.Worker = function(sender) { Mirror.call(this, sender); this.setTimeout(400); this.context = null; }; oop.inherits(Worker, Mirror); (function() { this.setOptions = function(options) { this.context = options.context; }; this.onUpdate = function() { var value = this.doc.getValue(); if (!value) return; var parser = new SAXParser(); var errors = []; var noop = function(){}; parser.contentHandler = { startDocument: noop, endDocument: noop, startElement: noop, endElement: noop, characters: noop }; parser.errorHandler = { error: function(message, location, code) { errors.push({ row: location.line, column: location.column, text: message, type: errorTypes[code] || "error" }); } }; if (this.context) parser.parseFragment(value, this.context); else parser.parse(value); this.sender.emit("error", errors); }; }).call(Worker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/worker-javascript.js
12,528
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; if (!window.console) { window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; } window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); } } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!(range instanceof Range)) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject(array[i]); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } if (Object.prototype.toString.call(obj) !== "[object Object]") return obj; copy = {}; for (var key in obj) copy[key] = deepCopy(obj[key]); return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/javascript/jshint",["require","exports","module"], function(require, exports, module) { module.exports = (function outer (modules, cache, entry) { var previousRequire = typeof require == "function" && require; function newRequire(name, jumped){ if(!cache[name]) { if(!modules[name]) { var currentRequire = typeof require == "function" && require; if (!jumped && currentRequire) return currentRequire(name, true); if (previousRequire) return previousRequire(name, true); var err = new Error('Cannot find module \'' + name + '\''); err.code = 'MODULE_NOT_FOUND'; throw err; } var m = cache[name] = {exports:{}}; modules[name][0].call(m.exports, function(x){ var id = modules[name][1][x]; return newRequire(id ? id : x); },m,m.exports,outer,modules,cache,entry); } return cache[name].exports; } for(var i=0;i<entry.length;i++) newRequire(entry[i]); return newRequire(entry[0]); }) ({"/node_modules/browserify/node_modules/events/events.js":[function(_dereq_,module,exports){ function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; EventEmitter.defaultMaxListeners = 10; EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) this._events[type] = listener; else if (isObject(this._events[type])) this._events[type].push(listener); else this._events[type] = [this._events[type], listener]; if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],"/node_modules/jshint/data/ascii-identifier-data.js":[function(_dereq_,module,exports){ var identifierStartTable = []; for (var i = 0; i < 128; i++) { identifierStartTable[i] = i === 36 || // $ i >= 65 && i <= 90 || // A-Z i === 95 || // _ i >= 97 && i <= 122; // a-z } var identifierPartTable = []; for (var i = 0; i < 128; i++) { identifierPartTable[i] = identifierStartTable[i] || // $, _, A-Z, a-z i >= 48 && i <= 57; // 0-9 } module.exports = { asciiIdentifierStartTable: identifierStartTable, asciiIdentifierPartTable: identifierPartTable }; },{}],"/node_modules/jshint/lodash.js":[function(_dereq_,module,exports){ (function (global){ ;(function() { var undefined; var VERSION = '3.7.0'; var FUNC_ERROR_TEXT = 'Expected a function'; var argsTag = '[object Arguments]', arrayTag = '[object Array]', boolTag = '[object Boolean]', dateTag = '[object Date]', errorTag = '[object Error]', funcTag = '[object Function]', mapTag = '[object Map]', numberTag = '[object Number]', objectTag = '[object Object]', regexpTag = '[object RegExp]', setTag = '[object Set]', stringTag = '[object String]', weakMapTag = '[object WeakMap]'; var arrayBufferTag = '[object ArrayBuffer]', float32Tag = '[object Float32Array]', float64Tag = '[object Float64Array]', int8Tag = '[object Int8Array]', int16Tag = '[object Int16Array]', int32Tag = '[object Int32Array]', uint8Tag = '[object Uint8Array]', uint8ClampedTag = '[object Uint8ClampedArray]', uint16Tag = '[object Uint16Array]', uint32Tag = '[object Uint32Array]'; var reIsDeepProp = /\.|\[(?:[^[\]]+|(["'])(?:(?!\1)[^\n\\]|\\.)*?)\1\]/, reIsPlainProp = /^\w*$/, rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\n\\]|\\.)*?)\2)\]/g; var reRegExpChars = /[.*+?^${}()|[\]\/\\]/g, reHasRegExpChars = RegExp(reRegExpChars.source); var reEscapeChar = /\\(\\)?/g; var reFlags = /\w*$/; var reIsHostCtor = /^\[object .+?Constructor\]$/; var typedArrayTags = {}; typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = typedArrayTags[uint32Tag] = true; typedArrayTags[argsTag] = typedArrayTags[arrayTag] = typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = typedArrayTags[dateTag] = typedArrayTags[errorTag] = typedArrayTags[funcTag] = typedArrayTags[mapTag] = typedArrayTags[numberTag] = typedArrayTags[objectTag] = typedArrayTags[regexpTag] = typedArrayTags[setTag] = typedArrayTags[stringTag] = typedArrayTags[weakMapTag] = false; var cloneableTags = {}; cloneableTags[argsTag] = cloneableTags[arrayTag] = cloneableTags[arrayBufferTag] = cloneableTags[boolTag] = cloneableTags[dateTag] = cloneableTags[float32Tag] = cloneableTags[float64Tag] = cloneableTags[int8Tag] = cloneableTags[int16Tag] = cloneableTags[int32Tag] = cloneableTags[numberTag] = cloneableTags[objectTag] = cloneableTags[regexpTag] = cloneableTags[stringTag] = cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; cloneableTags[errorTag] = cloneableTags[funcTag] = cloneableTags[mapTag] = cloneableTags[setTag] = cloneableTags[weakMapTag] = false; var objectTypes = { 'function': true, 'object': true }; var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; var freeGlobal = freeExports && freeModule && typeof global == 'object' && global && global.Object && global; var freeSelf = objectTypes[typeof self] && self && self.Object && self; var freeWindow = objectTypes[typeof window] && window && window.Object && window; var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; var root = freeGlobal || ((freeWindow !== (this && this.window)) && freeWindow) || freeSelf || this; function baseFindIndex(array, predicate, fromRight) { var length = array.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { if (predicate(array[index], index, array)) { return index; } } return -1; } function baseIndexOf(array, value, fromIndex) { if (value !== value) { return indexOfNaN(array, fromIndex); } var index = fromIndex - 1, length = array.length; while (++index < length) { if (array[index] === value) { return index; } } return -1; } function baseIsFunction(value) { return typeof value == 'function' || false; } function baseToString(value) { if (typeof value == 'string') { return value; } return value == null ? '' : (value + ''); } function indexOfNaN(array, fromIndex, fromRight) { var length = array.length, index = fromIndex + (fromRight ? 0 : -1); while ((fromRight ? index-- : ++index < length)) { var other = array[index]; if (other !== other) { return index; } } return -1; } function isObjectLike(value) { return !!value && typeof value == 'object'; } var arrayProto = Array.prototype, objectProto = Object.prototype; var fnToString = Function.prototype.toString; var hasOwnProperty = objectProto.hasOwnProperty; var objToString = objectProto.toString; var reIsNative = RegExp('^' + escapeRegExp(objToString) .replace(/toString|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' ); var ArrayBuffer = isNative(ArrayBuffer = root.ArrayBuffer) && ArrayBuffer, bufferSlice = isNative(bufferSlice = ArrayBuffer && new ArrayBuffer(0).slice) && bufferSlice, floor = Math.floor, getOwnPropertySymbols = isNative(getOwnPropertySymbols = Object.getOwnPropertySymbols) && getOwnPropertySymbols, getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, push = arrayProto.push, preventExtensions = isNative(Object.preventExtensions = Object.preventExtensions) && preventExtensions, propertyIsEnumerable = objectProto.propertyIsEnumerable, Uint8Array = isNative(Uint8Array = root.Uint8Array) && Uint8Array; var Float64Array = (function() { try { var func = isNative(func = root.Float64Array) && func, result = new func(new ArrayBuffer(10), 0, 1) && func; } catch(e) {} return result; }()); var nativeAssign = (function() { var object = { '1': 0 }, func = preventExtensions && isNative(func = Object.assign) && func; try { func(preventExtensions(object), 'xo'); } catch(e) {} return !object[1] && func; }()); var nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, nativeMax = Math.max, nativeMin = Math.min; var NEGATIVE_INFINITY = Number.NEGATIVE_INFINITY; var MAX_ARRAY_LENGTH = Math.pow(2, 32) - 1, MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1, HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1; var FLOAT64_BYTES_PER_ELEMENT = Float64Array ? Float64Array.BYTES_PER_ELEMENT : 0; var MAX_SAFE_INTEGER = Math.pow(2, 53) - 1; function lodash() { } var support = lodash.support = {}; (function(x) { var Ctor = function() { this.x = x; }, object = { '0': x, 'length': x }, props = []; Ctor.prototype = { 'valueOf': x, 'y': x }; for (var key in new Ctor) { props.push(key); } support.funcDecomp = /\bthis\b/.test(function() { return this; }); support.funcNames = typeof Function.name == 'string'; try { support.nonEnumArgs = !propertyIsEnumerable.call(arguments, 1); } catch(e) { support.nonEnumArgs = true; } }(1, 0)); function arrayCopy(source, array) { var index = -1, length = source.length; array || (array = Array(length)); while (++index < length) { array[index] = source[index]; } return array; } function arrayEach(array, iteratee) { var index = -1, length = array.length; while (++index < length) { if (iteratee(array[index], index, array) === false) { break; } } return array; } function arrayFilter(array, predicate) { var index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index]; if (predicate(value, index, array)) { result[++resIndex] = value; } } return result; } function arrayMap(array, iteratee) { var index = -1, length = array.length, result = Array(length); while (++index < length) { result[index] = iteratee(array[index], index, array); } return result; } function arrayMax(array) { var index = -1, length = array.length, result = NEGATIVE_INFINITY; while (++index < length) { var value = array[index]; if (value > result) { result = value; } } return result; } function arraySome(array, predicate) { var index = -1, length = array.length; while (++index < length) { if (predicate(array[index], index, array)) { return true; } } return false; } function assignWith(object, source, customizer) { var props = keys(source); push.apply(props, getSymbols(source)); var index = -1, length = props.length; while (++index < length) { var key = props[index], value = object[key], result = customizer(value, source[key], key, object, source); if ((result === result ? (result !== value) : (value === value)) || (value === undefined && !(key in object))) { object[key] = result; } } return object; } var baseAssign = nativeAssign || function(object, source) { return source == null ? object : baseCopy(source, getSymbols(source), baseCopy(source, keys(source), object)); }; function baseCopy(source, props, object) { object || (object = {}); var index = -1, length = props.length; while (++index < length) { var key = props[index]; object[key] = source[key]; } return object; } function baseCallback(func, thisArg, argCount) { var type = typeof func; if (type == 'function') { return thisArg === undefined ? func : bindCallback(func, thisArg, argCount); } if (func == null) { return identity; } if (type == 'object') { return baseMatches(func); } return thisArg === undefined ? property(func) : baseMatchesProperty(func, thisArg); } function baseClone(value, isDeep, customizer, key, object, stackA, stackB) { var result; if (customizer) { result = object ? customizer(value, key, object) : customizer(value); } if (result !== undefined) { return result; } if (!isObject(value)) { return value; } var isArr = isArray(value); if (isArr) { result = initCloneArray(value); if (!isDeep) { return arrayCopy(value, result); } } else { var tag = objToString.call(value), isFunc = tag == funcTag; if (tag == objectTag || tag == argsTag || (isFunc && !object)) { result = initCloneObject(isFunc ? {} : value); if (!isDeep) { return baseAssign(result, value); } } else { return cloneableTags[tag] ? initCloneByTag(value, tag, isDeep) : (object ? value : {}); } } stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == value) { return stackB[length]; } } stackA.push(value); stackB.push(result); (isArr ? arrayEach : baseForOwn)(value, function(subValue, key) { result[key] = baseClone(subValue, isDeep, customizer, key, value, stackA, stackB); }); return result; } var baseEach = createBaseEach(baseForOwn); function baseFilter(collection, predicate) { var result = []; baseEach(collection, function(value, index, collection) { if (predicate(value, index, collection)) { result.push(value); } }); return result; } var baseFor = createBaseFor(); function baseForIn(object, iteratee) { return baseFor(object, iteratee, keysIn); } function baseForOwn(object, iteratee) { return baseFor(object, iteratee, keys); } function baseGet(object, path, pathKey) { if (object == null) { return; } if (pathKey !== undefined && pathKey in toObject(object)) { path = [pathKey]; } var index = -1, length = path.length; while (object != null && ++index < length) { var result = object = object[path[index]]; } return result; } function baseIsEqual(value, other, customizer, isLoose, stackA, stackB) { if (value === other) { return value !== 0 || (1 / value == 1 / other); } var valType = typeof value, othType = typeof other; if ((valType != 'function' && valType != 'object' && othType != 'function' && othType != 'object') || value == null || other == null) { return value !== value && other !== other; } return baseIsEqualDeep(value, other, baseIsEqual, customizer, isLoose, stackA, stackB); } function baseIsEqualDeep(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objIsArr = isArray(object), othIsArr = isArray(other), objTag = arrayTag, othTag = arrayTag; if (!objIsArr) { objTag = objToString.call(object); if (objTag == argsTag) { objTag = objectTag; } else if (objTag != objectTag) { objIsArr = isTypedArray(object); } } if (!othIsArr) { othTag = objToString.call(other); if (othTag == argsTag) { othTag = objectTag; } else if (othTag != objectTag) { othIsArr = isTypedArray(other); } } var objIsObj = objTag == objectTag, othIsObj = othTag == objectTag, isSameTag = objTag == othTag; if (isSameTag && !(objIsArr || objIsObj)) { return equalByTag(object, other, objTag); } if (!isLoose) { var valWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'), othWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__'); if (valWrapped || othWrapped) { return equalFunc(valWrapped ? object.value() : object, othWrapped ? other.value() : other, customizer, isLoose, stackA, stackB); } } if (!isSameTag) { return false; } stackA || (stackA = []); stackB || (stackB = []); var length = stackA.length; while (length--) { if (stackA[length] == object) { return stackB[length] == other; } } stackA.push(object); stackB.push(other); var result = (objIsArr ? equalArrays : equalObjects)(object, other, equalFunc, customizer, isLoose, stackA, stackB); stackA.pop(); stackB.pop(); return result; } function baseIsMatch(object, props, values, strictCompareFlags, customizer) { var index = -1, length = props.length, noCustomizer = !customizer; while (++index < length) { if ((noCustomizer && strictCompareFlags[index]) ? values[index] !== object[props[index]] : !(props[index] in object) ) { return false; } } index = -1; while (++index < length) { var key = props[index], objValue = object[key], srcValue = values[index]; if (noCustomizer && strictCompareFlags[index]) { var result = objValue !== undefined || (key in object); } else { result = customizer ? customizer(objValue, srcValue, key) : undefined; if (result === undefined) { result = baseIsEqual(srcValue, objValue, customizer, true); } } if (!result) { return false; } } return true; } function baseMatches(source) { var props = keys(source), length = props.length; if (!length) { return constant(true); } if (length == 1) { var key = props[0], value = source[key]; if (isStrictComparable(value)) { return function(object) { if (object == null) { return false; } return object[key] === value && (value !== undefined || (key in toObject(object))); }; } } var values = Array(length), strictCompareFlags = Array(length); while (length--) { value = source[props[length]]; values[length] = value; strictCompareFlags[length] = isStrictComparable(value); } return function(object) { return object != null && baseIsMatch(toObject(object), props, values, strictCompareFlags); }; } function baseMatchesProperty(path, value) { var isArr = isArray(path), isCommon = isKey(path) && isStrictComparable(value), pathKey = (path + ''); path = toPath(path); return function(object) { if (object == null) { return false; } var key = pathKey; object = toObject(object); if ((isArr || !isCommon) && !(key in object)) { object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); if (object == null) { return false; } key = last(path); object = toObject(object); } return object[key] === value ? (value !== undefined || (key in object)) : baseIsEqual(value, object[key], null, true); }; } function baseMerge(object, source, customizer, stackA, stackB) { if (!isObject(object)) { return object; } var isSrcArr = isLength(source.length) && (isArray(source) || isTypedArray(source)); if (!isSrcArr) { var props = keys(source); push.apply(props, getSymbols(source)); } arrayEach(props || source, function(srcValue, key) { if (props) { key = srcValue; srcValue = source[key]; } if (isObjectLike(srcValue)) { stackA || (stackA = []); stackB || (stackB = []); baseMergeDeep(object, source, key, baseMerge, customizer, stackA, stackB); } else { var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; } if ((isSrcArr || result !== undefined) && (isCommon || (result === result ? (result !== value) : (value === value)))) { object[key] = result; } } }); return object; } function baseMergeDeep(object, source, key, mergeFunc, customizer, stackA, stackB) { var length = stackA.length, srcValue = source[key]; while (length--) { if (stackA[length] == srcValue) { object[key] = stackB[length]; return; } } var value = object[key], result = customizer ? customizer(value, srcValue, key, object, source) : undefined, isCommon = result === undefined; if (isCommon) { result = srcValue; if (isLength(srcValue.length) && (isArray(srcValue) || isTypedArray(srcValue))) { result = isArray(value) ? value : (getLength(value) ? arrayCopy(value) : []); } else if (isPlainObject(srcValue) || isArguments(srcValue)) { result = isArguments(value) ? toPlainObject(value) : (isPlainObject(value) ? value : {}); } else { isCommon = false; } } stackA.push(srcValue); stackB.push(result); if (isCommon) { object[key] = mergeFunc(result, srcValue, customizer, stackA, stackB); } else if (result === result ? (result !== value) : (value === value)) { object[key] = result; } } function baseProperty(key) { return function(object) { return object == null ? undefined : object[key]; }; } function basePropertyDeep(path) { var pathKey = (path + ''); path = toPath(path); return function(object) { return baseGet(object, path, pathKey); }; } function baseSlice(array, start, end) { var index = -1, length = array.length; start = start == null ? 0 : (+start || 0); if (start < 0) { start = -start > length ? 0 : (length + start); } end = (end === undefined || end > length) ? length : (+end || 0); if (end < 0) { end += length; } length = start > end ? 0 : ((end - start) >>> 0); start >>>= 0; var result = Array(length); while (++index < length) { result[index] = array[index + start]; } return result; } function baseSome(collection, predicate) { var result; baseEach(collection, function(value, index, collection) { result = predicate(value, index, collection); return !result; }); return !!result; } function baseValues(object, props) { var index = -1, length = props.length, result = Array(length); while (++index < length) { result[index] = object[props[index]]; } return result; } function binaryIndex(array, value, retHighest) { var low = 0, high = array ? array.length : low; if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { while (low < high) { var mid = (low + high) >>> 1, computed = array[mid]; if (retHighest ? (computed <= value) : (computed < value)) { low = mid + 1; } else { high = mid; } } return high; } return binaryIndexBy(array, value, identity, retHighest); } function binaryIndexBy(array, value, iteratee, retHighest) { value = iteratee(value); var low = 0, high = array ? array.length : 0, valIsNaN = value !== value, valIsUndef = value === undefined; while (low < high) { var mid = floor((low + high) / 2), computed = iteratee(array[mid]), isReflexive = computed === computed; if (valIsNaN) { var setLow = isReflexive || retHighest; } else if (valIsUndef) { setLow = isReflexive && (retHighest || computed !== undefined); } else { setLow = retHighest ? (computed <= value) : (computed < value); } if (setLow) { low = mid + 1; } else { high = mid; } } return nativeMin(high, MAX_ARRAY_INDEX); } function bindCallback(func, thisArg, argCount) { if (typeof func != 'function') { return identity; } if (thisArg === undefined) { return func; } switch (argCount) { case 1: return function(value) { return func.call(thisArg, value); }; case 3: return function(value, index, collection) { return func.call(thisArg, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(thisArg, accumulator, value, index, collection); }; case 5: return function(value, other, key, object, source) { return func.call(thisArg, value, other, key, object, source); }; } return function() { return func.apply(thisArg, arguments); }; } function bufferClone(buffer) { return bufferSlice.call(buffer, 0); } if (!bufferSlice) { bufferClone = !(ArrayBuffer && Uint8Array) ? constant(null) : function(buffer) { var byteLength = buffer.byteLength, floatLength = Float64Array ? floor(byteLength / FLOAT64_BYTES_PER_ELEMENT) : 0, offset = floatLength * FLOAT64_BYTES_PER_ELEMENT, result = new ArrayBuffer(byteLength); if (floatLength) { var view = new Float64Array(result, 0, floatLength); view.set(new Float64Array(buffer, 0, floatLength)); } if (byteLength != offset) { view = new Uint8Array(result, offset); view.set(new Uint8Array(buffer, offset)); } return result; }; } function createAssigner(assigner) { return restParam(function(object, sources) { var index = -1, length = object == null ? 0 : sources.length, customizer = length > 2 && sources[length - 2], guard = length > 2 && sources[2], thisArg = length > 1 && sources[length - 1]; if (typeof customizer == 'function') { customizer = bindCallback(customizer, thisArg, 5); length -= 2; } else { customizer = typeof thisArg == 'function' ? thisArg : null; length -= (customizer ? 1 : 0); } if (guard && isIterateeCall(sources[0], sources[1], guard)) { customizer = length < 3 ? null : customizer; length = 1; } while (++index < length) { var source = sources[index]; if (source) { assigner(object, source, customizer); } } return object; }); } function createBaseEach(eachFunc, fromRight) { return function(collection, iteratee) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { return eachFunc(collection, iteratee); } var index = fromRight ? length : -1, iterable = toObject(collection); while ((fromRight ? index-- : ++index < length)) { if (iteratee(iterable[index], index, iterable) === false) { break; } } return collection; }; } function createBaseFor(fromRight) { return function(object, iteratee, keysFunc) { var iterable = toObject(object), props = keysFunc(object), length = props.length, index = fromRight ? length : -1; while ((fromRight ? index-- : ++index < length)) { var key = props[index]; if (iteratee(iterable[key], key, iterable) === false) { break; } } return object; }; } function createFindIndex(fromRight) { return function(array, predicate, thisArg) { if (!(array && array.length)) { return -1; } predicate = getCallback(predicate, thisArg, 3); return baseFindIndex(array, predicate, fromRight); }; } function createForEach(arrayFunc, eachFunc) { return function(collection, iteratee, thisArg) { return (typeof iteratee == 'function' && thisArg === undefined && isArray(collection)) ? arrayFunc(collection, iteratee) : eachFunc(collection, bindCallback(iteratee, thisArg, 3)); }; } function equalArrays(array, other, equalFunc, customizer, isLoose, stackA, stackB) { var index = -1, arrLength = array.length, othLength = other.length, result = true; if (arrLength != othLength && !(isLoose && othLength > arrLength)) { return false; } while (result && ++index < arrLength) { var arrValue = array[index], othValue = other[index]; result = undefined; if (customizer) { result = isLoose ? customizer(othValue, arrValue, index) : customizer(arrValue, othValue, index); } if (result === undefined) { if (isLoose) { var othIndex = othLength; while (othIndex--) { othValue = other[othIndex]; result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); if (result) { break; } } } else { result = (arrValue && arrValue === othValue) || equalFunc(arrValue, othValue, customizer, isLoose, stackA, stackB); } } } return !!result; } function equalByTag(object, other, tag) { switch (tag) { case boolTag: case dateTag: return +object == +other; case errorTag: return object.name == other.name && object.message == other.message; case numberTag: return (object != +object) ? other != +other : (object == 0 ? ((1 / object) == (1 / other)) : object == +other); case regexpTag: case stringTag: return object == (other + ''); } return false; } function equalObjects(object, other, equalFunc, customizer, isLoose, stackA, stackB) { var objProps = keys(object), objLength = objProps.length, othProps = keys(other), othLength = othProps.length; if (objLength != othLength && !isLoose) { return false; } var skipCtor = isLoose, index = -1; while (++index < objLength) { var key = objProps[index], result = isLoose ? key in other : hasOwnProperty.call(other, key); if (result) { var objValue = object[key], othValue = other[key]; result = undefined; if (customizer) { result = isLoose ? customizer(othValue, objValue, key) : customizer(objValue, othValue, key); } if (result === undefined) { result = (objValue && objValue === othValue) || equalFunc(objValue, othValue, customizer, isLoose, stackA, stackB); } } if (!result) { return false; } skipCtor || (skipCtor = key == 'constructor'); } if (!skipCtor) { var objCtor = object.constructor, othCtor = other.constructor; if (objCtor != othCtor && ('constructor' in object && 'constructor' in other) && !(typeof objCtor == 'function' && objCtor instanceof objCtor && typeof othCtor == 'function' && othCtor instanceof othCtor)) { return false; } } return true; } function getCallback(func, thisArg, argCount) { var result = lodash.callback || callback; result = result === callback ? baseCallback : result; return argCount ? result(func, thisArg, argCount) : result; } function getIndexOf(collection, target, fromIndex) { var result = lodash.indexOf || indexOf; result = result === indexOf ? baseIndexOf : result; return collection ? result(collection, target, fromIndex) : result; } var getLength = baseProperty('length'); var getSymbols = !getOwnPropertySymbols ? constant([]) : function(object) { return getOwnPropertySymbols(toObject(object)); }; function initCloneArray(array) { var length = array.length, result = new array.constructor(length); if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) { result.index = array.index; result.input = array.input; } return result; } function initCloneObject(object) { var Ctor = object.constructor; if (!(typeof Ctor == 'function' && Ctor instanceof Ctor)) { Ctor = Object; } return new Ctor; } function initCloneByTag(object, tag, isDeep) { var Ctor = object.constructor; switch (tag) { case arrayBufferTag: return bufferClone(object); case boolTag: case dateTag: return new Ctor(+object); case float32Tag: case float64Tag: case int8Tag: case int16Tag: case int32Tag: case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag: var buffer = object.buffer; return new Ctor(isDeep ? bufferClone(buffer) : buffer, object.byteOffset, object.length); case numberTag: case stringTag: return new Ctor(object); case regexpTag: var result = new Ctor(object.source, reFlags.exec(object)); result.lastIndex = object.lastIndex; } return result; } function isIndex(value, length) { value = +value; length = length == null ? MAX_SAFE_INTEGER : length; return value > -1 && value % 1 == 0 && value < length; } function isIterateeCall(value, index, object) { if (!isObject(object)) { return false; } var type = typeof index; if (type == 'number') { var length = getLength(object), prereq = isLength(length) && isIndex(index, length); } else { prereq = type == 'string' && index in object; } if (prereq) { var other = object[index]; return value === value ? (value === other) : (other !== other); } return false; } function isKey(value, object) { var type = typeof value; if ((type == 'string' && reIsPlainProp.test(value)) || type == 'number') { return true; } if (isArray(value)) { return false; } var result = !reIsDeepProp.test(value); return result || (object != null && value in toObject(object)); } function isLength(value) { return typeof value == 'number' && value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; } function isStrictComparable(value) { return value === value && (value === 0 ? ((1 / value) > 0) : !isObject(value)); } function shimIsPlainObject(value) { var Ctor, support = lodash.support; if (!(isObjectLike(value) && objToString.call(value) == objectTag) || (!hasOwnProperty.call(value, 'constructor') && (Ctor = value.constructor, typeof Ctor == 'function' && !(Ctor instanceof Ctor)))) { return false; } var result; baseForIn(value, function(subValue, key) { result = key; }); return result === undefined || hasOwnProperty.call(value, result); } function shimKeys(object) { var props = keysIn(object), propsLength = props.length, length = propsLength && object.length, support = lodash.support; var allowIndexes = length && isLength(length) && (isArray(object) || (support.nonEnumArgs && isArguments(object))); var index = -1, result = []; while (++index < propsLength) { var key = props[index]; if ((allowIndexes && isIndex(key, length)) || hasOwnProperty.call(object, key)) { result.push(key); } } return result; } function toObject(value) { return isObject(value) ? value : Object(value); } function toPath(value) { if (isArray(value)) { return value; } var result = []; baseToString(value).replace(rePropName, function(match, number, quote, string) { result.push(quote ? string.replace(reEscapeChar, '$1') : (number || match)); }); return result; } var findLastIndex = createFindIndex(true); function indexOf(array, value, fromIndex) { var length = array ? array.length : 0; if (!length) { return -1; } if (typeof fromIndex == 'number') { fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : fromIndex; } else if (fromIndex) { var index = binaryIndex(array, value), other = array[index]; if (value === value ? (value === other) : (other !== other)) { return index; } return -1; } return baseIndexOf(array, value, fromIndex || 0); } function last(array) { var length = array ? array.length : 0; return length ? array[length - 1] : undefined; } function slice(array, start, end) { var length = array ? array.length : 0; if (!length) { return []; } if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { start = 0; end = length; } return baseSlice(array, start, end); } function unzip(array) { var index = -1, length = (array && array.length && arrayMax(arrayMap(array, getLength))) >>> 0, result = Array(length); while (++index < length) { result[index] = arrayMap(array, baseProperty(index)); } return result; } var zip = restParam(unzip); var forEach = createForEach(arrayEach, baseEach); function includes(collection, target, fromIndex, guard) { var length = collection ? getLength(collection) : 0; if (!isLength(length)) { collection = values(collection); length = collection.length; } if (!length) { return false; } if (typeof fromIndex != 'number' || (guard && isIterateeCall(target, fromIndex, guard))) { fromIndex = 0; } else { fromIndex = fromIndex < 0 ? nativeMax(length + fromIndex, 0) : (fromIndex || 0); } return (typeof collection == 'string' || !isArray(collection) && isString(collection)) ? (fromIndex < length && collection.indexOf(target, fromIndex) > -1) : (getIndexOf(collection, target, fromIndex) > -1); } function reject(collection, predicate, thisArg) { var func = isArray(collection) ? arrayFilter : baseFilter; predicate = getCallback(predicate, thisArg, 3); return func(collection, function(value, index, collection) { return !predicate(value, index, collection); }); } function some(collection, predicate, thisArg) { var func = isArray(collection) ? arraySome : baseSome; if (thisArg && isIterateeCall(collection, predicate, thisArg)) { predicate = null; } if (typeof predicate != 'function' || thisArg !== undefined) { predicate = getCallback(predicate, thisArg, 3); } return func(collection, predicate); } function restParam(func, start) { if (typeof func != 'function') { throw new TypeError(FUNC_ERROR_TEXT); } start = nativeMax(start === undefined ? (func.length - 1) : (+start || 0), 0); return function() { var args = arguments, index = -1, length = nativeMax(args.length - start, 0), rest = Array(length); while (++index < length) { rest[index] = args[start + index]; } switch (start) { case 0: return func.call(this, rest); case 1: return func.call(this, args[0], rest); case 2: return func.call(this, args[0], args[1], rest); } var otherArgs = Array(start + 1); index = -1; while (++index < start) { otherArgs[index] = args[index]; } otherArgs[start] = rest; return func.apply(this, otherArgs); }; } function clone(value, isDeep, customizer, thisArg) { if (isDeep && typeof isDeep != 'boolean' && isIterateeCall(value, isDeep, customizer)) { isDeep = false; } else if (typeof isDeep == 'function') { thisArg = customizer; customizer = isDeep; isDeep = false; } customizer = typeof customizer == 'function' && bindCallback(customizer, thisArg, 1); return baseClone(value, isDeep, customizer); } function isArguments(value) { var length = isObjectLike(value) ? value.length : undefined; return isLength(length) && objToString.call(value) == argsTag; } var isArray = nativeIsArray || function(value) { return isObjectLike(value) && isLength(value.length) && objToString.call(value) == arrayTag; }; function isEmpty(value) { if (value == null) { return true; } var length = getLength(value); if (isLength(length) && (isArray(value) || isString(value) || isArguments(value) || (isObjectLike(value) && isFunction(value.splice)))) { return !length; } return !keys(value).length; } var isFunction = !(baseIsFunction(/x/) || (Uint8Array && !baseIsFunction(Uint8Array))) ? baseIsFunction : function(value) { return objToString.call(value) == funcTag; }; function isObject(value) { var type = typeof value; return type == 'function' || (!!value && type == 'object'); } function isNative(value) { if (value == null) { return false; } if (objToString.call(value) == funcTag) { return reIsNative.test(fnToString.call(value)); } return isObjectLike(value) && reIsHostCtor.test(value); } function isNumber(value) { return typeof value == 'number' || (isObjectLike(value) && objToString.call(value) == numberTag); } var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { if (!(value && objToString.call(value) == objectTag)) { return false; } var valueOf = value.valueOf, objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); return objProto ? (value == objProto || getPrototypeOf(value) == objProto) : shimIsPlainObject(value); }; function isString(value) { return typeof value == 'string' || (isObjectLike(value) && objToString.call(value) == stringTag); } function isTypedArray(value) { return isObjectLike(value) && isLength(value.length) && !!typedArrayTags[objToString.call(value)]; } function toPlainObject(value) { return baseCopy(value, keysIn(value)); } var assign = createAssigner(function(object, source, customizer) { return customizer ? assignWith(object, source, customizer) : baseAssign(object, source); }); function has(object, path) { if (object == null) { return false; } var result = hasOwnProperty.call(object, path); if (!result && !isKey(path)) { path = toPath(path); object = path.length == 1 ? object : baseGet(object, baseSlice(path, 0, -1)); path = last(path); result = object != null && hasOwnProperty.call(object, path); } return result; } var keys = !nativeKeys ? shimKeys : function(object) { if (object) { var Ctor = object.constructor, length = object.length; } if ((typeof Ctor == 'function' && Ctor.prototype === object) || (typeof object != 'function' && isLength(length))) { return shimKeys(object); } return isObject(object) ? nativeKeys(object) : []; }; function keysIn(object) { if (object == null) { return []; } if (!isObject(object)) { object = Object(object); } var length = object.length; length = (length && isLength(length) && (isArray(object) || (support.nonEnumArgs && isArguments(object))) && length) || 0; var Ctor = object.constructor, index = -1, isProto = typeof Ctor == 'function' && Ctor.prototype === object, result = Array(length), skipIndexes = length > 0; while (++index < length) { result[index] = (index + ''); } for (var key in object) { if (!(skipIndexes && isIndex(key, length)) && !(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) { result.push(key); } } return result; } var merge = createAssigner(baseMerge); function values(object) { return baseValues(object, keys(object)); } function escapeRegExp(string) { string = baseToString(string); return (string && reHasRegExpChars.test(string)) ? string.replace(reRegExpChars, '\\$&') : string; } function callback(func, thisArg, guard) { if (guard && isIterateeCall(func, thisArg, guard)) { thisArg = null; } return baseCallback(func, thisArg); } function constant(value) { return function() { return value; }; } function identity(value) { return value; } function property(path) { return isKey(path) ? baseProperty(path) : basePropertyDeep(path); } lodash.assign = assign; lodash.callback = callback; lodash.constant = constant; lodash.forEach = forEach; lodash.keys = keys; lodash.keysIn = keysIn; lodash.merge = merge; lodash.property = property; lodash.reject = reject; lodash.restParam = restParam; lodash.slice = slice; lodash.toPlainObject = toPlainObject; lodash.unzip = unzip; lodash.values = values; lodash.zip = zip; lodash.each = forEach; lodash.extend = assign; lodash.iteratee = callback; lodash.clone = clone; lodash.escapeRegExp = escapeRegExp; lodash.findLastIndex = findLastIndex; lodash.has = has; lodash.identity = identity; lodash.includes = includes; lodash.indexOf = indexOf; lodash.isArguments = isArguments; lodash.isArray = isArray; lodash.isEmpty = isEmpty; lodash.isFunction = isFunction; lodash.isNative = isNative; lodash.isNumber = isNumber; lodash.isObject = isObject; lodash.isPlainObject = isPlainObject; lodash.isString = isString; lodash.isTypedArray = isTypedArray; lodash.last = last; lodash.some = some; lodash.any = some; lodash.contains = includes; lodash.include = includes; lodash.VERSION = VERSION; if (freeExports && freeModule) { if (moduleExports) { (freeModule.exports = lodash)._ = lodash; } else { freeExports._ = lodash; } } else { root._ = lodash; } }.call(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],"/node_modules/jshint/src/jshint.js":[function(_dereq_,module,exports){ var _ = _dereq_("../lodash"); var events = _dereq_("events"); var vars = _dereq_("./vars.js"); var messages = _dereq_("./messages.js"); var Lexer = _dereq_("./lex.js").Lexer; var reg = _dereq_("./reg.js"); var state = _dereq_("./state.js").state; var style = _dereq_("./style.js"); var options = _dereq_("./options.js"); var scopeManager = _dereq_("./scope-manager.js"); var JSHINT = (function() { "use strict"; var api, // Extension API bang = { "<" : true, "<=" : true, "==" : true, "===": true, "!==": true, "!=" : true, ">" : true, ">=" : true, "+" : true, "-" : true, "*" : true, "/" : true, "%" : true }, declared, // Globals that were declared using /*global ... */ syntax. functionicity = [ "closure", "exception", "global", "label", "outer", "unused", "var" ], functions, // All of the functions inblock, indent, lookahead, lex, member, membersOnly, predefined, // Global variables defined by option stack, urls, extraModules = [], emitter = new events.EventEmitter(); function checkOption(name, t) { name = name.trim(); if (/^[+-]W\d{3}$/g.test(name)) { return true; } if (options.validNames.indexOf(name) === -1) { if (t.type !== "jslint" && !_.has(options.removed, name)) { error("E001", t, name); return false; } } return true; } function isString(obj) { return Object.prototype.toString.call(obj) === "[object String]"; } function isIdentifier(tkn, value) { if (!tkn) return false; if (!tkn.identifier || tkn.value !== value) return false; return true; } function isReserved(token) { if (!token.reserved) { return false; } var meta = token.meta; if (meta && meta.isFutureReservedWord && state.inES5()) { if (!meta.es5) { return false; } if (meta.strictOnly) { if (!state.option.strict && !state.isStrict()) { return false; } } if (token.isProperty) { return false; } } return true; } function supplant(str, data) { return str.replace(/\{([^{}]*)\}/g, function(a, b) { var r = data[b]; return typeof r === "string" || typeof r === "number" ? r : a; }); } function combine(dest, src) { Object.keys(src).forEach(function(name) { if (_.has(JSHINT.blacklist, name)) return; dest[name] = src[name]; }); } function processenforceall() { if (state.option.enforceall) { for (var enforceopt in options.bool.enforcing) { if (state.option[enforceopt] === undefined && !options.noenforceall[enforceopt]) { state.option[enforceopt] = true; } } for (var relaxopt in options.bool.relaxing) { if (state.option[relaxopt] === undefined) { state.option[relaxopt] = false; } } } } function assume() { processenforceall(); if (!state.option.esversion && !state.option.moz) { if (state.option.es3) { state.option.esversion = 3; } else if (state.option.esnext) { state.option.esversion = 6; } else { state.option.esversion = 5; } } if (state.inES5()) { combine(predefined, vars.ecmaIdentifiers[5]); } if (state.inES6()) { combine(predefined, vars.ecmaIdentifiers[6]); } if (state.option.module) { if (state.option.strict === true) { state.option.strict = "global"; } if (!state.inES6()) { warning("W134", state.tokens.next, "module", 6); } } if (state.option.couch) { combine(predefined, vars.couch); } if (state.option.qunit) { combine(predefined, vars.qunit); } if (state.option.rhino) { combine(predefined, vars.rhino); } if (state.option.shelljs) { combine(predefined, vars.shelljs); combine(predefined, vars.node); } if (state.option.typed) { combine(predefined, vars.typed); } if (state.option.phantom) { combine(predefined, vars.phantom); if (state.option.strict === true) { state.option.strict = "global"; } } if (state.option.prototypejs) { combine(predefined, vars.prototypejs); } if (state.option.node) { combine(predefined, vars.node); combine(predefined, vars.typed); if (state.option.strict === true) { state.option.strict = "global"; } } if (state.option.devel) { combine(predefined, vars.devel); } if (state.option.dojo) { combine(predefined, vars.dojo); } if (state.option.browser) { combine(predefined, vars.browser); combine(predefined, vars.typed); } if (state.option.browserify) { combine(predefined, vars.browser); combine(predefined, vars.typed); combine(predefined, vars.browserify); if (state.option.strict === true) { state.option.strict = "global"; } } if (state.option.nonstandard) { combine(predefined, vars.nonstandard); } if (state.option.jasmine) { combine(predefined, vars.jasmine); } if (state.option.jquery) { combine(predefined, vars.jquery); } if (state.option.mootools) { combine(predefined, vars.mootools); } if (state.option.worker) { combine(predefined, vars.worker); } if (state.option.wsh) { combine(predefined, vars.wsh); } if (state.option.globalstrict && state.option.strict !== false) { state.option.strict = "global"; } if (state.option.yui) { combine(predefined, vars.yui); } if (state.option.mocha) { combine(predefined, vars.mocha); } } function quit(code, line, chr) { var percentage = Math.floor((line / state.lines.length) * 100); var message = messages.errors[code].desc; throw { name: "JSHintError", line: line, character: chr, message: message + " (" + percentage + "% scanned).", raw: message, code: code }; } function removeIgnoredMessages() { var ignored = state.ignoredLines; if (_.isEmpty(ignored)) return; JSHINT.errors = _.reject(JSHINT.errors, function(err) { return ignored[err.line] }); } function warning(code, t, a, b, c, d) { var ch, l, w, msg; if (/^W\d{3}$/.test(code)) { if (state.ignored[code]) return; msg = messages.warnings[code]; } else if (/E\d{3}/.test(code)) { msg = messages.errors[code]; } else if (/I\d{3}/.test(code)) { msg = messages.info[code]; } t = t || state.tokens.next || {}; if (t.id === "(end)") { // `~ t = state.tokens.curr; } l = t.line || 0; ch = t.from || 0; w = { id: "(error)", raw: msg.desc, code: msg.code, evidence: state.lines[l - 1] || "", line: l, character: ch, scope: JSHINT.scope, a: a, b: b, c: c, d: d }; w.reason = supplant(msg.desc, w); JSHINT.errors.push(w); removeIgnoredMessages(); if (JSHINT.errors.length >= state.option.maxerr) quit("E043", l, ch); return w; } function warningAt(m, l, ch, a, b, c, d) { return warning(m, { line: l, from: ch }, a, b, c, d); } function error(m, t, a, b, c, d) { warning(m, t, a, b, c, d); } function errorAt(m, l, ch, a, b, c, d) { return error(m, { line: l, from: ch }, a, b, c, d); } function addInternalSrc(elem, src) { var i; i = { id: "(internal)", elem: elem, value: src }; JSHINT.internals.push(i); return i; } function doOption() { var nt = state.tokens.next; var body = nt.body.match(/(-\s+)?[^\s,:]+(?:\s*:\s*(-\s+)?[^\s,]+)?/g) || []; var predef = {}; if (nt.type === "globals") { body.forEach(function(g, idx) { g = g.split(":"); var key = (g[0] || "").trim(); var val = (g[1] || "").trim(); if (key === "-" || !key.length) { if (idx > 0 && idx === body.length - 1) { return; } error("E002", nt); return; } if (key.charAt(0) === "-") { key = key.slice(1); val = false; JSHINT.blacklist[key] = key; delete predefined[key]; } else { predef[key] = (val === "true"); } }); combine(predefined, predef); for (var key in predef) { if (_.has(predef, key)) { declared[key] = nt; } } } if (nt.type === "exported") { body.forEach(function(e, idx) { if (!e.length) { if (idx > 0 && idx === body.length - 1) { return; } error("E002", nt); return; } state.funct["(scope)"].addExported(e); }); } if (nt.type === "members") { membersOnly = membersOnly || {}; body.forEach(function(m) { var ch1 = m.charAt(0); var ch2 = m.charAt(m.length - 1); if (ch1 === ch2 && (ch1 === "\"" || ch1 === "'")) { m = m .substr(1, m.length - 2) .replace("\\\"", "\""); } membersOnly[m] = false; }); } var numvals = [ "maxstatements", "maxparams", "maxdepth", "maxcomplexity", "maxerr", "maxlen", "indent" ]; if (nt.type === "jshint" || nt.type === "jslint") { body.forEach(function(g) { g = g.split(":"); var key = (g[0] || "").trim(); var val = (g[1] || "").trim(); if (!checkOption(key, nt)) { return; } if (numvals.indexOf(key) >= 0) { if (val !== "false") { val = +val; if (typeof val !== "number" || !isFinite(val) || val <= 0 || Math.floor(val) !== val) { error("E032", nt, g[1].trim()); return; } state.option[key] = val; } else { state.option[key] = key === "indent" ? 4 : false; } return; } if (key === "validthis") { if (state.funct["(global)"]) return void error("E009"); if (val !== "true" && val !== "false") return void error("E002", nt); state.option.validthis = (val === "true"); return; } if (key === "quotmark") { switch (val) { case "true": case "false": state.option.quotmark = (val === "true"); break; case "double": case "single": state.option.quotmark = val; break; default: error("E002", nt); } return; } if (key === "shadow") { switch (val) { case "true": state.option.shadow = true; break; case "outer": state.option.shadow = "outer"; break; case "false": case "inner": state.option.shadow = "inner"; break; default: error("E002", nt); } return; } if (key === "unused") { switch (val) { case "true": state.option.unused = true; break; case "false": state.option.unused = false; break; case "vars": case "strict": state.option.unused = val; break; default: error("E002", nt); } return; } if (key === "latedef") { switch (val) { case "true": state.option.latedef = true; break; case "false": state.option.latedef = false; break; case "nofunc": state.option.latedef = "nofunc"; break; default: error("E002", nt); } return; } if (key === "ignore") { switch (val) { case "line": state.ignoredLines[nt.line] = true; removeIgnoredMessages(); break; default: error("E002", nt); } return; } if (key === "strict") { switch (val) { case "true": state.option.strict = true; break; case "false": state.option.strict = false; break; case "func": case "global": case "implied": state.option.strict = val; break; default: error("E002", nt); } return; } if (key === "module") { if (!hasParsedCode(state.funct)) { error("E055", state.tokens.next, "module"); } } var esversions = { es3 : 3, es5 : 5, esnext: 6 }; if (_.has(esversions, key)) { switch (val) { case "true": state.option.moz = false; state.option.esversion = esversions[key]; break; case "false": if (!state.option.moz) { state.option.esversion = 5; } break; default: error("E002", nt); } return; } if (key === "esversion") { switch (val) { case "5": if (state.inES5(true)) { warning("I003"); } case "3": case "6": state.option.moz = false; state.option.esversion = +val; break; case "2015": state.option.moz = false; state.option.esversion = 6; break; default: error("E002", nt); } if (!hasParsedCode(state.funct)) { error("E055", state.tokens.next, "esversion"); } return; } var match = /^([+-])(W\d{3})$/g.exec(key); if (match) { state.ignored[match[2]] = (match[1] === "-"); return; } var tn; if (val === "true" || val === "false") { if (nt.type === "jslint") { tn = options.renamed[key] || key; state.option[tn] = (val === "true"); if (options.inverted[tn] !== undefined) { state.option[tn] = !state.option[tn]; } } else { state.option[key] = (val === "true"); } if (key === "newcap") { state.option["(explicitNewcap)"] = true; } return; } error("E002", nt); }); assume(); } } function peek(p) { var i = p || 0, j = lookahead.length, t; if (i < j) { return lookahead[i]; } while (j <= i) { t = lookahead[j]; if (!t) { t = lookahead[j] = lex.token(); } j += 1; } if (!t && state.tokens.next.id === "(end)") { return state.tokens.next; } return t; } function peekIgnoreEOL() { var i = 0; var t; do { t = peek(i++); } while (t.id === "(endline)"); return t; } function advance(id, t) { switch (state.tokens.curr.id) { case "(number)": if (state.tokens.next.id === ".") { warning("W005", state.tokens.curr); } break; case "-": if (state.tokens.next.id === "-" || state.tokens.next.id === "--") { warning("W006"); } break; case "+": if (state.tokens.next.id === "+" || state.tokens.next.id === "++") { warning("W007"); } break; } if (id && state.tokens.next.id !== id) { if (t) { if (state.tokens.next.id === "(end)") { error("E019", t, t.id); } else { error("E020", state.tokens.next, id, t.id, t.line, state.tokens.next.value); } } else if (state.tokens.next.type !== "(identifier)" || state.tokens.next.value !== id) { warning("W116", state.tokens.next, id, state.tokens.next.value); } } state.tokens.prev = state.tokens.curr; state.tokens.curr = state.tokens.next; for (;;) { state.tokens.next = lookahead.shift() || lex.token(); if (!state.tokens.next) { // No more tokens left, give up quit("E041", state.tokens.curr.line); } if (state.tokens.next.id === "(end)" || state.tokens.next.id === "(error)") { return; } if (state.tokens.next.check) { state.tokens.next.check(); } if (state.tokens.next.isSpecial) { if (state.tokens.next.type === "falls through") { state.tokens.curr.caseFallsThrough = true; } else { doOption(); } } else { if (state.tokens.next.id !== "(endline)") { break; } } } } function isInfix(token) { return token.infix || (!token.identifier && !token.template && !!token.led); } function isEndOfExpr() { var curr = state.tokens.curr; var next = state.tokens.next; if (next.id === ";" || next.id === "}" || next.id === ":") { return true; } if (isInfix(next) === isInfix(curr) || (curr.id === "yield" && state.inMoz())) { return curr.line !== startLine(next); } return false; } function isBeginOfExpr(prev) { return !prev.left && prev.arity !== "unary"; } function expression(rbp, initial) { var left, isArray = false, isObject = false, isLetExpr = false; state.nameStack.push(); if (!initial && state.tokens.next.value === "let" && peek(0).value === "(") { if (!state.inMoz()) { warning("W118", state.tokens.next, "let expressions"); } isLetExpr = true; state.funct["(scope)"].stack(); advance("let"); advance("("); state.tokens.prev.fud(); advance(")"); } if (state.tokens.next.id === "(end)") error("E006", state.tokens.curr); var isDangerous = state.option.asi && state.tokens.prev.line !== startLine(state.tokens.curr) && _.contains(["]", ")"], state.tokens.prev.id) && _.contains(["[", "("], state.tokens.curr.id); if (isDangerous) warning("W014", state.tokens.curr, state.tokens.curr.id); advance(); if (initial) { state.funct["(verb)"] = state.tokens.curr.value; state.tokens.curr.beginsStmt = true; } if (initial === true && state.tokens.curr.fud) { left = state.tokens.curr.fud(); } else { if (state.tokens.curr.nud) { left = state.tokens.curr.nud(); } else { error("E030", state.tokens.curr, state.tokens.curr.id); } while ((rbp < state.tokens.next.lbp || state.tokens.next.type === "(template)") && !isEndOfExpr()) { isArray = state.tokens.curr.value === "Array"; isObject = state.tokens.curr.value === "Object"; if (left && (left.value || (left.first && left.first.value))) { if (left.value !== "new" || (left.first && left.first.value && left.first.value === ".")) { isArray = false; if (left.value !== state.tokens.curr.value) { isObject = false; } } } advance(); if (isArray && state.tokens.curr.id === "(" && state.tokens.next.id === ")") { warning("W009", state.tokens.curr); } if (isObject && state.tokens.curr.id === "(" && state.tokens.next.id === ")") { warning("W010", state.tokens.curr); } if (left && state.tokens.curr.led) { left = state.tokens.curr.led(left); } else { error("E033", state.tokens.curr, state.tokens.curr.id); } } } if (isLetExpr) { state.funct["(scope)"].unstack(); } state.nameStack.pop(); return left; } function startLine(token) { return token.startLine || token.line; } function nobreaknonadjacent(left, right) { left = left || state.tokens.curr; right = right || state.tokens.next; if (!state.option.laxbreak && left.line !== startLine(right)) { warning("W014", right, right.value); } } function nolinebreak(t) { t = t || state.tokens.curr; if (t.line !== startLine(state.tokens.next)) { warning("E022", t, t.value); } } function nobreakcomma(left, right) { if (left.line !== startLine(right)) { if (!state.option.laxcomma) { if (comma.first) { warning("I001"); comma.first = false; } warning("W014", left, right.value); } } } function comma(opts) { opts = opts || {}; if (!opts.peek) { nobreakcomma(state.tokens.curr, state.tokens.next); advance(","); } else { nobreakcomma(state.tokens.prev, state.tokens.curr); } if (state.tokens.next.identifier && !(opts.property && state.inES5())) { switch (state.tokens.next.value) { case "break": case "case": case "catch": case "continue": case "default": case "do": case "else": case "finally": case "for": case "if": case "in": case "instanceof": case "return": case "switch": case "throw": case "try": case "var": case "let": case "while": case "with": error("E024", state.tokens.next, state.tokens.next.value); return false; } } if (state.tokens.next.type === "(punctuator)") { switch (state.tokens.next.value) { case "}": case "]": case ",": if (opts.allowTrailing) { return true; } case ")": error("E024", state.tokens.next, state.tokens.next.value); return false; } } return true; } function symbol(s, p) { var x = state.syntax[s]; if (!x || typeof x !== "object") { state.syntax[s] = x = { id: s, lbp: p, value: s }; } return x; } function delim(s) { var x = symbol(s, 0); x.delim = true; return x; } function stmt(s, f) { var x = delim(s); x.identifier = x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; } function reserveName(x) { var c = x.id.charAt(0); if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z")) { x.identifier = x.reserved = true; } return x; } function prefix(s, f) { var x = symbol(s, 150); reserveName(x); x.nud = (typeof f === "function") ? f : function() { this.arity = "unary"; this.right = expression(150); if (this.id === "++" || this.id === "--") { if (state.option.plusplus) { warning("W016", this, this.id); } else if (this.right && (!this.right.identifier || isReserved(this.right)) && this.right.id !== "." && this.right.id !== "[") { warning("W017", this); } if (this.right && this.right.isMetaProperty) { error("E031", this); } else if (this.right && this.right.identifier) { state.funct["(scope)"].block.modify(this.right.value, this); } } return this; }; return x; } function type(s, f) { var x = delim(s); x.type = s; x.nud = f; return x; } function reserve(name, func) { var x = type(name, func); x.identifier = true; x.reserved = true; return x; } function FutureReservedWord(name, meta) { var x = type(name, (meta && meta.nud) || function() { return this; }); meta = meta || {}; meta.isFutureReservedWord = true; x.value = name; x.identifier = true; x.reserved = true; x.meta = meta; return x; } function reservevar(s, v) { return reserve(s, function() { if (typeof v === "function") { v(this); } return this; }); } function infix(s, f, p, w) { var x = symbol(s, p); reserveName(x); x.infix = true; x.led = function(left) { if (!w) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); } if ((s === "in" || s === "instanceof") && left.id === "!") { warning("W018", left, "!"); } if (typeof f === "function") { return f(left, this); } else { this.left = left; this.right = expression(p); return this; } }; return x; } function application(s) { var x = symbol(s, 42); x.led = function(left) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); this.left = left; this.right = doFunction({ type: "arrow", loneArg: left }); return this; }; return x; } function relation(s, f) { var x = symbol(s, 100); x.led = function(left) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); this.left = left; var right = this.right = expression(100); if (isIdentifier(left, "NaN") || isIdentifier(right, "NaN")) { warning("W019", this); } else if (f) { f.apply(this, [left, right]); } if (!left || !right) { quit("E041", state.tokens.curr.line); } if (left.id === "!") { warning("W018", left, "!"); } if (right.id === "!") { warning("W018", right, "!"); } return this; }; return x; } function isPoorRelation(node) { return node && ((node.type === "(number)" && +node.value === 0) || (node.type === "(string)" && node.value === "") || (node.type === "null" && !state.option.eqnull) || node.type === "true" || node.type === "false" || node.type === "undefined"); } var typeofValues = {}; typeofValues.legacy = [ "xml", "unknown" ]; typeofValues.es3 = [ "undefined", "boolean", "number", "string", "function", "object", ]; typeofValues.es3 = typeofValues.es3.concat(typeofValues.legacy); typeofValues.es6 = typeofValues.es3.concat("symbol"); function isTypoTypeof(left, right, state) { var values; if (state.option.notypeof) return false; if (!left || !right) return false; values = state.inES6() ? typeofValues.es6 : typeofValues.es3; if (right.type === "(identifier)" && right.value === "typeof" && left.type === "(string)") return !_.contains(values, left.value); return false; } function isGlobalEval(left, state) { var isGlobal = false; if (left.type === "this" && state.funct["(context)"] === null) { isGlobal = true; } else if (left.type === "(identifier)") { if (state.option.node && left.value === "global") { isGlobal = true; } else if (state.option.browser && (left.value === "window" || left.value === "document")) { isGlobal = true; } } return isGlobal; } function findNativePrototype(left) { var natives = [ "Array", "ArrayBuffer", "Boolean", "Collator", "DataView", "Date", "DateTimeFormat", "Error", "EvalError", "Float32Array", "Float64Array", "Function", "Infinity", "Intl", "Int16Array", "Int32Array", "Int8Array", "Iterator", "Number", "NumberFormat", "Object", "RangeError", "ReferenceError", "RegExp", "StopIteration", "String", "SyntaxError", "TypeError", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray", "URIError" ]; function walkPrototype(obj) { if (typeof obj !== "object") return; return obj.right === "prototype" ? obj : walkPrototype(obj.left); } function walkNative(obj) { while (!obj.identifier && typeof obj.left === "object") obj = obj.left; if (obj.identifier && natives.indexOf(obj.value) >= 0) return obj.value; } var prototype = walkPrototype(left); if (prototype) return walkNative(prototype); } function checkLeftSideAssign(left, assignToken, options) { var allowDestructuring = options && options.allowDestructuring; assignToken = assignToken || left; if (state.option.freeze) { var nativeObject = findNativePrototype(left); if (nativeObject) warning("W121", left, nativeObject); } if (left.identifier && !left.isMetaProperty) { state.funct["(scope)"].block.reassign(left.value, left); } if (left.id === ".") { if (!left.left || left.left.value === "arguments" && !state.isStrict()) { warning("E031", assignToken); } state.nameStack.set(state.tokens.prev); return true; } else if (left.id === "{" || left.id === "[") { if (allowDestructuring && state.tokens.curr.left.destructAssign) { state.tokens.curr.left.destructAssign.forEach(function(t) { if (t.id) { state.funct["(scope)"].block.modify(t.id, t.token); } }); } else { if (left.id === "{" || !left.left) { warning("E031", assignToken); } else if (left.left.value === "arguments" && !state.isStrict()) { warning("E031", assignToken); } } if (left.id === "[") { state.nameStack.set(left.right); } return true; } else if (left.isMetaProperty) { error("E031", assignToken); return true; } else if (left.identifier && !isReserved(left)) { if (state.funct["(scope)"].labeltype(left.value) === "exception") { warning("W022", left); } state.nameStack.set(left); return true; } if (left === state.syntax["function"]) { warning("W023", state.tokens.curr); } return false; } function assignop(s, f, p) { var x = infix(s, typeof f === "function" ? f : function(left, that) { that.left = left; if (left && checkLeftSideAssign(left, that, { allowDestructuring: true })) { that.right = expression(10); return that; } error("E031", that); }, p); x.exps = true; x.assign = true; return x; } function bitwise(s, f, p) { var x = symbol(s, p); reserveName(x); x.led = (typeof f === "function") ? f : function(left) { if (state.option.bitwise) { warning("W016", this, this.id); } this.left = left; this.right = expression(p); return this; }; return x; } function bitwiseassignop(s) { return assignop(s, function(left, that) { if (state.option.bitwise) { warning("W016", that, that.id); } if (left && checkLeftSideAssign(left, that)) { that.right = expression(10); return that; } error("E031", that); }, 20); } function suffix(s) { var x = symbol(s, 150); x.led = function(left) { if (state.option.plusplus) { warning("W016", this, this.id); } else if ((!left.identifier || isReserved(left)) && left.id !== "." && left.id !== "[") { warning("W017", this); } if (left.isMetaProperty) { error("E031", this); } else if (left && left.identifier) { state.funct["(scope)"].block.modify(left.value, left); } this.left = left; return this; }; return x; } function optionalidentifier(fnparam, prop, preserve) { if (!state.tokens.next.identifier) { return; } if (!preserve) { advance(); } var curr = state.tokens.curr; var val = state.tokens.curr.value; if (!isReserved(curr)) { return val; } if (prop) { if (state.inES5()) { return val; } } if (fnparam && val === "undefined") { return val; } warning("W024", state.tokens.curr, state.tokens.curr.id); return val; } function identifier(fnparam, prop) { var i = optionalidentifier(fnparam, prop, false); if (i) { return i; } if (state.tokens.next.value === "...") { if (!state.inES6(true)) { warning("W119", state.tokens.next, "spread/rest operator", "6"); } advance(); if (checkPunctuator(state.tokens.next, "...")) { warning("E024", state.tokens.next, "..."); while (checkPunctuator(state.tokens.next, "...")) { advance(); } } if (!state.tokens.next.identifier) { warning("E024", state.tokens.curr, "..."); return; } return identifier(fnparam, prop); } else { error("E030", state.tokens.next, state.tokens.next.value); if (state.tokens.next.id !== ";") { advance(); } } } function reachable(controlToken) { var i = 0, t; if (state.tokens.next.id !== ";" || controlToken.inBracelessBlock) { return; } for (;;) { do { t = peek(i); i += 1; } while (t.id !== "(end)" && t.id === "(comment)"); if (t.reach) { return; } if (t.id !== "(endline)") { if (t.id === "function") { if (state.option.latedef === true) { warning("W026", t); } break; } warning("W027", t, t.value, controlToken.value); break; } } } function parseFinalSemicolon() { if (state.tokens.next.id !== ";") { if (state.tokens.next.isUnclosed) return advance(); var sameLine = startLine(state.tokens.next) === state.tokens.curr.line && state.tokens.next.id !== "(end)"; var blockEnd = checkPunctuator(state.tokens.next, "}"); if (sameLine && !blockEnd) { errorAt("E058", state.tokens.curr.line, state.tokens.curr.character); } else if (!state.option.asi) { if ((blockEnd && !state.option.lastsemic) || !sameLine) { warningAt("W033", state.tokens.curr.line, state.tokens.curr.character); } } } else { advance(";"); } } function statement() { var i = indent, r, t = state.tokens.next, hasOwnScope = false; if (t.id === ";") { advance(";"); return; } var res = isReserved(t); if (res && t.meta && t.meta.isFutureReservedWord && peek().id === ":") { warning("W024", t, t.id); res = false; } if (t.identifier && !res && peek().id === ":") { advance(); advance(":"); hasOwnScope = true; state.funct["(scope)"].stack(); state.funct["(scope)"].block.addBreakLabel(t.value, { token: state.tokens.curr }); if (!state.tokens.next.labelled && state.tokens.next.value !== "{") { warning("W028", state.tokens.next, t.value, state.tokens.next.value); } state.tokens.next.label = t.value; t = state.tokens.next; } if (t.id === "{") { var iscase = (state.funct["(verb)"] === "case" && state.tokens.curr.value === ":"); block(true, true, false, false, iscase); return; } r = expression(0, true); if (r && !(r.identifier && r.value === "function") && !(r.type === "(punctuator)" && r.left && r.left.identifier && r.left.value === "function")) { if (!state.isStrict() && state.option.strict === "global") { warning("E007"); } } if (!t.block) { if (!state.option.expr && (!r || !r.exps)) { warning("W030", state.tokens.curr); } else if (state.option.nonew && r && r.left && r.id === "(" && r.left.id === "new") { warning("W031", t); } parseFinalSemicolon(); } indent = i; if (hasOwnScope) { state.funct["(scope)"].unstack(); } return r; } function statements() { var a = [], p; while (!state.tokens.next.reach && state.tokens.next.id !== "(end)") { if (state.tokens.next.id === ";") { p = peek(); if (!p || (p.id !== "(" && p.id !== "[")) { warning("W032"); } advance(";"); } else { a.push(statement()); } } return a; } function directives() { var i, p, pn; while (state.tokens.next.id === "(string)") { p = peek(0); if (p.id === "(endline)") { i = 1; do { pn = peek(i++); } while (pn.id === "(endline)"); if (pn.id === ";") { p = pn; } else if (pn.value === "[" || pn.value === ".") { break; } else if (!state.option.asi || pn.value === "(") { warning("W033", state.tokens.next); } } else if (p.id === "." || p.id === "[") { break; } else if (p.id !== ";") { warning("W033", p); } advance(); var directive = state.tokens.curr.value; if (state.directive[directive] || (directive === "use strict" && state.option.strict === "implied")) { warning("W034", state.tokens.curr, directive); } state.directive[directive] = true; if (p.id === ";") { advance(";"); } } if (state.isStrict()) { if (!state.option["(explicitNewcap)"]) { state.option.newcap = true; } state.option.undef = true; } } function block(ordinary, stmt, isfunc, isfatarrow, iscase) { var a, b = inblock, old_indent = indent, m, t, line, d; inblock = ordinary; t = state.tokens.next; var metrics = state.funct["(metrics)"]; metrics.nestedBlockDepth += 1; metrics.verifyMaxNestedBlockDepthPerFunction(); if (state.tokens.next.id === "{") { advance("{"); state.funct["(scope)"].stack(); line = state.tokens.curr.line; if (state.tokens.next.id !== "}") { indent += state.option.indent; while (!ordinary && state.tokens.next.from > indent) { indent += state.option.indent; } if (isfunc) { m = {}; for (d in state.directive) { if (_.has(state.directive, d)) { m[d] = state.directive[d]; } } directives(); if (state.option.strict && state.funct["(context)"]["(global)"]) { if (!m["use strict"] && !state.isStrict()) { warning("E007"); } } } a = statements(); metrics.statementCount += a.length; indent -= state.option.indent; } advance("}", t); if (isfunc) { state.funct["(scope)"].validateParams(); if (m) { state.directive = m; } } state.funct["(scope)"].unstack(); indent = old_indent; } else if (!ordinary) { if (isfunc) { state.funct["(scope)"].stack(); m = {}; if (stmt && !isfatarrow && !state.inMoz()) { error("W118", state.tokens.curr, "function closure expressions"); } if (!stmt) { for (d in state.directive) { if (_.has(state.directive, d)) { m[d] = state.directive[d]; } } } expression(10); if (state.option.strict && state.funct["(context)"]["(global)"]) { if (!m["use strict"] && !state.isStrict()) { warning("E007"); } } state.funct["(scope)"].unstack(); } else { error("E021", state.tokens.next, "{", state.tokens.next.value); } } else { state.funct["(noblockscopedvar)"] = state.tokens.next.id !== "for"; state.funct["(scope)"].stack(); if (!stmt || state.option.curly) { warning("W116", state.tokens.next, "{", state.tokens.next.value); } state.tokens.next.inBracelessBlock = true; indent += state.option.indent; a = [statement()]; indent -= state.option.indent; state.funct["(scope)"].unstack(); delete state.funct["(noblockscopedvar)"]; } switch (state.funct["(verb)"]) { case "break": case "continue": case "return": case "throw": if (iscase) { break; } default: state.funct["(verb)"] = null; } inblock = b; if (ordinary && state.option.noempty && (!a || a.length === 0)) { warning("W035", state.tokens.prev); } metrics.nestedBlockDepth -= 1; return a; } function countMember(m) { if (membersOnly && typeof membersOnly[m] !== "boolean") { warning("W036", state.tokens.curr, m); } if (typeof member[m] === "number") { member[m] += 1; } else { member[m] = 1; } } type("(number)", function() { return this; }); type("(string)", function() { return this; }); state.syntax["(identifier)"] = { type: "(identifier)", lbp: 0, identifier: true, nud: function() { var v = this.value; if (state.tokens.next.id === "=>") { return this; } if (!state.funct["(comparray)"].check(v)) { state.funct["(scope)"].block.use(v, state.tokens.curr); } return this; }, led: function() { error("E033", state.tokens.next, state.tokens.next.value); } }; var baseTemplateSyntax = { lbp: 0, identifier: false, template: true, }; state.syntax["(template)"] = _.extend({ type: "(template)", nud: doTemplateLiteral, led: doTemplateLiteral, noSubst: false }, baseTemplateSyntax); state.syntax["(template middle)"] = _.extend({ type: "(template middle)", middle: true, noSubst: false }, baseTemplateSyntax); state.syntax["(template tail)"] = _.extend({ type: "(template tail)", tail: true, noSubst: false }, baseTemplateSyntax); state.syntax["(no subst template)"] = _.extend({ type: "(template)", nud: doTemplateLiteral, led: doTemplateLiteral, noSubst: true, tail: true // mark as tail, since it's always the last component }, baseTemplateSyntax); type("(regexp)", function() { return this; }); delim("(endline)"); delim("(begin)"); delim("(end)").reach = true; delim("(error)").reach = true; delim("}").reach = true; delim(")"); delim("]"); delim("\"").reach = true; delim("'").reach = true; delim(";"); delim(":").reach = true; delim("#"); reserve("else"); reserve("case").reach = true; reserve("catch"); reserve("default").reach = true; reserve("finally"); reservevar("arguments", function(x) { if (state.isStrict() && state.funct["(global)"]) { warning("E008", x); } }); reservevar("eval"); reservevar("false"); reservevar("Infinity"); reservevar("null"); reservevar("this", function(x) { if (state.isStrict() && !isMethod() && !state.option.validthis && ((state.funct["(statement)"] && state.funct["(name)"].charAt(0) > "Z") || state.funct["(global)"])) { warning("W040", x); } }); reservevar("true"); reservevar("undefined"); assignop("=", "assign", 20); assignop("+=", "assignadd", 20); assignop("-=", "assignsub", 20); assignop("*=", "assignmult", 20); assignop("/=", "assigndiv", 20).nud = function() { error("E014"); }; assignop("%=", "assignmod", 20); bitwiseassignop("&="); bitwiseassignop("|="); bitwiseassignop("^="); bitwiseassignop("<<="); bitwiseassignop(">>="); bitwiseassignop(">>>="); infix(",", function(left, that) { var expr; that.exprs = [left]; if (state.option.nocomma) { warning("W127"); } if (!comma({ peek: true })) { return that; } while (true) { if (!(expr = expression(10))) { break; } that.exprs.push(expr); if (state.tokens.next.value !== "," || !comma()) { break; } } return that; }, 10, true); infix("?", function(left, that) { increaseComplexityCount(); that.left = left; that.right = expression(10); advance(":"); that["else"] = expression(10); return that; }, 30); var orPrecendence = 40; infix("||", function(left, that) { increaseComplexityCount(); that.left = left; that.right = expression(orPrecendence); return that; }, orPrecendence); infix("&&", "and", 50); bitwise("|", "bitor", 70); bitwise("^", "bitxor", 80); bitwise("&", "bitand", 90); relation("==", function(left, right) { var eqnull = state.option.eqnull && ((left && left.value) === "null" || (right && right.value) === "null"); switch (true) { case !eqnull && state.option.eqeqeq: this.from = this.character; warning("W116", this, "===", "=="); break; case isPoorRelation(left): warning("W041", this, "===", left.value); break; case isPoorRelation(right): warning("W041", this, "===", right.value); break; case isTypoTypeof(right, left, state): warning("W122", this, right.value); break; case isTypoTypeof(left, right, state): warning("W122", this, left.value); break; } return this; }); relation("===", function(left, right) { if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("!=", function(left, right) { var eqnull = state.option.eqnull && ((left && left.value) === "null" || (right && right.value) === "null"); if (!eqnull && state.option.eqeqeq) { this.from = this.character; warning("W116", this, "!==", "!="); } else if (isPoorRelation(left)) { warning("W041", this, "!==", left.value); } else if (isPoorRelation(right)) { warning("W041", this, "!==", right.value); } else if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("!==", function(left, right) { if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("<"); relation(">"); relation("<="); relation(">="); bitwise("<<", "shiftleft", 120); bitwise(">>", "shiftright", 120); bitwise(">>>", "shiftrightunsigned", 120); infix("in", "in", 120); infix("instanceof", "instanceof", 120); infix("+", function(left, that) { var right; that.left = left; that.right = right = expression(130); if (left && right && left.id === "(string)" && right.id === "(string)") { left.value += right.value; left.character = right.character; if (!state.option.scripturl && reg.javascriptURL.test(left.value)) { warning("W050", left); } return left; } return that; }, 130); prefix("+", "num"); prefix("+++", function() { warning("W007"); this.arity = "unary"; this.right = expression(150); return this; }); infix("+++", function(left) { warning("W007"); this.left = left; this.right = expression(130); return this; }, 130); infix("-", "sub", 130); prefix("-", "neg"); prefix("---", function() { warning("W006"); this.arity = "unary"; this.right = expression(150); return this; }); infix("---", function(left) { warning("W006"); this.left = left; this.right = expression(130); return this; }, 130); infix("*", "mult", 140); infix("/", "div", 140); infix("%", "mod", 140); suffix("++"); prefix("++", "preinc"); state.syntax["++"].exps = true; suffix("--"); prefix("--", "predec"); state.syntax["--"].exps = true; prefix("delete", function() { var p = expression(10); if (!p) { return this; } if (p.id !== "." && p.id !== "[") { warning("W051"); } this.first = p; if (p.identifier && !state.isStrict()) { p.forgiveUndef = true; } return this; }).exps = true; prefix("~", function() { if (state.option.bitwise) { warning("W016", this, "~"); } this.arity = "unary"; this.right = expression(150); return this; }); prefix("...", function() { if (!state.inES6(true)) { warning("W119", this, "spread/rest operator", "6"); } if (!state.tokens.next.identifier && state.tokens.next.type !== "(string)" && !checkPunctuators(state.tokens.next, ["[", "("])) { error("E030", state.tokens.next, state.tokens.next.value); } expression(150); return this; }); prefix("!", function() { this.arity = "unary"; this.right = expression(150); if (!this.right) { // '!' followed by nothing? Give up. quit("E041", this.line || 0); } if (bang[this.right.id] === true) { warning("W018", this, "!"); } return this; }); prefix("typeof", (function() { var p = expression(150); this.first = this.right = p; if (!p) { // 'typeof' followed by nothing? Give up. quit("E041", this.line || 0, this.character || 0); } if (p.identifier) { p.forgiveUndef = true; } return this; })); prefix("new", function() { var mp = metaProperty("target", function() { if (!state.inES6(true)) { warning("W119", state.tokens.prev, "new.target", "6"); } var inFunction, c = state.funct; while (c) { inFunction = !c["(global)"]; if (!c["(arrow)"]) { break; } c = c["(context)"]; } if (!inFunction) { warning("W136", state.tokens.prev, "new.target"); } }); if (mp) { return mp; } var c = expression(155), i; if (c && c.id !== "function") { if (c.identifier) { c["new"] = true; switch (c.value) { case "Number": case "String": case "Boolean": case "Math": case "JSON": warning("W053", state.tokens.prev, c.value); break; case "Symbol": if (state.inES6()) { warning("W053", state.tokens.prev, c.value); } break; case "Function": if (!state.option.evil) { warning("W054"); } break; case "Date": case "RegExp": case "this": break; default: if (c.id !== "function") { i = c.value.substr(0, 1); if (state.option.newcap && (i < "A" || i > "Z") && !state.funct["(scope)"].isPredefined(c.value)) { warning("W055", state.tokens.curr); } } } } else { if (c.id !== "." && c.id !== "[" && c.id !== "(") { warning("W056", state.tokens.curr); } } } else { if (!state.option.supernew) warning("W057", this); } if (state.tokens.next.id !== "(" && !state.option.supernew) { warning("W058", state.tokens.curr, state.tokens.curr.value); } this.first = this.right = c; return this; }); state.syntax["new"].exps = true; prefix("void").exps = true; infix(".", function(left, that) { var m = identifier(false, true); if (typeof m === "string") { countMember(m); } that.left = left; that.right = m; if (m && m === "hasOwnProperty" && state.tokens.next.value === "=") { warning("W001"); } if (left && left.value === "arguments" && (m === "callee" || m === "caller")) { if (state.option.noarg) warning("W059", left, m); else if (state.isStrict()) error("E008"); } else if (!state.option.evil && left && left.value === "document" && (m === "write" || m === "writeln")) { warning("W060", left); } if (!state.option.evil && (m === "eval" || m === "execScript")) { if (isGlobalEval(left, state)) { warning("W061"); } } return that; }, 160, true); infix("(", function(left, that) { if (state.option.immed && left && !left.immed && left.id === "function") { warning("W062"); } var n = 0; var p = []; if (left) { if (left.type === "(identifier)") { if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { if ("Array Number String Boolean Date Object Error Symbol".indexOf(left.value) === -1) { if (left.value === "Math") { warning("W063", left); } else if (state.option.newcap) { warning("W064", left); } } } } } if (state.tokens.next.id !== ")") { for (;;) { p[p.length] = expression(10); n += 1; if (state.tokens.next.id !== ",") { break; } comma(); } } advance(")"); if (typeof left === "object") { if (!state.inES5() && left.value === "parseInt" && n === 1) { warning("W065", state.tokens.curr); } if (!state.option.evil) { if (left.value === "eval" || left.value === "Function" || left.value === "execScript") { warning("W061", left); if (p[0] && [0].id === "(string)") { addInternalSrc(left, p[0].value); } } else if (p[0] && p[0].id === "(string)" && (left.value === "setTimeout" || left.value === "setInterval")) { warning("W066", left); addInternalSrc(left, p[0].value); } else if (p[0] && p[0].id === "(string)" && left.value === "." && left.left.value === "window" && (left.right === "setTimeout" || left.right === "setInterval")) { warning("W066", left); addInternalSrc(left, p[0].value); } } if (!left.identifier && left.id !== "." && left.id !== "[" && left.id !== "=>" && left.id !== "(" && left.id !== "&&" && left.id !== "||" && left.id !== "?" && !(state.inES6() && left["(name)"])) { warning("W067", that); } } that.left = left; return that; }, 155, true).exps = true; prefix("(", function() { var pn = state.tokens.next, pn1, i = -1; var ret, triggerFnExpr, first, last; var parens = 1; var opening = state.tokens.curr; var preceeding = state.tokens.prev; var isNecessary = !state.option.singleGroups; do { if (pn.value === "(") { parens += 1; } else if (pn.value === ")") { parens -= 1; } i += 1; pn1 = pn; pn = peek(i); } while (!(parens === 0 && pn1.value === ")") && pn.value !== ";" && pn.type !== "(end)"); if (state.tokens.next.id === "function") { triggerFnExpr = state.tokens.next.immed = true; } if (pn.value === "=>") { return doFunction({ type: "arrow", parsedOpening: true }); } var exprs = []; if (state.tokens.next.id !== ")") { for (;;) { exprs.push(expression(10)); if (state.tokens.next.id !== ",") { break; } if (state.option.nocomma) { warning("W127"); } comma(); } } advance(")", this); if (state.option.immed && exprs[0] && exprs[0].id === "function") { if (state.tokens.next.id !== "(" && state.tokens.next.id !== "." && state.tokens.next.id !== "[") { warning("W068", this); } } if (!exprs.length) { return; } if (exprs.length > 1) { ret = Object.create(state.syntax[","]); ret.exprs = exprs; first = exprs[0]; last = exprs[exprs.length - 1]; if (!isNecessary) { isNecessary = preceeding.assign || preceeding.delim; } } else { ret = first = last = exprs[0]; if (!isNecessary) { isNecessary = (opening.beginsStmt && (ret.id === "{" || triggerFnExpr || isFunctor(ret))) || (triggerFnExpr && (!isEndOfExpr() || state.tokens.prev.id !== "}")) || (isFunctor(ret) && !isEndOfExpr()) || (ret.id === "{" && preceeding.id === "=>") || (ret.type === "(number)" && checkPunctuator(pn, ".") && /^\d+$/.test(ret.value)); } } if (ret) { if (!isNecessary && (first.left || first.right || ret.exprs)) { isNecessary = (!isBeginOfExpr(preceeding) && first.lbp <= preceeding.lbp) || (!isEndOfExpr() && last.lbp < state.tokens.next.lbp); } if (!isNecessary) { warning("W126", opening); } ret.paren = true; } return ret; }); application("=>"); infix("[", function(left, that) { var e = expression(10), s; if (e && e.type === "(string)") { if (!state.option.evil && (e.value === "eval" || e.value === "execScript")) { if (isGlobalEval(left, state)) { warning("W061"); } } countMember(e.value); if (!state.option.sub && reg.identifier.test(e.value)) { s = state.syntax[e.value]; if (!s || !isReserved(s)) { warning("W069", state.tokens.prev, e.value); } } } advance("]", that); if (e && e.value === "hasOwnProperty" && state.tokens.next.value === "=") { warning("W001"); } that.left = left; that.right = e; return that; }, 160, true); function comprehensiveArrayExpression() { var res = {}; res.exps = true; state.funct["(comparray)"].stack(); var reversed = false; if (state.tokens.next.value !== "for") { reversed = true; if (!state.inMoz()) { warning("W116", state.tokens.next, "for", state.tokens.next.value); } state.funct["(comparray)"].setState("use"); res.right = expression(10); } advance("for"); if (state.tokens.next.value === "each") { advance("each"); if (!state.inMoz()) { warning("W118", state.tokens.curr, "for each"); } } advance("("); state.funct["(comparray)"].setState("define"); res.left = expression(130); if (_.contains(["in", "of"], state.tokens.next.value)) { advance(); } else { error("E045", state.tokens.curr); } state.funct["(comparray)"].setState("generate"); expression(10); advance(")"); if (state.tokens.next.value === "if") { advance("if"); advance("("); state.funct["(comparray)"].setState("filter"); res.filter = expression(10); advance(")"); } if (!reversed) { state.funct["(comparray)"].setState("use"); res.right = expression(10); } advance("]"); state.funct["(comparray)"].unstack(); return res; } prefix("[", function() { var blocktype = lookupBlockType(); if (blocktype.isCompArray) { if (!state.option.esnext && !state.inMoz()) { warning("W118", state.tokens.curr, "array comprehension"); } return comprehensiveArrayExpression(); } else if (blocktype.isDestAssign) { this.destructAssign = destructuringPattern({ openingParsed: true, assignment: true }); return this; } var b = state.tokens.curr.line !== startLine(state.tokens.next); this.first = []; if (b) { indent += state.option.indent; if (state.tokens.next.from === indent + state.option.indent) { indent += state.option.indent; } } while (state.tokens.next.id !== "(end)") { while (state.tokens.next.id === ",") { if (!state.option.elision) { if (!state.inES5()) { warning("W070"); } else { warning("W128"); do { advance(","); } while (state.tokens.next.id === ","); continue; } } advance(","); } if (state.tokens.next.id === "]") { break; } this.first.push(expression(10)); if (state.tokens.next.id === ",") { comma({ allowTrailing: true }); if (state.tokens.next.id === "]" && !state.inES5()) { warning("W070", state.tokens.curr); break; } } else { break; } } if (b) { indent -= state.option.indent; } advance("]", this); return this; }); function isMethod() { return state.funct["(statement)"] && state.funct["(statement)"].type === "class" || state.funct["(context)"] && state.funct["(context)"]["(verb)"] === "class"; } function isPropertyName(token) { return token.identifier || token.id === "(string)" || token.id === "(number)"; } function propertyName(preserveOrToken) { var id; var preserve = true; if (typeof preserveOrToken === "object") { id = preserveOrToken; } else { preserve = preserveOrToken; id = optionalidentifier(false, true, preserve); } if (!id) { if (state.tokens.next.id === "(string)") { id = state.tokens.next.value; if (!preserve) { advance(); } } else if (state.tokens.next.id === "(number)") { id = state.tokens.next.value.toString(); if (!preserve) { advance(); } } } else if (typeof id === "object") { if (id.id === "(string)" || id.id === "(identifier)") id = id.value; else if (id.id === "(number)") id = id.value.toString(); } if (id === "hasOwnProperty") { warning("W001"); } return id; } function functionparams(options) { var next; var paramsIds = []; var ident; var tokens = []; var t; var pastDefault = false; var pastRest = false; var arity = 0; var loneArg = options && options.loneArg; if (loneArg && loneArg.identifier === true) { state.funct["(scope)"].addParam(loneArg.value, loneArg); return { arity: 1, params: [ loneArg.value ] }; } next = state.tokens.next; if (!options || !options.parsedOpening) { advance("("); } if (state.tokens.next.id === ")") { advance(")"); return; } function addParam(addParamArgs) { state.funct["(scope)"].addParam.apply(state.funct["(scope)"], addParamArgs); } for (;;) { arity++; var currentParams = []; if (_.contains(["{", "["], state.tokens.next.id)) { tokens = destructuringPattern(); for (t in tokens) { t = tokens[t]; if (t.id) { paramsIds.push(t.id); currentParams.push([t.id, t.token]); } } } else { if (checkPunctuator(state.tokens.next, "...")) pastRest = true; ident = identifier(true); if (ident) { paramsIds.push(ident); currentParams.push([ident, state.tokens.curr]); } else { while (!checkPunctuators(state.tokens.next, [",", ")"])) advance(); } } if (pastDefault) { if (state.tokens.next.id !== "=") { error("W138", state.tokens.current); } } if (state.tokens.next.id === "=") { if (!state.inES6()) { warning("W119", state.tokens.next, "default parameters", "6"); } advance("="); pastDefault = true; expression(10); } currentParams.forEach(addParam); if (state.tokens.next.id === ",") { if (pastRest) { warning("W131", state.tokens.next); } comma(); } else { advance(")", next); return { arity: arity, params: paramsIds }; } } } function functor(name, token, overwrites) { var funct = { "(name)" : name, "(breakage)" : 0, "(loopage)" : 0, "(tokens)" : {}, "(properties)": {}, "(catch)" : false, "(global)" : false, "(line)" : null, "(character)" : null, "(metrics)" : null, "(statement)" : null, "(context)" : null, "(scope)" : null, "(comparray)" : null, "(generator)" : null, "(arrow)" : null, "(params)" : null }; if (token) { _.extend(funct, { "(line)" : token.line, "(character)": token.character, "(metrics)" : createMetrics(token) }); } _.extend(funct, overwrites); if (funct["(context)"]) { funct["(scope)"] = funct["(context)"]["(scope)"]; funct["(comparray)"] = funct["(context)"]["(comparray)"]; } return funct; } function isFunctor(token) { return "(scope)" in token; } function hasParsedCode(funct) { return funct["(global)"] && !funct["(verb)"]; } function doTemplateLiteral(left) { var ctx = this.context; var noSubst = this.noSubst; var depth = this.depth; if (!noSubst) { while (!end()) { if (!state.tokens.next.template || state.tokens.next.depth > depth) { expression(0); // should probably have different rbp? } else { advance(); } } } return { id: "(template)", type: "(template)", tag: left }; function end() { if (state.tokens.curr.template && state.tokens.curr.tail && state.tokens.curr.context === ctx) return true; var complete = (state.tokens.next.template && state.tokens.next.tail && state.tokens.next.context === ctx); if (complete) advance(); return complete || state.tokens.next.isUnclosed; } } function doFunction(options) { var f, token, name, statement, classExprBinding, isGenerator, isArrow, ignoreLoopFunc; var oldOption = state.option; var oldIgnored = state.ignored; if (options) { name = options.name; statement = options.statement; classExprBinding = options.classExprBinding; isGenerator = options.type === "generator"; isArrow = options.type === "arrow"; ignoreLoopFunc = options.ignoreLoopFunc; } state.option = Object.create(state.option); state.ignored = Object.create(state.ignored); state.funct = functor(name || state.nameStack.infer(), state.tokens.next, { "(statement)": statement, "(context)": state.funct, "(arrow)": isArrow, "(generator)": isGenerator }); f = state.funct; token = state.tokens.curr; token.funct = state.funct; functions.push(state.funct); state.funct["(scope)"].stack("functionouter"); var internallyAccessibleName = name || classExprBinding; if (internallyAccessibleName) { state.funct["(scope)"].block.add(internallyAccessibleName, classExprBinding ? "class" : "function", state.tokens.curr, false); } state.funct["(scope)"].stack("functionparams"); var paramsInfo = functionparams(options); if (paramsInfo) { state.funct["(params)"] = paramsInfo.params; state.funct["(metrics)"].arity = paramsInfo.arity; state.funct["(metrics)"].verifyMaxParametersPerFunction(); } else { state.funct["(metrics)"].arity = 0; } if (isArrow) { if (!state.inES6(true)) { warning("W119", state.tokens.curr, "arrow function syntax (=>)", "6"); } if (!options.loneArg) { advance("=>"); } } block(false, true, true, isArrow); if (!state.option.noyield && isGenerator && state.funct["(generator)"] !== "yielded") { warning("W124", state.tokens.curr); } state.funct["(metrics)"].verifyMaxStatementsPerFunction(); state.funct["(metrics)"].verifyMaxComplexityPerFunction(); state.funct["(unusedOption)"] = state.option.unused; state.option = oldOption; state.ignored = oldIgnored; state.funct["(last)"] = state.tokens.curr.line; state.funct["(lastcharacter)"] = state.tokens.curr.character; state.funct["(scope)"].unstack(); // also does usage and label checks state.funct["(scope)"].unstack(); state.funct = state.funct["(context)"]; if (!ignoreLoopFunc && !state.option.loopfunc && state.funct["(loopage)"]) { if (f["(isCapturing)"]) { warning("W083", token); } } return f; } function createMetrics(functionStartToken) { return { statementCount: 0, nestedBlockDepth: -1, ComplexityCount: 1, arity: 0, verifyMaxStatementsPerFunction: function() { if (state.option.maxstatements && this.statementCount > state.option.maxstatements) { warning("W071", functionStartToken, this.statementCount); } }, verifyMaxParametersPerFunction: function() { if (_.isNumber(state.option.maxparams) && this.arity > state.option.maxparams) { warning("W072", functionStartToken, this.arity); } }, verifyMaxNestedBlockDepthPerFunction: function() { if (state.option.maxdepth && this.nestedBlockDepth > 0 && this.nestedBlockDepth === state.option.maxdepth + 1) { warning("W073", null, this.nestedBlockDepth); } }, verifyMaxComplexityPerFunction: function() { var max = state.option.maxcomplexity; var cc = this.ComplexityCount; if (max && cc > max) { warning("W074", functionStartToken, cc); } } }; } function increaseComplexityCount() { state.funct["(metrics)"].ComplexityCount += 1; } function checkCondAssignment(expr) { var id, paren; if (expr) { id = expr.id; paren = expr.paren; if (id === "," && (expr = expr.exprs[expr.exprs.length - 1])) { id = expr.id; paren = paren || expr.paren; } } switch (id) { case "=": case "+=": case "-=": case "*=": case "%=": case "&=": case "|=": case "^=": case "/=": if (!paren && !state.option.boss) { warning("W084"); } } } function checkProperties(props) { if (state.inES5()) { for (var name in props) { if (props[name] && props[name].setterToken && !props[name].getterToken) { warning("W078", props[name].setterToken); } } } } function metaProperty(name, c) { if (checkPunctuator(state.tokens.next, ".")) { var left = state.tokens.curr.id; advance("."); var id = identifier(); state.tokens.curr.isMetaProperty = true; if (name !== id) { error("E057", state.tokens.prev, left, id); } else { c(); } return state.tokens.curr; } } (function(x) { x.nud = function() { var b, f, i, p, t, isGeneratorMethod = false, nextVal; var props = Object.create(null); // All properties, including accessors b = state.tokens.curr.line !== startLine(state.tokens.next); if (b) { indent += state.option.indent; if (state.tokens.next.from === indent + state.option.indent) { indent += state.option.indent; } } var blocktype = lookupBlockType(); if (blocktype.isDestAssign) { this.destructAssign = destructuringPattern({ openingParsed: true, assignment: true }); return this; } for (;;) { if (state.tokens.next.id === "}") { break; } nextVal = state.tokens.next.value; if (state.tokens.next.identifier && (peekIgnoreEOL().id === "," || peekIgnoreEOL().id === "}")) { if (!state.inES6()) { warning("W104", state.tokens.next, "object short notation", "6"); } i = propertyName(true); saveProperty(props, i, state.tokens.next); expression(10); } else if (peek().id !== ":" && (nextVal === "get" || nextVal === "set")) { advance(nextVal); if (!state.inES5()) { error("E034"); } i = propertyName(); if (!i && !state.inES6()) { error("E035"); } if (i) { saveAccessor(nextVal, props, i, state.tokens.curr); } t = state.tokens.next; f = doFunction(); p = f["(params)"]; if (nextVal === "get" && i && p) { warning("W076", t, p[0], i); } else if (nextVal === "set" && i && (!p || p.length !== 1)) { warning("W077", t, i); } } else { if (state.tokens.next.value === "*" && state.tokens.next.type === "(punctuator)") { if (!state.inES6()) { warning("W104", state.tokens.next, "generator functions", "6"); } advance("*"); isGeneratorMethod = true; } else { isGeneratorMethod = false; } if (state.tokens.next.id === "[") { i = computedPropertyName(); state.nameStack.set(i); } else { state.nameStack.set(state.tokens.next); i = propertyName(); saveProperty(props, i, state.tokens.next); if (typeof i !== "string") { break; } } if (state.tokens.next.value === "(") { if (!state.inES6()) { warning("W104", state.tokens.curr, "concise methods", "6"); } doFunction({ type: isGeneratorMethod ? "generator" : null }); } else { advance(":"); expression(10); } } countMember(i); if (state.tokens.next.id === ",") { comma({ allowTrailing: true, property: true }); if (state.tokens.next.id === ",") { warning("W070", state.tokens.curr); } else if (state.tokens.next.id === "}" && !state.inES5()) { warning("W070", state.tokens.curr); } } else { break; } } if (b) { indent -= state.option.indent; } advance("}", this); checkProperties(props); return this; }; x.fud = function() { error("E036", state.tokens.curr); }; }(delim("{"))); function destructuringPattern(options) { var isAssignment = options && options.assignment; if (!state.inES6()) { warning("W104", state.tokens.curr, isAssignment ? "destructuring assignment" : "destructuring binding", "6"); } return destructuringPatternRecursive(options); } function destructuringPatternRecursive(options) { var ids; var identifiers = []; var openingParsed = options && options.openingParsed; var isAssignment = options && options.assignment; var recursiveOptions = isAssignment ? { assignment: isAssignment } : null; var firstToken = openingParsed ? state.tokens.curr : state.tokens.next; var nextInnerDE = function() { var ident; if (checkPunctuators(state.tokens.next, ["[", "{"])) { ids = destructuringPatternRecursive(recursiveOptions); for (var id in ids) { id = ids[id]; identifiers.push({ id: id.id, token: id.token }); } } else if (checkPunctuator(state.tokens.next, ",")) { identifiers.push({ id: null, token: state.tokens.curr }); } else if (checkPunctuator(state.tokens.next, "(")) { advance("("); nextInnerDE(); advance(")"); } else { var is_rest = checkPunctuator(state.tokens.next, "..."); if (isAssignment) { var identifierToken = is_rest ? peek(0) : state.tokens.next; if (!identifierToken.identifier) { warning("E030", identifierToken, identifierToken.value); } var assignTarget = expression(155); if (assignTarget) { checkLeftSideAssign(assignTarget); if (assignTarget.identifier) { ident = assignTarget.value; } } } else { ident = identifier(); } if (ident) { identifiers.push({ id: ident, token: state.tokens.curr }); } return is_rest; } return false; }; var assignmentProperty = function() { var id; if (checkPunctuator(state.tokens.next, "[")) { advance("["); expression(10); advance("]"); advance(":"); nextInnerDE(); } else if (state.tokens.next.id === "(string)" || state.tokens.next.id === "(number)") { advance(); advance(":"); nextInnerDE(); } else { id = identifier(); if (checkPunctuator(state.tokens.next, ":")) { advance(":"); nextInnerDE(); } else if (id) { if (isAssignment) { checkLeftSideAssign(state.tokens.curr); } identifiers.push({ id: id, token: state.tokens.curr }); } } }; if (checkPunctuator(firstToken, "[")) { if (!openingParsed) { advance("["); } if (checkPunctuator(state.tokens.next, "]")) { warning("W137", state.tokens.curr); } var element_after_rest = false; while (!checkPunctuator(state.tokens.next, "]")) { if (nextInnerDE() && !element_after_rest && checkPunctuator(state.tokens.next, ",")) { warning("W130", state.tokens.next); element_after_rest = true; } if (checkPunctuator(state.tokens.next, "=")) { if (checkPunctuator(state.tokens.prev, "...")) { advance("]"); } else { advance("="); } if (state.tokens.next.id === "undefined") { warning("W080", state.tokens.prev, state.tokens.prev.value); } expression(10); } if (!checkPunctuator(state.tokens.next, "]")) { advance(","); } } advance("]"); } else if (checkPunctuator(firstToken, "{")) { if (!openingParsed) { advance("{"); } if (checkPunctuator(state.tokens.next, "}")) { warning("W137", state.tokens.curr); } while (!checkPunctuator(state.tokens.next, "}")) { assignmentProperty(); if (checkPunctuator(state.tokens.next, "=")) { advance("="); if (state.tokens.next.id === "undefined") { warning("W080", state.tokens.prev, state.tokens.prev.value); } expression(10); } if (!checkPunctuator(state.tokens.next, "}")) { advance(","); if (checkPunctuator(state.tokens.next, "}")) { break; } } } advance("}"); } return identifiers; } function destructuringPatternMatch(tokens, value) { var first = value.first; if (!first) return; _.zip(tokens, Array.isArray(first) ? first : [ first ]).forEach(function(val) { var token = val[0]; var value = val[1]; if (token && value) token.first = value; else if (token && token.first && !value) warning("W080", token.first, token.first.value); }); } function blockVariableStatement(type, statement, context) { var prefix = context && context.prefix; var inexport = context && context.inexport; var isLet = type === "let"; var isConst = type === "const"; var tokens, lone, value, letblock; if (!state.inES6()) { warning("W104", state.tokens.curr, type, "6"); } if (isLet && state.tokens.next.value === "(") { if (!state.inMoz()) { warning("W118", state.tokens.next, "let block"); } advance("("); state.funct["(scope)"].stack(); letblock = true; } else if (state.funct["(noblockscopedvar)"]) { error("E048", state.tokens.curr, isConst ? "Const" : "Let"); } statement.first = []; for (;;) { var names = []; if (_.contains(["{", "["], state.tokens.next.value)) { tokens = destructuringPattern(); lone = false; } else { tokens = [ { id: identifier(), token: state.tokens.curr } ]; lone = true; } if (!prefix && isConst && state.tokens.next.id !== "=") { warning("E012", state.tokens.curr, state.tokens.curr.value); } for (var t in tokens) { if (tokens.hasOwnProperty(t)) { t = tokens[t]; if (state.funct["(scope)"].block.isGlobal()) { if (predefined[t.id] === false) { warning("W079", t.token, t.id); } } if (t.id && !state.funct["(noblockscopedvar)"]) { state.funct["(scope)"].addlabel(t.id, { type: type, token: t.token }); names.push(t.token); if (lone && inexport) { state.funct["(scope)"].setExported(t.token.value, t.token); } } } } if (state.tokens.next.id === "=") { advance("="); if (!prefix && state.tokens.next.id === "undefined") { warning("W080", state.tokens.prev, state.tokens.prev.value); } if (!prefix && peek(0).id === "=" && state.tokens.next.identifier) { warning("W120", state.tokens.next, state.tokens.next.value); } value = expression(prefix ? 120 : 10); if (lone) { tokens[0].first = value; } else { destructuringPatternMatch(names, value); } } statement.first = statement.first.concat(names); if (state.tokens.next.id !== ",") { break; } comma(); } if (letblock) { advance(")"); block(true, true); statement.block = true; state.funct["(scope)"].unstack(); } return statement; } var conststatement = stmt("const", function(context) { return blockVariableStatement("const", this, context); }); conststatement.exps = true; var letstatement = stmt("let", function(context) { return blockVariableStatement("let", this, context); }); letstatement.exps = true; var varstatement = stmt("var", function(context) { var prefix = context && context.prefix; var inexport = context && context.inexport; var tokens, lone, value; var implied = context && context.implied; var report = !(context && context.ignore); this.first = []; for (;;) { var names = []; if (_.contains(["{", "["], state.tokens.next.value)) { tokens = destructuringPattern(); lone = false; } else { tokens = [ { id: identifier(), token: state.tokens.curr } ]; lone = true; } if (!(prefix && implied) && report && state.option.varstmt) { warning("W132", this); } this.first = this.first.concat(names); for (var t in tokens) { if (tokens.hasOwnProperty(t)) { t = tokens[t]; if (!implied && state.funct["(global)"]) { if (predefined[t.id] === false) { warning("W079", t.token, t.id); } else if (state.option.futurehostile === false) { if ((!state.inES5() && vars.ecmaIdentifiers[5][t.id] === false) || (!state.inES6() && vars.ecmaIdentifiers[6][t.id] === false)) { warning("W129", t.token, t.id); } } } if (t.id) { if (implied === "for") { if (!state.funct["(scope)"].has(t.id)) { if (report) warning("W088", t.token, t.id); } state.funct["(scope)"].block.use(t.id, t.token); } else { state.funct["(scope)"].addlabel(t.id, { type: "var", token: t.token }); if (lone && inexport) { state.funct["(scope)"].setExported(t.id, t.token); } } names.push(t.token); } } } if (state.tokens.next.id === "=") { state.nameStack.set(state.tokens.curr); advance("="); if (!prefix && report && !state.funct["(loopage)"] && state.tokens.next.id === "undefined") { warning("W080", state.tokens.prev, state.tokens.prev.value); } if (peek(0).id === "=" && state.tokens.next.identifier) { if (!prefix && report && !state.funct["(params)"] || state.funct["(params)"].indexOf(state.tokens.next.value) === -1) { warning("W120", state.tokens.next, state.tokens.next.value); } } value = expression(prefix ? 120 : 10); if (lone) { tokens[0].first = value; } else { destructuringPatternMatch(names, value); } } if (state.tokens.next.id !== ",") { break; } comma(); } return this; }); varstatement.exps = true; blockstmt("class", function() { return classdef.call(this, true); }); function classdef(isStatement) { if (!state.inES6()) { warning("W104", state.tokens.curr, "class", "6"); } if (isStatement) { this.name = identifier(); state.funct["(scope)"].addlabel(this.name, { type: "class", token: state.tokens.curr }); } else if (state.tokens.next.identifier && state.tokens.next.value !== "extends") { this.name = identifier(); this.namedExpr = true; } else { this.name = state.nameStack.infer(); } classtail(this); return this; } function classtail(c) { var wasInClassBody = state.inClassBody; if (state.tokens.next.value === "extends") { advance("extends"); c.heritage = expression(10); } state.inClassBody = true; advance("{"); c.body = classbody(c); advance("}"); state.inClassBody = wasInClassBody; } function classbody(c) { var name; var isStatic; var isGenerator; var getset; var props = Object.create(null); var staticProps = Object.create(null); var computed; for (var i = 0; state.tokens.next.id !== "}"; ++i) { name = state.tokens.next; isStatic = false; isGenerator = false; getset = null; if (name.id === ";") { warning("W032"); advance(";"); continue; } if (name.id === "*") { isGenerator = true; advance("*"); name = state.tokens.next; } if (name.id === "[") { name = computedPropertyName(); computed = true; } else if (isPropertyName(name)) { advance(); computed = false; if (name.identifier && name.value === "static") { if (checkPunctuator(state.tokens.next, "*")) { isGenerator = true; advance("*"); } if (isPropertyName(state.tokens.next) || state.tokens.next.id === "[") { computed = state.tokens.next.id === "["; isStatic = true; name = state.tokens.next; if (state.tokens.next.id === "[") { name = computedPropertyName(); } else advance(); } } if (name.identifier && (name.value === "get" || name.value === "set")) { if (isPropertyName(state.tokens.next) || state.tokens.next.id === "[") { computed = state.tokens.next.id === "["; getset = name; name = state.tokens.next; if (state.tokens.next.id === "[") { name = computedPropertyName(); } else advance(); } } } else { warning("W052", state.tokens.next, state.tokens.next.value || state.tokens.next.type); advance(); continue; } if (!checkPunctuator(state.tokens.next, "(")) { error("E054", state.tokens.next, state.tokens.next.value); while (state.tokens.next.id !== "}" && !checkPunctuator(state.tokens.next, "(")) { advance(); } if (state.tokens.next.value !== "(") { doFunction({ statement: c }); } } if (!computed) { if (getset) { saveAccessor( getset.value, isStatic ? staticProps : props, name.value, name, true, isStatic); } else { if (name.value === "constructor") { state.nameStack.set(c); } else { state.nameStack.set(name); } saveProperty(isStatic ? staticProps : props, name.value, name, true, isStatic); } } if (getset && name.value === "constructor") { var propDesc = getset.value === "get" ? "class getter method" : "class setter method"; error("E049", name, propDesc, "constructor"); } else if (name.value === "prototype") { error("E049", name, "class method", "prototype"); } propertyName(name); doFunction({ statement: c, type: isGenerator ? "generator" : null, classExprBinding: c.namedExpr ? c.name : null }); } checkProperties(props); } blockstmt("function", function(context) { var inexport = context && context.inexport; var generator = false; if (state.tokens.next.value === "*") { advance("*"); if (state.inES6({ strict: true })) { generator = true; } else { warning("W119", state.tokens.curr, "function*", "6"); } } if (inblock) { warning("W082", state.tokens.curr); } var i = optionalidentifier(); state.funct["(scope)"].addlabel(i, { type: "function", token: state.tokens.curr }); if (i === undefined) { warning("W025"); } else if (inexport) { state.funct["(scope)"].setExported(i, state.tokens.prev); } doFunction({ name: i, statement: this, type: generator ? "generator" : null, ignoreLoopFunc: inblock // a declaration may already have warned }); if (state.tokens.next.id === "(" && state.tokens.next.line === state.tokens.curr.line) { error("E039"); } return this; }); prefix("function", function() { var generator = false; if (state.tokens.next.value === "*") { if (!state.inES6()) { warning("W119", state.tokens.curr, "function*", "6"); } advance("*"); generator = true; } var i = optionalidentifier(); doFunction({ name: i, type: generator ? "generator" : null }); return this; }); blockstmt("if", function() { var t = state.tokens.next; increaseComplexityCount(); state.condition = true; advance("("); var expr = expression(0); checkCondAssignment(expr); var forinifcheck = null; if (state.option.forin && state.forinifcheckneeded) { state.forinifcheckneeded = false; // We only need to analyze the first if inside the loop forinifcheck = state.forinifchecks[state.forinifchecks.length - 1]; if (expr.type === "(punctuator)" && expr.value === "!") { forinifcheck.type = "(negative)"; } else { forinifcheck.type = "(positive)"; } } advance(")", t); state.condition = false; var s = block(true, true); if (forinifcheck && forinifcheck.type === "(negative)") { if (s && s[0] && s[0].type === "(identifier)" && s[0].value === "continue") { forinifcheck.type = "(negative-with-continue)"; } } if (state.tokens.next.id === "else") { advance("else"); if (state.tokens.next.id === "if" || state.tokens.next.id === "switch") { statement(); } else { block(true, true); } } return this; }); blockstmt("try", function() { var b; function doCatch() { advance("catch"); advance("("); state.funct["(scope)"].stack("catchparams"); if (checkPunctuators(state.tokens.next, ["[", "{"])) { var tokens = destructuringPattern(); _.each(tokens, function(token) { if (token.id) { state.funct["(scope)"].addParam(token.id, token, "exception"); } }); } else if (state.tokens.next.type !== "(identifier)") { warning("E030", state.tokens.next, state.tokens.next.value); } else { state.funct["(scope)"].addParam(identifier(), state.tokens.curr, "exception"); } if (state.tokens.next.value === "if") { if (!state.inMoz()) { warning("W118", state.tokens.curr, "catch filter"); } advance("if"); expression(0); } advance(")"); block(false); state.funct["(scope)"].unstack(); } block(true); while (state.tokens.next.id === "catch") { increaseComplexityCount(); if (b && (!state.inMoz())) { warning("W118", state.tokens.next, "multiple catch blocks"); } doCatch(); b = true; } if (state.tokens.next.id === "finally") { advance("finally"); block(true); return; } if (!b) { error("E021", state.tokens.next, "catch", state.tokens.next.value); } return this; }); blockstmt("while", function() { var t = state.tokens.next; state.funct["(breakage)"] += 1; state.funct["(loopage)"] += 1; increaseComplexityCount(); advance("("); checkCondAssignment(expression(0)); advance(")", t); block(true, true); state.funct["(breakage)"] -= 1; state.funct["(loopage)"] -= 1; return this; }).labelled = true; blockstmt("with", function() { var t = state.tokens.next; if (state.isStrict()) { error("E010", state.tokens.curr); } else if (!state.option.withstmt) { warning("W085", state.tokens.curr); } advance("("); expression(0); advance(")", t); block(true, true); return this; }); blockstmt("switch", function() { var t = state.tokens.next; var g = false; var noindent = false; state.funct["(breakage)"] += 1; advance("("); checkCondAssignment(expression(0)); advance(")", t); t = state.tokens.next; advance("{"); if (state.tokens.next.from === indent) noindent = true; if (!noindent) indent += state.option.indent; this.cases = []; for (;;) { switch (state.tokens.next.id) { case "case": switch (state.funct["(verb)"]) { case "yield": case "break": case "case": case "continue": case "return": case "switch": case "throw": break; default: if (!state.tokens.curr.caseFallsThrough) { warning("W086", state.tokens.curr, "case"); } } advance("case"); this.cases.push(expression(0)); increaseComplexityCount(); g = true; advance(":"); state.funct["(verb)"] = "case"; break; case "default": switch (state.funct["(verb)"]) { case "yield": case "break": case "continue": case "return": case "throw": break; default: if (this.cases.length) { if (!state.tokens.curr.caseFallsThrough) { warning("W086", state.tokens.curr, "default"); } } } advance("default"); g = true; advance(":"); break; case "}": if (!noindent) indent -= state.option.indent; advance("}", t); state.funct["(breakage)"] -= 1; state.funct["(verb)"] = undefined; return; case "(end)": error("E023", state.tokens.next, "}"); return; default: indent += state.option.indent; if (g) { switch (state.tokens.curr.id) { case ",": error("E040"); return; case ":": g = false; statements(); break; default: error("E025", state.tokens.curr); return; } } else { if (state.tokens.curr.id === ":") { advance(":"); error("E024", state.tokens.curr, ":"); statements(); } else { error("E021", state.tokens.next, "case", state.tokens.next.value); return; } } indent -= state.option.indent; } } return this; }).labelled = true; stmt("debugger", function() { if (!state.option.debug) { warning("W087", this); } return this; }).exps = true; (function() { var x = stmt("do", function() { state.funct["(breakage)"] += 1; state.funct["(loopage)"] += 1; increaseComplexityCount(); this.first = block(true, true); advance("while"); var t = state.tokens.next; advance("("); checkCondAssignment(expression(0)); advance(")", t); state.funct["(breakage)"] -= 1; state.funct["(loopage)"] -= 1; return this; }); x.labelled = true; x.exps = true; }()); blockstmt("for", function() { var s, t = state.tokens.next; var letscope = false; var foreachtok = null; if (t.value === "each") { foreachtok = t; advance("each"); if (!state.inMoz()) { warning("W118", state.tokens.curr, "for each"); } } increaseComplexityCount(); advance("("); var nextop; // contains the token of the "in" or "of" operator var i = 0; var inof = ["in", "of"]; var level = 0; // BindingPattern "level" --- level 0 === no BindingPattern var comma; // First comma punctuator at level 0 var initializer; // First initializer at level 0 if (checkPunctuators(state.tokens.next, ["{", "["])) ++level; do { nextop = peek(i); ++i; if (checkPunctuators(nextop, ["{", "["])) ++level; else if (checkPunctuators(nextop, ["}", "]"])) --level; if (level < 0) break; if (level === 0) { if (!comma && checkPunctuator(nextop, ",")) comma = nextop; else if (!initializer && checkPunctuator(nextop, "=")) initializer = nextop; } } while (level > 0 || !_.contains(inof, nextop.value) && nextop.value !== ";" && nextop.type !== "(end)"); // Is this a JSCS bug? This looks really weird. if (_.contains(inof, nextop.value)) { if (!state.inES6() && nextop.value === "of") { warning("W104", nextop, "for of", "6"); } var ok = !(initializer || comma); if (initializer) { error("W133", comma, nextop.value, "initializer is forbidden"); } if (comma) { error("W133", comma, nextop.value, "more than one ForBinding"); } if (state.tokens.next.id === "var") { advance("var"); state.tokens.curr.fud({ prefix: true }); } else if (state.tokens.next.id === "let" || state.tokens.next.id === "const") { advance(state.tokens.next.id); letscope = true; state.funct["(scope)"].stack(); state.tokens.curr.fud({ prefix: true }); } else { Object.create(varstatement).fud({ prefix: true, implied: "for", ignore: !ok }); } advance(nextop.value); expression(20); advance(")", t); if (nextop.value === "in" && state.option.forin) { state.forinifcheckneeded = true; if (state.forinifchecks === undefined) { state.forinifchecks = []; } state.forinifchecks.push({ type: "(none)" }); } state.funct["(breakage)"] += 1; state.funct["(loopage)"] += 1; s = block(true, true); if (nextop.value === "in" && state.option.forin) { if (state.forinifchecks && state.forinifchecks.length > 0) { var check = state.forinifchecks.pop(); if (// No if statement or not the first statement in loop body s && s.length > 0 && (typeof s[0] !== "object" || s[0].value !== "if") || check.type === "(positive)" && s.length > 1 || check.type === "(negative)") { warning("W089", this); } } state.forinifcheckneeded = false; } state.funct["(breakage)"] -= 1; state.funct["(loopage)"] -= 1; } else { if (foreachtok) { error("E045", foreachtok); } if (state.tokens.next.id !== ";") { if (state.tokens.next.id === "var") { advance("var"); state.tokens.curr.fud(); } else if (state.tokens.next.id === "let") { advance("let"); letscope = true; state.funct["(scope)"].stack(); state.tokens.curr.fud(); } else { for (;;) { expression(0, "for"); if (state.tokens.next.id !== ",") { break; } comma(); } } } nolinebreak(state.tokens.curr); advance(";"); state.funct["(loopage)"] += 1; if (state.tokens.next.id !== ";") { checkCondAssignment(expression(0)); } nolinebreak(state.tokens.curr); advance(";"); if (state.tokens.next.id === ";") { error("E021", state.tokens.next, ")", ";"); } if (state.tokens.next.id !== ")") { for (;;) { expression(0, "for"); if (state.tokens.next.id !== ",") { break; } comma(); } } advance(")", t); state.funct["(breakage)"] += 1; block(true, true); state.funct["(breakage)"] -= 1; state.funct["(loopage)"] -= 1; } if (letscope) { state.funct["(scope)"].unstack(); } return this; }).labelled = true; stmt("break", function() { var v = state.tokens.next.value; if (!state.option.asi) nolinebreak(this); if (state.tokens.next.id !== ";" && !state.tokens.next.reach && state.tokens.curr.line === startLine(state.tokens.next)) { if (!state.funct["(scope)"].funct.hasBreakLabel(v)) { warning("W090", state.tokens.next, v); } this.first = state.tokens.next; advance(); } else { if (state.funct["(breakage)"] === 0) warning("W052", state.tokens.next, this.value); } reachable(this); return this; }).exps = true; stmt("continue", function() { var v = state.tokens.next.value; if (state.funct["(breakage)"] === 0) warning("W052", state.tokens.next, this.value); if (!state.funct["(loopage)"]) warning("W052", state.tokens.next, this.value); if (!state.option.asi) nolinebreak(this); if (state.tokens.next.id !== ";" && !state.tokens.next.reach) { if (state.tokens.curr.line === startLine(state.tokens.next)) { if (!state.funct["(scope)"].funct.hasBreakLabel(v)) { warning("W090", state.tokens.next, v); } this.first = state.tokens.next; advance(); } } reachable(this); return this; }).exps = true; stmt("return", function() { if (this.line === startLine(state.tokens.next)) { if (state.tokens.next.id !== ";" && !state.tokens.next.reach) { this.first = expression(0); if (this.first && this.first.type === "(punctuator)" && this.first.value === "=" && !this.first.paren && !state.option.boss) { warningAt("W093", this.first.line, this.first.character); } } } else { if (state.tokens.next.type === "(punctuator)" && ["[", "{", "+", "-"].indexOf(state.tokens.next.value) > -1) { nolinebreak(this); // always warn (Line breaking error) } } reachable(this); return this; }).exps = true; (function(x) { x.exps = true; x.lbp = 25; }(prefix("yield", function() { var prev = state.tokens.prev; if (state.inES6(true) && !state.funct["(generator)"]) { if (!("(catch)" === state.funct["(name)"] && state.funct["(context)"]["(generator)"])) { error("E046", state.tokens.curr, "yield"); } } else if (!state.inES6()) { warning("W104", state.tokens.curr, "yield", "6"); } state.funct["(generator)"] = "yielded"; var delegatingYield = false; if (state.tokens.next.value === "*") { delegatingYield = true; advance("*"); } if (this.line === startLine(state.tokens.next) || !state.inMoz()) { if (delegatingYield || (state.tokens.next.id !== ";" && !state.option.asi && !state.tokens.next.reach && state.tokens.next.nud)) { nobreaknonadjacent(state.tokens.curr, state.tokens.next); this.first = expression(10); if (this.first.type === "(punctuator)" && this.first.value === "=" && !this.first.paren && !state.option.boss) { warningAt("W093", this.first.line, this.first.character); } } if (state.inMoz() && state.tokens.next.id !== ")" && (prev.lbp > 30 || (!prev.assign && !isEndOfExpr()) || prev.id === "yield")) { error("E050", this); } } else if (!state.option.asi) { nolinebreak(this); // always warn (Line breaking error) } return this; }))); stmt("throw", function() { nolinebreak(this); this.first = expression(20); reachable(this); return this; }).exps = true; stmt("import", function() { if (!state.inES6()) { warning("W119", state.tokens.curr, "import", "6"); } if (state.tokens.next.type === "(string)") { advance("(string)"); return this; } if (state.tokens.next.identifier) { this.name = identifier(); state.funct["(scope)"].addlabel(this.name, { type: "const", token: state.tokens.curr }); if (state.tokens.next.value === ",") { advance(","); } else { advance("from"); advance("(string)"); return this; } } if (state.tokens.next.id === "*") { advance("*"); advance("as"); if (state.tokens.next.identifier) { this.name = identifier(); state.funct["(scope)"].addlabel(this.name, { type: "const", token: state.tokens.curr }); } } else { advance("{"); for (;;) { if (state.tokens.next.value === "}") { advance("}"); break; } var importName; if (state.tokens.next.type === "default") { importName = "default"; advance("default"); } else { importName = identifier(); } if (state.tokens.next.value === "as") { advance("as"); importName = identifier(); } state.funct["(scope)"].addlabel(importName, { type: "const", token: state.tokens.curr }); if (state.tokens.next.value === ",") { advance(","); } else if (state.tokens.next.value === "}") { advance("}"); break; } else { error("E024", state.tokens.next, state.tokens.next.value); break; } } } advance("from"); advance("(string)"); return this; }).exps = true; stmt("export", function() { var ok = true; var token; var identifier; if (!state.inES6()) { warning("W119", state.tokens.curr, "export", "6"); ok = false; } if (!state.funct["(scope)"].block.isGlobal()) { error("E053", state.tokens.curr); ok = false; } if (state.tokens.next.value === "*") { advance("*"); advance("from"); advance("(string)"); return this; } if (state.tokens.next.type === "default") { state.nameStack.set(state.tokens.next); advance("default"); var exportType = state.tokens.next.id; if (exportType === "function" || exportType === "class") { this.block = true; } token = peek(); expression(10); identifier = token.value; if (this.block) { state.funct["(scope)"].addlabel(identifier, { type: exportType, token: token }); state.funct["(scope)"].setExported(identifier, token); } return this; } if (state.tokens.next.value === "{") { advance("{"); var exportedTokens = []; for (;;) { if (!state.tokens.next.identifier) { error("E030", state.tokens.next, state.tokens.next.value); } advance(); exportedTokens.push(state.tokens.curr); if (state.tokens.next.value === "as") { advance("as"); if (!state.tokens.next.identifier) { error("E030", state.tokens.next, state.tokens.next.value); } advance(); } if (state.tokens.next.value === ",") { advance(","); } else if (state.tokens.next.value === "}") { advance("}"); break; } else { error("E024", state.tokens.next, state.tokens.next.value); break; } } if (state.tokens.next.value === "from") { advance("from"); advance("(string)"); } else if (ok) { exportedTokens.forEach(function(token) { state.funct["(scope)"].setExported(token.value, token); }); } return this; } if (state.tokens.next.id === "var") { advance("var"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "let") { advance("let"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "const") { advance("const"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "function") { this.block = true; advance("function"); state.syntax["function"].fud({ inexport:true }); } else if (state.tokens.next.id === "class") { this.block = true; advance("class"); var classNameToken = state.tokens.next; state.syntax["class"].fud(); state.funct["(scope)"].setExported(classNameToken.value, classNameToken); } else { error("E024", state.tokens.next, state.tokens.next.value); } return this; }).exps = true; FutureReservedWord("abstract"); FutureReservedWord("boolean"); FutureReservedWord("byte"); FutureReservedWord("char"); FutureReservedWord("class", { es5: true, nud: classdef }); FutureReservedWord("double"); FutureReservedWord("enum", { es5: true }); FutureReservedWord("export", { es5: true }); FutureReservedWord("extends", { es5: true }); FutureReservedWord("final"); FutureReservedWord("float"); FutureReservedWord("goto"); FutureReservedWord("implements", { es5: true, strictOnly: true }); FutureReservedWord("import", { es5: true }); FutureReservedWord("int"); FutureReservedWord("interface", { es5: true, strictOnly: true }); FutureReservedWord("long"); FutureReservedWord("native"); FutureReservedWord("package", { es5: true, strictOnly: true }); FutureReservedWord("private", { es5: true, strictOnly: true }); FutureReservedWord("protected", { es5: true, strictOnly: true }); FutureReservedWord("public", { es5: true, strictOnly: true }); FutureReservedWord("short"); FutureReservedWord("static", { es5: true, strictOnly: true }); FutureReservedWord("super", { es5: true }); FutureReservedWord("synchronized"); FutureReservedWord("transient"); FutureReservedWord("volatile"); var lookupBlockType = function() { var pn, pn1, prev; var i = -1; var bracketStack = 0; var ret = {}; if (checkPunctuators(state.tokens.curr, ["[", "{"])) { bracketStack += 1; } do { prev = i === -1 ? state.tokens.curr : pn; pn = i === -1 ? state.tokens.next : peek(i); pn1 = peek(i + 1); i = i + 1; if (checkPunctuators(pn, ["[", "{"])) { bracketStack += 1; } else if (checkPunctuators(pn, ["]", "}"])) { bracketStack -= 1; } if (bracketStack === 1 && pn.identifier && pn.value === "for" && !checkPunctuator(prev, ".")) { ret.isCompArray = true; ret.notJson = true; break; } if (bracketStack === 0 && checkPunctuators(pn, ["}", "]"])) { if (pn1.value === "=") { ret.isDestAssign = true; ret.notJson = true; break; } else if (pn1.value === ".") { ret.notJson = true; break; } } if (checkPunctuator(pn, ";")) { ret.isBlock = true; ret.notJson = true; } } while (bracketStack > 0 && pn.id !== "(end)"); return ret; }; function saveProperty(props, name, tkn, isClass, isStatic) { var msg = ["key", "class method", "static class method"]; msg = msg[(isClass || false) + (isStatic || false)]; if (tkn.identifier) { name = tkn.value; } if (props[name] && name !== "__proto__") { warning("W075", state.tokens.next, msg, name); } else { props[name] = Object.create(null); } props[name].basic = true; props[name].basictkn = tkn; } function saveAccessor(accessorType, props, name, tkn, isClass, isStatic) { var flagName = accessorType === "get" ? "getterToken" : "setterToken"; var msg = ""; if (isClass) { if (isStatic) { msg += "static "; } msg += accessorType + "ter method"; } else { msg = "key"; } state.tokens.curr.accessorType = accessorType; state.nameStack.set(tkn); if (props[name]) { if ((props[name].basic || props[name][flagName]) && name !== "__proto__") { warning("W075", state.tokens.next, msg, name); } } else { props[name] = Object.create(null); } props[name][flagName] = tkn; } function computedPropertyName() { advance("["); if (!state.inES6()) { warning("W119", state.tokens.curr, "computed property names", "6"); } var value = expression(10); advance("]"); return value; } function checkPunctuators(token, values) { if (token.type === "(punctuator)") { return _.contains(values, token.value); } return false; } function checkPunctuator(token, value) { return token.type === "(punctuator)" && token.value === value; } function destructuringAssignOrJsonValue() { var block = lookupBlockType(); if (block.notJson) { if (!state.inES6() && block.isDestAssign) { warning("W104", state.tokens.curr, "destructuring assignment", "6"); } statements(); } else { state.option.laxbreak = true; state.jsonMode = true; jsonValue(); } } var arrayComprehension = function() { var CompArray = function() { this.mode = "use"; this.variables = []; }; var _carrays = []; var _current; function declare(v) { var l = _current.variables.filter(function(elt) { if (elt.value === v) { elt.undef = false; return v; } }).length; return l !== 0; } function use(v) { var l = _current.variables.filter(function(elt) { if (elt.value === v && !elt.undef) { if (elt.unused === true) { elt.unused = false; } return v; } }).length; return (l === 0); } return { stack: function() { _current = new CompArray(); _carrays.push(_current); }, unstack: function() { _current.variables.filter(function(v) { if (v.unused) warning("W098", v.token, v.raw_text || v.value); if (v.undef) state.funct["(scope)"].block.use(v.value, v.token); }); _carrays.splice(-1, 1); _current = _carrays[_carrays.length - 1]; }, setState: function(s) { if (_.contains(["use", "define", "generate", "filter"], s)) _current.mode = s; }, check: function(v) { if (!_current) { return; } if (_current && _current.mode === "use") { if (use(v)) { _current.variables.push({ funct: state.funct, token: state.tokens.curr, value: v, undef: true, unused: false }); } return true; } else if (_current && _current.mode === "define") { if (!declare(v)) { _current.variables.push({ funct: state.funct, token: state.tokens.curr, value: v, undef: false, unused: true }); } return true; } else if (_current && _current.mode === "generate") { state.funct["(scope)"].block.use(v, state.tokens.curr); return true; } else if (_current && _current.mode === "filter") { if (use(v)) { state.funct["(scope)"].block.use(v, state.tokens.curr); } return true; } return false; } }; }; function jsonValue() { function jsonObject() { var o = {}, t = state.tokens.next; advance("{"); if (state.tokens.next.id !== "}") { for (;;) { if (state.tokens.next.id === "(end)") { error("E026", state.tokens.next, t.line); } else if (state.tokens.next.id === "}") { warning("W094", state.tokens.curr); break; } else if (state.tokens.next.id === ",") { error("E028", state.tokens.next); } else if (state.tokens.next.id !== "(string)") { warning("W095", state.tokens.next, state.tokens.next.value); } if (o[state.tokens.next.value] === true) { warning("W075", state.tokens.next, "key", state.tokens.next.value); } else if ((state.tokens.next.value === "__proto__" && !state.option.proto) || (state.tokens.next.value === "__iterator__" && !state.option.iterator)) { warning("W096", state.tokens.next, state.tokens.next.value); } else { o[state.tokens.next.value] = true; } advance(); advance(":"); jsonValue(); if (state.tokens.next.id !== ",") { break; } advance(","); } } advance("}"); } function jsonArray() { var t = state.tokens.next; advance("["); if (state.tokens.next.id !== "]") { for (;;) { if (state.tokens.next.id === "(end)") { error("E027", state.tokens.next, t.line); } else if (state.tokens.next.id === "]") { warning("W094", state.tokens.curr); break; } else if (state.tokens.next.id === ",") { error("E028", state.tokens.next); } jsonValue(); if (state.tokens.next.id !== ",") { break; } advance(","); } } advance("]"); } switch (state.tokens.next.id) { case "{": jsonObject(); break; case "[": jsonArray(); break; case "true": case "false": case "null": case "(number)": case "(string)": advance(); break; case "-": advance("-"); advance("(number)"); break; default: error("E003", state.tokens.next); } } var escapeRegex = function(str) { return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); }; var itself = function(s, o, g) { var i, k, x, reIgnoreStr, reIgnore; var optionKeys; var newOptionObj = {}; var newIgnoredObj = {}; o = _.clone(o); state.reset(); if (o && o.scope) { JSHINT.scope = o.scope; } else { JSHINT.errors = []; JSHINT.undefs = []; JSHINT.internals = []; JSHINT.blacklist = {}; JSHINT.scope = "(main)"; } predefined = Object.create(null); combine(predefined, vars.ecmaIdentifiers[3]); combine(predefined, vars.reservedVars); combine(predefined, g || {}); declared = Object.create(null); var exported = Object.create(null); // Variables that live outside the current file function each(obj, cb) { if (!obj) return; if (!Array.isArray(obj) && typeof obj === "object") obj = Object.keys(obj); obj.forEach(cb); } if (o) { each(o.predef || null, function(item) { var slice, prop; if (item[0] === "-") { slice = item.slice(1); JSHINT.blacklist[slice] = slice; delete predefined[slice]; } else { prop = Object.getOwnPropertyDescriptor(o.predef, item); predefined[item] = prop ? prop.value : false; } }); each(o.exported || null, function(item) { exported[item] = true; }); delete o.predef; delete o.exported; optionKeys = Object.keys(o); for (x = 0; x < optionKeys.length; x++) { if (/^-W\d{3}$/g.test(optionKeys[x])) { newIgnoredObj[optionKeys[x].slice(1)] = true; } else { var optionKey = optionKeys[x]; newOptionObj[optionKey] = o[optionKey]; if ((optionKey === "esversion" && o[optionKey] === 5) || (optionKey === "es5" && o[optionKey])) { warning("I003"); } if (optionKeys[x] === "newcap" && o[optionKey] === false) newOptionObj["(explicitNewcap)"] = true; } } } state.option = newOptionObj; state.ignored = newIgnoredObj; state.option.indent = state.option.indent || 4; state.option.maxerr = state.option.maxerr || 50; indent = 1; var scopeManagerInst = scopeManager(state, predefined, exported, declared); scopeManagerInst.on("warning", function(ev) { warning.apply(null, [ ev.code, ev.token].concat(ev.data)); }); scopeManagerInst.on("error", function(ev) { error.apply(null, [ ev.code, ev.token ].concat(ev.data)); }); state.funct = functor("(global)", null, { "(global)" : true, "(scope)" : scopeManagerInst, "(comparray)" : arrayComprehension(), "(metrics)" : createMetrics(state.tokens.next) }); functions = [state.funct]; urls = []; stack = null; member = {}; membersOnly = null; inblock = false; lookahead = []; if (!isString(s) && !Array.isArray(s)) { errorAt("E004", 0); return false; } api = { get isJSON() { return state.jsonMode; }, getOption: function(name) { return state.option[name] || null; }, getCache: function(name) { return state.cache[name]; }, setCache: function(name, value) { state.cache[name] = value; }, warn: function(code, data) { warningAt.apply(null, [ code, data.line, data.char ].concat(data.data)); }, on: function(names, listener) { names.split(" ").forEach(function(name) { emitter.on(name, listener); }.bind(this)); } }; emitter.removeAllListeners(); (extraModules || []).forEach(function(func) { func(api); }); state.tokens.prev = state.tokens.curr = state.tokens.next = state.syntax["(begin)"]; if (o && o.ignoreDelimiters) { if (!Array.isArray(o.ignoreDelimiters)) { o.ignoreDelimiters = [o.ignoreDelimiters]; } o.ignoreDelimiters.forEach(function(delimiterPair) { if (!delimiterPair.start || !delimiterPair.end) return; reIgnoreStr = escapeRegex(delimiterPair.start) + "[\\s\\S]*?" + escapeRegex(delimiterPair.end); reIgnore = new RegExp(reIgnoreStr, "ig"); s = s.replace(reIgnore, function(match) { return match.replace(/./g, " "); }); }); } lex = new Lexer(s); lex.on("warning", function(ev) { warningAt.apply(null, [ ev.code, ev.line, ev.character].concat(ev.data)); }); lex.on("error", function(ev) { errorAt.apply(null, [ ev.code, ev.line, ev.character ].concat(ev.data)); }); lex.on("fatal", function(ev) { quit("E041", ev.line, ev.from); }); lex.on("Identifier", function(ev) { emitter.emit("Identifier", ev); }); lex.on("String", function(ev) { emitter.emit("String", ev); }); lex.on("Number", function(ev) { emitter.emit("Number", ev); }); lex.start(); for (var name in o) { if (_.has(o, name)) { checkOption(name, state.tokens.curr); } } assume(); combine(predefined, g || {}); comma.first = true; try { advance(); switch (state.tokens.next.id) { case "{": case "[": destructuringAssignOrJsonValue(); break; default: directives(); if (state.directive["use strict"]) { if (state.option.strict !== "global") { warning("W097", state.tokens.prev); } } statements(); } if (state.tokens.next.id !== "(end)") { quit("E041", state.tokens.curr.line); } state.funct["(scope)"].unstack(); } catch (err) { if (err && err.name === "JSHintError") { var nt = state.tokens.next || {}; JSHINT.errors.push({ scope : "(main)", raw : err.raw, code : err.code, reason : err.message, line : err.line || nt.line, character : err.character || nt.from }, null); } else { throw err; } } if (JSHINT.scope === "(main)") { o = o || {}; for (i = 0; i < JSHINT.internals.length; i += 1) { k = JSHINT.internals[i]; o.scope = k.elem; itself(k.value, o, g); } } return JSHINT.errors.length === 0; }; itself.addModule = function(func) { extraModules.push(func); }; itself.addModule(style.register); itself.data = function() { var data = { functions: [], options: state.option }; var fu, f, i, j, n, globals; if (itself.errors.length) { data.errors = itself.errors; } if (state.jsonMode) { data.json = true; } var impliedGlobals = state.funct["(scope)"].getImpliedGlobals(); if (impliedGlobals.length > 0) { data.implieds = impliedGlobals; } if (urls.length > 0) { data.urls = urls; } globals = state.funct["(scope)"].getUsedOrDefinedGlobals(); if (globals.length > 0) { data.globals = globals; } for (i = 1; i < functions.length; i += 1) { f = functions[i]; fu = {}; for (j = 0; j < functionicity.length; j += 1) { fu[functionicity[j]] = []; } for (j = 0; j < functionicity.length; j += 1) { if (fu[functionicity[j]].length === 0) { delete fu[functionicity[j]]; } } fu.name = f["(name)"]; fu.param = f["(params)"]; fu.line = f["(line)"]; fu.character = f["(character)"]; fu.last = f["(last)"]; fu.lastcharacter = f["(lastcharacter)"]; fu.metrics = { complexity: f["(metrics)"].ComplexityCount, parameters: f["(metrics)"].arity, statements: f["(metrics)"].statementCount }; data.functions.push(fu); } var unuseds = state.funct["(scope)"].getUnuseds(); if (unuseds.length > 0) { data.unused = unuseds; } for (n in member) { if (typeof member[n] === "number") { data.member = member; break; } } return data; }; itself.jshint = itself; return itself; }()); if (typeof exports === "object" && exports) { exports.JSHINT = JSHINT; } },{"../lodash":"/node_modules/jshint/lodash.js","./lex.js":"/node_modules/jshint/src/lex.js","./messages.js":"/node_modules/jshint/src/messages.js","./options.js":"/node_modules/jshint/src/options.js","./reg.js":"/node_modules/jshint/src/reg.js","./scope-manager.js":"/node_modules/jshint/src/scope-manager.js","./state.js":"/node_modules/jshint/src/state.js","./style.js":"/node_modules/jshint/src/style.js","./vars.js":"/node_modules/jshint/src/vars.js","events":"/node_modules/browserify/node_modules/events/events.js"}],"/node_modules/jshint/src/lex.js":[function(_dereq_,module,exports){ "use strict"; var _ = _dereq_("../lodash"); var events = _dereq_("events"); var reg = _dereq_("./reg.js"); var state = _dereq_("./state.js").state; var unicodeData = _dereq_("../data/ascii-identifier-data.js"); var asciiIdentifierStartTable = unicodeData.asciiIdentifierStartTable; var asciiIdentifierPartTable = unicodeData.asciiIdentifierPartTable; var Token = { Identifier: 1, Punctuator: 2, NumericLiteral: 3, StringLiteral: 4, Comment: 5, Keyword: 6, NullLiteral: 7, BooleanLiteral: 8, RegExp: 9, TemplateHead: 10, TemplateMiddle: 11, TemplateTail: 12, NoSubstTemplate: 13 }; var Context = { Block: 1, Template: 2 }; function asyncTrigger() { var _checks = []; return { push: function(fn) { _checks.push(fn); }, check: function() { for (var check = 0; check < _checks.length; ++check) { _checks[check](); } _checks.splice(0, _checks.length); } }; } function Lexer(source) { var lines = source; if (typeof lines === "string") { lines = lines .replace(/\r\n/g, "\n") .replace(/\r/g, "\n") .split("\n"); } if (lines[0] && lines[0].substr(0, 2) === "#!") { if (lines[0].indexOf("node") !== -1) { state.option.node = true; } lines[0] = ""; } this.emitter = new events.EventEmitter(); this.source = source; this.setLines(lines); this.prereg = true; this.line = 0; this.char = 1; this.from = 1; this.input = ""; this.inComment = false; this.context = []; this.templateStarts = []; for (var i = 0; i < state.option.indent; i += 1) { state.tab += " "; } this.ignoreLinterErrors = false; } Lexer.prototype = { _lines: [], inContext: function(ctxType) { return this.context.length > 0 && this.context[this.context.length - 1].type === ctxType; }, pushContext: function(ctxType) { this.context.push({ type: ctxType }); }, popContext: function() { return this.context.pop(); }, isContext: function(context) { return this.context.length > 0 && this.context[this.context.length - 1] === context; }, currentContext: function() { return this.context.length > 0 && this.context[this.context.length - 1]; }, getLines: function() { this._lines = state.lines; return this._lines; }, setLines: function(val) { this._lines = val; state.lines = this._lines; }, peek: function(i) { return this.input.charAt(i || 0); }, skip: function(i) { i = i || 1; this.char += i; this.input = this.input.slice(i); }, on: function(names, listener) { names.split(" ").forEach(function(name) { this.emitter.on(name, listener); }.bind(this)); }, trigger: function() { this.emitter.emit.apply(this.emitter, Array.prototype.slice.call(arguments)); }, triggerAsync: function(type, args, checks, fn) { checks.push(function() { if (fn()) { this.trigger(type, args); } }.bind(this)); }, scanPunctuator: function() { var ch1 = this.peek(); var ch2, ch3, ch4; switch (ch1) { case ".": if ((/^[0-9]$/).test(this.peek(1))) { return null; } if (this.peek(1) === "." && this.peek(2) === ".") { return { type: Token.Punctuator, value: "..." }; } case "(": case ")": case ";": case ",": case "[": case "]": case ":": case "~": case "?": return { type: Token.Punctuator, value: ch1 }; case "{": this.pushContext(Context.Block); return { type: Token.Punctuator, value: ch1 }; case "}": if (this.inContext(Context.Block)) { this.popContext(); } return { type: Token.Punctuator, value: ch1 }; case "#": return { type: Token.Punctuator, value: ch1 }; case "": return null; } ch2 = this.peek(1); ch3 = this.peek(2); ch4 = this.peek(3); if (ch1 === ">" && ch2 === ">" && ch3 === ">" && ch4 === "=") { return { type: Token.Punctuator, value: ">>>=" }; } if (ch1 === "=" && ch2 === "=" && ch3 === "=") { return { type: Token.Punctuator, value: "===" }; } if (ch1 === "!" && ch2 === "=" && ch3 === "=") { return { type: Token.Punctuator, value: "!==" }; } if (ch1 === ">" && ch2 === ">" && ch3 === ">") { return { type: Token.Punctuator, value: ">>>" }; } if (ch1 === "<" && ch2 === "<" && ch3 === "=") { return { type: Token.Punctuator, value: "<<=" }; } if (ch1 === ">" && ch2 === ">" && ch3 === "=") { return { type: Token.Punctuator, value: ">>=" }; } if (ch1 === "=" && ch2 === ">") { return { type: Token.Punctuator, value: ch1 + ch2 }; } if (ch1 === ch2 && ("+-<>&|".indexOf(ch1) >= 0)) { return { type: Token.Punctuator, value: ch1 + ch2 }; } if ("<>=!+-*%&|^".indexOf(ch1) >= 0) { if (ch2 === "=") { return { type: Token.Punctuator, value: ch1 + ch2 }; } return { type: Token.Punctuator, value: ch1 }; } if (ch1 === "/") { if (ch2 === "=") { return { type: Token.Punctuator, value: "/=" }; } return { type: Token.Punctuator, value: "/" }; } return null; }, scanComments: function() { var ch1 = this.peek(); var ch2 = this.peek(1); var rest = this.input.substr(2); var startLine = this.line; var startChar = this.char; var self = this; function commentToken(label, body, opt) { var special = ["jshint", "jslint", "members", "member", "globals", "global", "exported"]; var isSpecial = false; var value = label + body; var commentType = "plain"; opt = opt || {}; if (opt.isMultiline) { value += "*/"; } body = body.replace(/\n/g, " "); if (label === "/*" && reg.fallsThrough.test(body)) { isSpecial = true; commentType = "falls through"; } special.forEach(function(str) { if (isSpecial) { return; } if (label === "//" && str !== "jshint") { return; } if (body.charAt(str.length) === " " && body.substr(0, str.length) === str) { isSpecial = true; label = label + str; body = body.substr(str.length); } if (!isSpecial && body.charAt(0) === " " && body.charAt(str.length + 1) === " " && body.substr(1, str.length) === str) { isSpecial = true; label = label + " " + str; body = body.substr(str.length + 1); } if (!isSpecial) { return; } switch (str) { case "member": commentType = "members"; break; case "global": commentType = "globals"; break; default: var options = body.split(":").map(function(v) { return v.replace(/^\s+/, "").replace(/\s+$/, ""); }); if (options.length === 2) { switch (options[0]) { case "ignore": switch (options[1]) { case "start": self.ignoringLinterErrors = true; isSpecial = false; break; case "end": self.ignoringLinterErrors = false; isSpecial = false; break; } } } commentType = str; } }); return { type: Token.Comment, commentType: commentType, value: value, body: body, isSpecial: isSpecial, isMultiline: opt.isMultiline || false, isMalformed: opt.isMalformed || false }; } if (ch1 === "*" && ch2 === "/") { this.trigger("error", { code: "E018", line: startLine, character: startChar }); this.skip(2); return null; } if (ch1 !== "/" || (ch2 !== "*" && ch2 !== "/")) { return null; } if (ch2 === "/") { this.skip(this.input.length); // Skip to the EOL. return commentToken("//", rest); } var body = ""; if (ch2 === "*") { this.inComment = true; this.skip(2); while (this.peek() !== "*" || this.peek(1) !== "/") { if (this.peek() === "") { // End of Line body += "\n"; if (!this.nextLine()) { this.trigger("error", { code: "E017", line: startLine, character: startChar }); this.inComment = false; return commentToken("/*", body, { isMultiline: true, isMalformed: true }); } } else { body += this.peek(); this.skip(); } } this.skip(2); this.inComment = false; return commentToken("/*", body, { isMultiline: true }); } }, scanKeyword: function() { var result = /^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input); var keywords = [ "if", "in", "do", "var", "for", "new", "try", "let", "this", "else", "case", "void", "with", "enum", "while", "break", "catch", "throw", "const", "yield", "class", "super", "return", "typeof", "delete", "switch", "export", "import", "default", "finally", "extends", "function", "continue", "debugger", "instanceof" ]; if (result && keywords.indexOf(result[0]) >= 0) { return { type: Token.Keyword, value: result[0] }; } return null; }, scanIdentifier: function() { var id = ""; var index = 0; var type, char; function isNonAsciiIdentifierStart(code) { return code > 256; } function isNonAsciiIdentifierPart(code) { return code > 256; } function isHexDigit(str) { return (/^[0-9a-fA-F]$/).test(str); } var readUnicodeEscapeSequence = function() { index += 1; if (this.peek(index) !== "u") { return null; } var ch1 = this.peek(index + 1); var ch2 = this.peek(index + 2); var ch3 = this.peek(index + 3); var ch4 = this.peek(index + 4); var code; if (isHexDigit(ch1) && isHexDigit(ch2) && isHexDigit(ch3) && isHexDigit(ch4)) { code = parseInt(ch1 + ch2 + ch3 + ch4, 16); if (asciiIdentifierPartTable[code] || isNonAsciiIdentifierPart(code)) { index += 5; return "\\u" + ch1 + ch2 + ch3 + ch4; } return null; } return null; }.bind(this); var getIdentifierStart = function() { var chr = this.peek(index); var code = chr.charCodeAt(0); if (code === 92) { return readUnicodeEscapeSequence(); } if (code < 128) { if (asciiIdentifierStartTable[code]) { index += 1; return chr; } return null; } if (isNonAsciiIdentifierStart(code)) { index += 1; return chr; } return null; }.bind(this); var getIdentifierPart = function() { var chr = this.peek(index); var code = chr.charCodeAt(0); if (code === 92) { return readUnicodeEscapeSequence(); } if (code < 128) { if (asciiIdentifierPartTable[code]) { index += 1; return chr; } return null; } if (isNonAsciiIdentifierPart(code)) { index += 1; return chr; } return null; }.bind(this); function removeEscapeSequences(id) { return id.replace(/\\u([0-9a-fA-F]{4})/g, function(m0, codepoint) { return String.fromCharCode(parseInt(codepoint, 16)); }); } char = getIdentifierStart(); if (char === null) { return null; } id = char; for (;;) { char = getIdentifierPart(); if (char === null) { break; } id += char; } switch (id) { case "true": case "false": type = Token.BooleanLiteral; break; case "null": type = Token.NullLiteral; break; default: type = Token.Identifier; } return { type: type, value: removeEscapeSequences(id), text: id, tokenLength: id.length }; }, scanNumericLiteral: function() { var index = 0; var value = ""; var length = this.input.length; var char = this.peek(index); var bad; var isAllowedDigit = isDecimalDigit; var base = 10; var isLegacy = false; function isDecimalDigit(str) { return (/^[0-9]$/).test(str); } function isOctalDigit(str) { return (/^[0-7]$/).test(str); } function isBinaryDigit(str) { return (/^[01]$/).test(str); } function isHexDigit(str) { return (/^[0-9a-fA-F]$/).test(str); } function isIdentifierStart(ch) { return (ch === "$") || (ch === "_") || (ch === "\\") || (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"); } if (char !== "." && !isDecimalDigit(char)) { return null; } if (char !== ".") { value = this.peek(index); index += 1; char = this.peek(index); if (value === "0") { if (char === "x" || char === "X") { isAllowedDigit = isHexDigit; base = 16; index += 1; value += char; } if (char === "o" || char === "O") { isAllowedDigit = isOctalDigit; base = 8; if (!state.inES6(true)) { this.trigger("warning", { code: "W119", line: this.line, character: this.char, data: [ "Octal integer literal", "6" ] }); } index += 1; value += char; } if (char === "b" || char === "B") { isAllowedDigit = isBinaryDigit; base = 2; if (!state.inES6(true)) { this.trigger("warning", { code: "W119", line: this.line, character: this.char, data: [ "Binary integer literal", "6" ] }); } index += 1; value += char; } if (isOctalDigit(char)) { isAllowedDigit = isOctalDigit; base = 8; isLegacy = true; bad = false; index += 1; value += char; } if (!isOctalDigit(char) && isDecimalDigit(char)) { index += 1; value += char; } } while (index < length) { char = this.peek(index); if (isLegacy && isDecimalDigit(char)) { bad = true; } else if (!isAllowedDigit(char)) { break; } value += char; index += 1; } if (isAllowedDigit !== isDecimalDigit) { if (!isLegacy && value.length <= 2) { // 0x return { type: Token.NumericLiteral, value: value, isMalformed: true }; } if (index < length) { char = this.peek(index); if (isIdentifierStart(char)) { return null; } } return { type: Token.NumericLiteral, value: value, base: base, isLegacy: isLegacy, isMalformed: false }; } } if (char === ".") { value += char; index += 1; while (index < length) { char = this.peek(index); if (!isDecimalDigit(char)) { break; } value += char; index += 1; } } if (char === "e" || char === "E") { value += char; index += 1; char = this.peek(index); if (char === "+" || char === "-") { value += this.peek(index); index += 1; } char = this.peek(index); if (isDecimalDigit(char)) { value += char; index += 1; while (index < length) { char = this.peek(index); if (!isDecimalDigit(char)) { break; } value += char; index += 1; } } else { return null; } } if (index < length) { char = this.peek(index); if (isIdentifierStart(char)) { return null; } } return { type: Token.NumericLiteral, value: value, base: base, isMalformed: !isFinite(value) }; }, scanEscapeSequence: function(checks) { var allowNewLine = false; var jump = 1; this.skip(); var char = this.peek(); switch (char) { case "'": this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\'" ] }, checks, function() {return state.jsonMode; }); break; case "b": char = "\\b"; break; case "f": char = "\\f"; break; case "n": char = "\\n"; break; case "r": char = "\\r"; break; case "t": char = "\\t"; break; case "0": char = "\\0"; var n = parseInt(this.peek(1), 10); this.triggerAsync("warning", { code: "W115", line: this.line, character: this.char }, checks, function() { return n >= 0 && n <= 7 && state.isStrict(); }); break; case "u": var hexCode = this.input.substr(1, 4); var code = parseInt(hexCode, 16); if (isNaN(code)) { this.trigger("warning", { code: "W052", line: this.line, character: this.char, data: [ "u" + hexCode ] }); } char = String.fromCharCode(code); jump = 5; break; case "v": this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\v" ] }, checks, function() { return state.jsonMode; }); char = "\v"; break; case "x": var x = parseInt(this.input.substr(1, 2), 16); this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\x-" ] }, checks, function() { return state.jsonMode; }); char = String.fromCharCode(x); jump = 3; break; case "\\": char = "\\\\"; break; case "\"": char = "\\\""; break; case "/": break; case "": allowNewLine = true; char = ""; break; } return { char: char, jump: jump, allowNewLine: allowNewLine }; }, scanTemplateLiteral: function(checks) { var tokenType; var value = ""; var ch; var startLine = this.line; var startChar = this.char; var depth = this.templateStarts.length; if (!state.inES6(true)) { return null; } else if (this.peek() === "`") { tokenType = Token.TemplateHead; this.templateStarts.push({ line: this.line, char: this.char }); depth = this.templateStarts.length; this.skip(1); this.pushContext(Context.Template); } else if (this.inContext(Context.Template) && this.peek() === "}") { tokenType = Token.TemplateMiddle; } else { return null; } while (this.peek() !== "`") { while ((ch = this.peek()) === "") { value += "\n"; if (!this.nextLine()) { var startPos = this.templateStarts.pop(); this.trigger("error", { code: "E052", line: startPos.line, character: startPos.char }); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: true, depth: depth, context: this.popContext() }; } } if (ch === '$' && this.peek(1) === '{') { value += '${'; this.skip(2); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, depth: depth, context: this.currentContext() }; } else if (ch === '\\') { var escape = this.scanEscapeSequence(checks); value += escape.char; this.skip(escape.jump); } else if (ch !== '`') { value += ch; this.skip(1); } } tokenType = tokenType === Token.TemplateHead ? Token.NoSubstTemplate : Token.TemplateTail; this.skip(1); this.templateStarts.pop(); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, depth: depth, context: this.popContext() }; }, scanStringLiteral: function(checks) { var quote = this.peek(); if (quote !== "\"" && quote !== "'") { return null; } this.triggerAsync("warning", { code: "W108", line: this.line, character: this.char // +1? }, checks, function() { return state.jsonMode && quote !== "\""; }); var value = ""; var startLine = this.line; var startChar = this.char; var allowNewLine = false; this.skip(); while (this.peek() !== quote) { if (this.peek() === "") { // End Of Line if (!allowNewLine) { this.trigger("warning", { code: "W112", line: this.line, character: this.char }); } else { allowNewLine = false; this.triggerAsync("warning", { code: "W043", line: this.line, character: this.char }, checks, function() { return !state.option.multistr; }); this.triggerAsync("warning", { code: "W042", line: this.line, character: this.char }, checks, function() { return state.jsonMode && state.option.multistr; }); } if (!this.nextLine()) { this.trigger("error", { code: "E029", line: startLine, character: startChar }); return { type: Token.StringLiteral, value: value, startLine: startLine, startChar: startChar, isUnclosed: true, quote: quote }; } } else { // Any character other than End Of Line allowNewLine = false; var char = this.peek(); var jump = 1; // A length of a jump, after we're done if (char < " ") { this.trigger("warning", { code: "W113", line: this.line, character: this.char, data: [ "<non-printable>" ] }); } if (char === "\\") { var parsed = this.scanEscapeSequence(checks); char = parsed.char; jump = parsed.jump; allowNewLine = parsed.allowNewLine; } value += char; this.skip(jump); } } this.skip(); return { type: Token.StringLiteral, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, quote: quote }; }, scanRegExp: function() { var index = 0; var length = this.input.length; var char = this.peek(); var value = char; var body = ""; var flags = []; var malformed = false; var isCharSet = false; var terminated; var scanUnexpectedChars = function() { if (char < " ") { malformed = true; this.trigger("warning", { code: "W048", line: this.line, character: this.char }); } if (char === "<") { malformed = true; this.trigger("warning", { code: "W049", line: this.line, character: this.char, data: [ char ] }); } }.bind(this); if (!this.prereg || char !== "/") { return null; } index += 1; terminated = false; while (index < length) { char = this.peek(index); value += char; body += char; if (isCharSet) { if (char === "]") { if (this.peek(index - 1) !== "\\" || this.peek(index - 2) === "\\") { isCharSet = false; } } if (char === "\\") { index += 1; char = this.peek(index); body += char; value += char; scanUnexpectedChars(); } index += 1; continue; } if (char === "\\") { index += 1; char = this.peek(index); body += char; value += char; scanUnexpectedChars(); if (char === "/") { index += 1; continue; } if (char === "[") { index += 1; continue; } } if (char === "[") { isCharSet = true; index += 1; continue; } if (char === "/") { body = body.substr(0, body.length - 1); terminated = true; index += 1; break; } index += 1; } if (!terminated) { this.trigger("error", { code: "E015", line: this.line, character: this.from }); return void this.trigger("fatal", { line: this.line, from: this.from }); } while (index < length) { char = this.peek(index); if (!/[gim]/.test(char)) { break; } flags.push(char); value += char; index += 1; } try { new RegExp(body, flags.join("")); } catch (err) { malformed = true; this.trigger("error", { code: "E016", line: this.line, character: this.char, data: [ err.message ] // Platform dependent! }); } return { type: Token.RegExp, value: value, flags: flags, isMalformed: malformed }; }, scanNonBreakingSpaces: function() { return state.option.nonbsp ? this.input.search(/(\u00A0)/) : -1; }, scanUnsafeChars: function() { return this.input.search(reg.unsafeChars); }, next: function(checks) { this.from = this.char; var start; if (/\s/.test(this.peek())) { start = this.char; while (/\s/.test(this.peek())) { this.from += 1; this.skip(); } } var match = this.scanComments() || this.scanStringLiteral(checks) || this.scanTemplateLiteral(checks); if (match) { return match; } match = this.scanRegExp() || this.scanPunctuator() || this.scanKeyword() || this.scanIdentifier() || this.scanNumericLiteral(); if (match) { this.skip(match.tokenLength || match.value.length); return match; } return null; }, nextLine: function() { var char; if (this.line >= this.getLines().length) { return false; } this.input = this.getLines()[this.line]; this.line += 1; this.char = 1; this.from = 1; var inputTrimmed = this.input.trim(); var startsWith = function() { return _.some(arguments, function(prefix) { return inputTrimmed.indexOf(prefix) === 0; }); }; var endsWith = function() { return _.some(arguments, function(suffix) { return inputTrimmed.indexOf(suffix, inputTrimmed.length - suffix.length) !== -1; }); }; if (this.ignoringLinterErrors === true) { if (!startsWith("/*", "//") && !(this.inComment && endsWith("*/"))) { this.input = ""; } } char = this.scanNonBreakingSpaces(); if (char >= 0) { this.trigger("warning", { code: "W125", line: this.line, character: char + 1 }); } this.input = this.input.replace(/\t/g, state.tab); char = this.scanUnsafeChars(); if (char >= 0) { this.trigger("warning", { code: "W100", line: this.line, character: char }); } if (!this.ignoringLinterErrors && state.option.maxlen && state.option.maxlen < this.input.length) { var inComment = this.inComment || startsWith.call(inputTrimmed, "//") || startsWith.call(inputTrimmed, "/*"); var shouldTriggerError = !inComment || !reg.maxlenException.test(inputTrimmed); if (shouldTriggerError) { this.trigger("warning", { code: "W101", line: this.line, character: this.input.length }); } } return true; }, start: function() { this.nextLine(); }, token: function() { var checks = asyncTrigger(); var token; function isReserved(token, isProperty) { if (!token.reserved) { return false; } var meta = token.meta; if (meta && meta.isFutureReservedWord && state.inES5()) { if (!meta.es5) { return false; } if (meta.strictOnly) { if (!state.option.strict && !state.isStrict()) { return false; } } if (isProperty) { return false; } } return true; } var create = function(type, value, isProperty, token) { var obj; if (type !== "(endline)" && type !== "(end)") { this.prereg = false; } if (type === "(punctuator)") { switch (value) { case ".": case ")": case "~": case "#": case "]": case "++": case "--": this.prereg = false; break; default: this.prereg = true; } obj = Object.create(state.syntax[value] || state.syntax["(error)"]); } if (type === "(identifier)") { if (value === "return" || value === "case" || value === "typeof") { this.prereg = true; } if (_.has(state.syntax, value)) { obj = Object.create(state.syntax[value] || state.syntax["(error)"]); if (!isReserved(obj, isProperty && type === "(identifier)")) { obj = null; } } } if (!obj) { obj = Object.create(state.syntax[type]); } obj.identifier = (type === "(identifier)"); obj.type = obj.type || type; obj.value = value; obj.line = this.line; obj.character = this.char; obj.from = this.from; if (obj.identifier && token) obj.raw_text = token.text || token.value; if (token && token.startLine && token.startLine !== this.line) { obj.startLine = token.startLine; } if (token && token.context) { obj.context = token.context; } if (token && token.depth) { obj.depth = token.depth; } if (token && token.isUnclosed) { obj.isUnclosed = token.isUnclosed; } if (isProperty && obj.identifier) { obj.isProperty = isProperty; } obj.check = checks.check; return obj; }.bind(this); for (;;) { if (!this.input.length) { if (this.nextLine()) { return create("(endline)", ""); } if (this.exhausted) { return null; } this.exhausted = true; return create("(end)", ""); } token = this.next(checks); if (!token) { if (this.input.length) { this.trigger("error", { code: "E024", line: this.line, character: this.char, data: [ this.peek() ] }); this.input = ""; } continue; } switch (token.type) { case Token.StringLiteral: this.triggerAsync("String", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value, quote: token.quote }, checks, function() { return true; }); return create("(string)", token.value, null, token); case Token.TemplateHead: this.trigger("TemplateHead", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template)", token.value, null, token); case Token.TemplateMiddle: this.trigger("TemplateMiddle", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template middle)", token.value, null, token); case Token.TemplateTail: this.trigger("TemplateTail", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template tail)", token.value, null, token); case Token.NoSubstTemplate: this.trigger("NoSubstTemplate", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(no subst template)", token.value, null, token); case Token.Identifier: this.triggerAsync("Identifier", { line: this.line, char: this.char, from: this.form, name: token.value, raw_name: token.text, isProperty: state.tokens.curr.id === "." }, checks, function() { return true; }); case Token.Keyword: case Token.NullLiteral: case Token.BooleanLiteral: return create("(identifier)", token.value, state.tokens.curr.id === ".", token); case Token.NumericLiteral: if (token.isMalformed) { this.trigger("warning", { code: "W045", line: this.line, character: this.char, data: [ token.value ] }); } this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "0x-" ] }, checks, function() { return token.base === 16 && state.jsonMode; }); this.triggerAsync("warning", { code: "W115", line: this.line, character: this.char }, checks, function() { return state.isStrict() && token.base === 8 && token.isLegacy; }); this.trigger("Number", { line: this.line, char: this.char, from: this.from, value: token.value, base: token.base, isMalformed: token.malformed }); return create("(number)", token.value); case Token.RegExp: return create("(regexp)", token.value); case Token.Comment: state.tokens.curr.comment = true; if (token.isSpecial) { return { id: '(comment)', value: token.value, body: token.body, type: token.commentType, isSpecial: token.isSpecial, line: this.line, character: this.char, from: this.from }; } break; case "": break; default: return create("(punctuator)", token.value); } } } }; exports.Lexer = Lexer; exports.Context = Context; },{"../data/ascii-identifier-data.js":"/node_modules/jshint/data/ascii-identifier-data.js","../lodash":"/node_modules/jshint/lodash.js","./reg.js":"/node_modules/jshint/src/reg.js","./state.js":"/node_modules/jshint/src/state.js","events":"/node_modules/browserify/node_modules/events/events.js"}],"/node_modules/jshint/src/messages.js":[function(_dereq_,module,exports){ "use strict"; var _ = _dereq_("../lodash"); var errors = { E001: "Bad option: '{a}'.", E002: "Bad option value.", E003: "Expected a JSON value.", E004: "Input is neither a string nor an array of strings.", E005: "Input is empty.", E006: "Unexpected early end of program.", E007: "Missing \"use strict\" statement.", E008: "Strict violation.", E009: "Option 'validthis' can't be used in a global scope.", E010: "'with' is not allowed in strict mode.", E011: "'{a}' has already been declared.", E012: "const '{a}' is initialized to 'undefined'.", E013: "Attempting to override '{a}' which is a constant.", E014: "A regular expression literal can be confused with '/='.", E015: "Unclosed regular expression.", E016: "Invalid regular expression.", E017: "Unclosed comment.", E018: "Unbegun comment.", E019: "Unmatched '{a}'.", E020: "Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", E021: "Expected '{a}' and instead saw '{b}'.", E022: "Line breaking error '{a}'.", E023: "Missing '{a}'.", E024: "Unexpected '{a}'.", E025: "Missing ':' on a case clause.", E026: "Missing '}' to match '{' from line {a}.", E027: "Missing ']' to match '[' from line {a}.", E028: "Illegal comma.", E029: "Unclosed string.", E030: "Expected an identifier and instead saw '{a}'.", E031: "Bad assignment.", // FIXME: Rephrase E032: "Expected a small integer or 'false' and instead saw '{a}'.", E033: "Expected an operator and instead saw '{a}'.", E034: "get/set are ES5 features.", E035: "Missing property name.", E036: "Expected to see a statement and instead saw a block.", E037: null, E038: null, E039: "Function declarations are not invocable. Wrap the whole function invocation in parens.", E040: "Each value should have its own case label.", E041: "Unrecoverable syntax error.", E042: "Stopping.", E043: "Too many errors.", E044: null, E045: "Invalid for each loop.", E046: "A yield statement shall be within a generator function (with syntax: `function*`)", E047: null, E048: "{a} declaration not directly within block.", E049: "A {a} cannot be named '{b}'.", E050: "Mozilla requires the yield expression to be parenthesized here.", E051: null, E052: "Unclosed template literal.", E053: "Export declaration must be in global scope.", E054: "Class properties must be methods. Expected '(' but instead saw '{a}'.", E055: "The '{a}' option cannot be set after any executable code.", E056: "'{a}' was used before it was declared, which is illegal for '{b}' variables.", E057: "Invalid meta property: '{a}.{b}'.", E058: "Missing semicolon." }; var warnings = { W001: "'hasOwnProperty' is a really bad name.", W002: "Value of '{a}' may be overwritten in IE 8 and earlier.", W003: "'{a}' was used before it was defined.", W004: "'{a}' is already defined.", W005: "A dot following a number can be confused with a decimal point.", W006: "Confusing minuses.", W007: "Confusing plusses.", W008: "A leading decimal point can be confused with a dot: '{a}'.", W009: "The array literal notation [] is preferable.", W010: "The object literal notation {} is preferable.", W011: null, W012: null, W013: null, W014: "Bad line breaking before '{a}'.", W015: null, W016: "Unexpected use of '{a}'.", W017: "Bad operand.", W018: "Confusing use of '{a}'.", W019: "Use the isNaN function to compare with NaN.", W020: "Read only.", W021: "Reassignment of '{a}', which is is a {b}. " + "Use 'var' or 'let' to declare bindings that may change.", W022: "Do not assign to the exception parameter.", W023: "Expected an identifier in an assignment and instead saw a function invocation.", W024: "Expected an identifier and instead saw '{a}' (a reserved word).", W025: "Missing name in function declaration.", W026: "Inner functions should be listed at the top of the outer function.", W027: "Unreachable '{a}' after '{b}'.", W028: "Label '{a}' on {b} statement.", W030: "Expected an assignment or function call and instead saw an expression.", W031: "Do not use 'new' for side effects.", W032: "Unnecessary semicolon.", W033: "Missing semicolon.", W034: "Unnecessary directive \"{a}\".", W035: "Empty block.", W036: "Unexpected /*member '{a}'.", W037: "'{a}' is a statement label.", W038: "'{a}' used out of scope.", W039: "'{a}' is not allowed.", W040: "Possible strict violation.", W041: "Use '{a}' to compare with '{b}'.", W042: "Avoid EOL escaping.", W043: "Bad escaping of EOL. Use option multistr if needed.", W044: "Bad or unnecessary escaping.", /* TODO(caitp): remove W044 */ W045: "Bad number '{a}'.", W046: "Don't use extra leading zeros '{a}'.", W047: "A trailing decimal point can be confused with a dot: '{a}'.", W048: "Unexpected control character in regular expression.", W049: "Unexpected escaped character '{a}' in regular expression.", W050: "JavaScript URL.", W051: "Variables should not be deleted.", W052: "Unexpected '{a}'.", W053: "Do not use {a} as a constructor.", W054: "The Function constructor is a form of eval.", W055: "A constructor name should start with an uppercase letter.", W056: "Bad constructor.", W057: "Weird construction. Is 'new' necessary?", W058: "Missing '()' invoking a constructor.", W059: "Avoid arguments.{a}.", W060: "document.write can be a form of eval.", W061: "eval can be harmful.", W062: "Wrap an immediate function invocation in parens " + "to assist the reader in understanding that the expression " + "is the result of a function, and not the function itself.", W063: "Math is not a function.", W064: "Missing 'new' prefix when invoking a constructor.", W065: "Missing radix parameter.", W066: "Implied eval. Consider passing a function instead of a string.", W067: "Bad invocation.", W068: "Wrapping non-IIFE function literals in parens is unnecessary.", W069: "['{a}'] is better written in dot notation.", W070: "Extra comma. (it breaks older versions of IE)", W071: "This function has too many statements. ({a})", W072: "This function has too many parameters. ({a})", W073: "Blocks are nested too deeply. ({a})", W074: "This function's cyclomatic complexity is too high. ({a})", W075: "Duplicate {a} '{b}'.", W076: "Unexpected parameter '{a}' in get {b} function.", W077: "Expected a single parameter in set {a} function.", W078: "Setter is defined without getter.", W079: "Redefinition of '{a}'.", W080: "It's not necessary to initialize '{a}' to 'undefined'.", W081: null, W082: "Function declarations should not be placed in blocks. " + "Use a function expression or move the statement to the top of " + "the outer function.", W083: "Don't make functions within a loop.", W084: "Assignment in conditional expression", W085: "Don't use 'with'.", W086: "Expected a 'break' statement before '{a}'.", W087: "Forgotten 'debugger' statement?", W088: "Creating global 'for' variable. Should be 'for (var {a} ...'.", W089: "The body of a for in should be wrapped in an if statement to filter " + "unwanted properties from the prototype.", W090: "'{a}' is not a statement label.", W091: null, W093: "Did you mean to return a conditional instead of an assignment?", W094: "Unexpected comma.", W095: "Expected a string and instead saw {a}.", W096: "The '{a}' key may produce unexpected results.", W097: "Use the function form of \"use strict\".", W098: "'{a}' is defined but never used.", W099: null, W100: "This character may get silently deleted by one or more browsers.", W101: "Line is too long.", W102: null, W103: "The '{a}' property is deprecated.", W104: "'{a}' is available in ES{b} (use 'esversion: {b}') or Mozilla JS extensions (use moz).", W105: "Unexpected {a} in '{b}'.", W106: "Identifier '{a}' is not in camel case.", W107: "Script URL.", W108: "Strings must use doublequote.", W109: "Strings must use singlequote.", W110: "Mixed double and single quotes.", W112: "Unclosed string.", W113: "Control character in string: {a}.", W114: "Avoid {a}.", W115: "Octal literals are not allowed in strict mode.", W116: "Expected '{a}' and instead saw '{b}'.", W117: "'{a}' is not defined.", W118: "'{a}' is only available in Mozilla JavaScript extensions (use moz option).", W119: "'{a}' is only available in ES{b} (use 'esversion: {b}').", W120: "You might be leaking a variable ({a}) here.", W121: "Extending prototype of native object: '{a}'.", W122: "Invalid typeof value '{a}'", W123: "'{a}' is already defined in outer scope.", W124: "A generator function shall contain a yield statement.", W125: "This line contains non-breaking spaces: http://jshint.com/doc/options/#nonbsp", W126: "Unnecessary grouping operator.", W127: "Unexpected use of a comma operator.", W128: "Empty array elements require elision=true.", W129: "'{a}' is defined in a future version of JavaScript. Use a " + "different variable name to avoid migration issues.", W130: "Invalid element after rest element.", W131: "Invalid parameter after rest parameter.", W132: "`var` declarations are forbidden. Use `let` or `const` instead.", W133: "Invalid for-{a} loop left-hand-side: {b}.", W134: "The '{a}' option is only available when linting ECMAScript {b} code.", W135: "{a} may not be supported by non-browser environments.", W136: "'{a}' must be in function scope.", W137: "Empty destructuring.", W138: "Regular parameters should not come after default parameters." }; var info = { I001: "Comma warnings can be turned off with 'laxcomma'.", I002: null, I003: "ES5 option is now set per default" }; exports.errors = {}; exports.warnings = {}; exports.info = {}; _.each(errors, function(desc, code) { exports.errors[code] = { code: code, desc: desc }; }); _.each(warnings, function(desc, code) { exports.warnings[code] = { code: code, desc: desc }; }); _.each(info, function(desc, code) { exports.info[code] = { code: code, desc: desc }; }); },{"../lodash":"/node_modules/jshint/lodash.js"}],"/node_modules/jshint/src/name-stack.js":[function(_dereq_,module,exports){ "use strict"; function NameStack() { this._stack = []; } Object.defineProperty(NameStack.prototype, "length", { get: function() { return this._stack.length; } }); NameStack.prototype.push = function() { this._stack.push(null); }; NameStack.prototype.pop = function() { this._stack.pop(); }; NameStack.prototype.set = function(token) { this._stack[this.length - 1] = token; }; NameStack.prototype.infer = function() { var nameToken = this._stack[this.length - 1]; var prefix = ""; var type; if (!nameToken || nameToken.type === "class") { nameToken = this._stack[this.length - 2]; } if (!nameToken) { return "(empty)"; } type = nameToken.type; if (type !== "(string)" && type !== "(number)" && type !== "(identifier)" && type !== "default") { return "(expression)"; } if (nameToken.accessorType) { prefix = nameToken.accessorType + " "; } return prefix + nameToken.value; }; module.exports = NameStack; },{}],"/node_modules/jshint/src/options.js":[function(_dereq_,module,exports){ "use strict"; exports.bool = { enforcing: { bitwise : true, freeze : true, camelcase : true, curly : true, eqeqeq : true, futurehostile: true, notypeof : true, es3 : true, es5 : true, forin : true, funcscope : true, immed : true, iterator : true, newcap : true, noarg : true, nocomma : true, noempty : true, nonbsp : true, nonew : true, undef : true, singleGroups: false, varstmt: false, enforceall : false }, relaxing: { asi : true, multistr : true, debug : true, boss : true, evil : true, globalstrict: true, plusplus : true, proto : true, scripturl : true, sub : true, supernew : true, laxbreak : true, laxcomma : true, validthis : true, withstmt : true, moz : true, noyield : true, eqnull : true, lastsemic : true, loopfunc : true, expr : true, esnext : true, elision : true, }, environments: { mootools : true, couch : true, jasmine : true, jquery : true, node : true, qunit : true, rhino : true, shelljs : true, prototypejs : true, yui : true, mocha : true, module : true, wsh : true, worker : true, nonstandard : true, browser : true, browserify : true, devel : true, dojo : true, typed : true, phantom : true }, obsolete: { onecase : true, // if one case switch statements should be allowed regexp : true, // if the . should not be allowed in regexp literals regexdash : true // if unescaped first/last dash (-) inside brackets } }; exports.val = { maxlen : false, indent : false, maxerr : false, predef : false, globals : false, quotmark : false, scope : false, maxstatements: false, maxdepth : false, maxparams : false, maxcomplexity: false, shadow : false, strict : true, unused : true, latedef : false, ignore : false, // start/end ignoring lines of code, bypassing the lexer ignoreDelimiters: false, // array of start/end delimiters used to ignore esversion: 5 }; exports.inverted = { bitwise : true, forin : true, newcap : true, plusplus: true, regexp : true, undef : true, eqeqeq : true, strict : true }; exports.validNames = Object.keys(exports.val) .concat(Object.keys(exports.bool.relaxing)) .concat(Object.keys(exports.bool.enforcing)) .concat(Object.keys(exports.bool.obsolete)) .concat(Object.keys(exports.bool.environments)); exports.renamed = { eqeq : "eqeqeq", windows: "wsh", sloppy : "strict" }; exports.removed = { nomen: true, onevar: true, passfail: true, white: true, gcl: true, smarttabs: true, trailing: true }; exports.noenforceall = { varstmt: true, strict: true }; },{}],"/node_modules/jshint/src/reg.js":[function(_dereq_,module,exports){ "use strict"; exports.unsafeString = /@cc|<\/?|script|\]\s*\]|<\s*!|&lt/i; exports.unsafeChars = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; exports.needEsc = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; exports.needEscGlobal = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; exports.starSlash = /\*\//; exports.identifier = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/; exports.javascriptURL = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\s*:/i; exports.fallsThrough = /^\s*falls?\sthrough\s*$/; exports.maxlenException = /^(?:(?:\/\/|\/\*|\*) ?)?[^ ]+$/; },{}],"/node_modules/jshint/src/scope-manager.js":[function(_dereq_,module,exports){ "use strict"; var _ = _dereq_("../lodash"); var events = _dereq_("events"); var marker = {}; var scopeManager = function(state, predefined, exported, declared) { var _current; var _scopeStack = []; function _newScope(type) { _current = { "(labels)": Object.create(null), "(usages)": Object.create(null), "(breakLabels)": Object.create(null), "(parent)": _current, "(type)": type, "(params)": (type === "functionparams" || type === "catchparams") ? [] : null }; _scopeStack.push(_current); } _newScope("global"); _current["(predefined)"] = predefined; var _currentFunctBody = _current; // this is the block after the params = function var usedPredefinedAndGlobals = Object.create(null); var impliedGlobals = Object.create(null); var unuseds = []; var emitter = new events.EventEmitter(); function warning(code, token) { emitter.emit("warning", { code: code, token: token, data: _.slice(arguments, 2) }); } function error(code, token) { emitter.emit("warning", { code: code, token: token, data: _.slice(arguments, 2) }); } function _setupUsages(labelName) { if (!_current["(usages)"][labelName]) { _current["(usages)"][labelName] = { "(modified)": [], "(reassigned)": [], "(tokens)": [] }; } } var _getUnusedOption = function(unused_opt) { if (unused_opt === undefined) { unused_opt = state.option.unused; } if (unused_opt === true) { unused_opt = "last-param"; } return unused_opt; }; var _warnUnused = function(name, tkn, type, unused_opt) { var line = tkn.line; var chr = tkn.from; var raw_name = tkn.raw_text || name; unused_opt = _getUnusedOption(unused_opt); var warnable_types = { "vars": ["var"], "last-param": ["var", "param"], "strict": ["var", "param", "last-param"] }; if (unused_opt) { if (warnable_types[unused_opt] && warnable_types[unused_opt].indexOf(type) !== -1) { warning("W098", { line: line, from: chr }, raw_name); } } if (unused_opt || type === "var") { unuseds.push({ name: name, line: line, character: chr }); } }; function _checkForUnused() { if (_current["(type)"] === "functionparams") { _checkParams(); return; } var curentLabels = _current["(labels)"]; for (var labelName in curentLabels) { if (curentLabels[labelName]) { if (curentLabels[labelName]["(type)"] !== "exception" && curentLabels[labelName]["(unused)"]) { _warnUnused(labelName, curentLabels[labelName]["(token)"], "var"); } } } } function _checkParams() { var params = _current["(params)"]; if (!params) { return; } var param = params.pop(); var unused_opt; while (param) { var label = _current["(labels)"][param]; unused_opt = _getUnusedOption(state.funct["(unusedOption)"]); if (param === "undefined") return; if (label["(unused)"]) { _warnUnused(param, label["(token)"], "param", state.funct["(unusedOption)"]); } else if (unused_opt === "last-param") { return; } param = params.pop(); } } function _getLabel(labelName) { for (var i = _scopeStack.length - 1 ; i >= 0; --i) { var scopeLabels = _scopeStack[i]["(labels)"]; if (scopeLabels[labelName]) { return scopeLabels; } } } function usedSoFarInCurrentFunction(labelName) { for (var i = _scopeStack.length - 1; i >= 0; i--) { var current = _scopeStack[i]; if (current["(usages)"][labelName]) { return current["(usages)"][labelName]; } if (current === _currentFunctBody) { break; } } return false; } function _checkOuterShadow(labelName, token) { if (state.option.shadow !== "outer") { return; } var isGlobal = _currentFunctBody["(type)"] === "global", isNewFunction = _current["(type)"] === "functionparams"; var outsideCurrentFunction = !isGlobal; for (var i = 0; i < _scopeStack.length; i++) { var stackItem = _scopeStack[i]; if (!isNewFunction && _scopeStack[i + 1] === _currentFunctBody) { outsideCurrentFunction = false; } if (outsideCurrentFunction && stackItem["(labels)"][labelName]) { warning("W123", token, labelName); } if (stackItem["(breakLabels)"][labelName]) { warning("W123", token, labelName); } } } function _latedefWarning(type, labelName, token) { if (state.option.latedef) { if ((state.option.latedef === true && type === "function") || type !== "function") { warning("W003", token, labelName); } } } var scopeManagerInst = { on: function(names, listener) { names.split(" ").forEach(function(name) { emitter.on(name, listener); }); }, isPredefined: function(labelName) { return !this.has(labelName) && _.has(_scopeStack[0]["(predefined)"], labelName); }, stack: function(type) { var previousScope = _current; _newScope(type); if (!type && previousScope["(type)"] === "functionparams") { _current["(isFuncBody)"] = true; _current["(context)"] = _currentFunctBody; _currentFunctBody = _current; } }, unstack: function() { var subScope = _scopeStack.length > 1 ? _scopeStack[_scopeStack.length - 2] : null; var isUnstackingFunctionBody = _current === _currentFunctBody, isUnstackingFunctionParams = _current["(type)"] === "functionparams", isUnstackingFunctionOuter = _current["(type)"] === "functionouter"; var i, j; var currentUsages = _current["(usages)"]; var currentLabels = _current["(labels)"]; var usedLabelNameList = Object.keys(currentUsages); if (currentUsages.__proto__ && usedLabelNameList.indexOf("__proto__") === -1) { usedLabelNameList.push("__proto__"); } for (i = 0; i < usedLabelNameList.length; i++) { var usedLabelName = usedLabelNameList[i]; var usage = currentUsages[usedLabelName]; var usedLabel = currentLabels[usedLabelName]; if (usedLabel) { var usedLabelType = usedLabel["(type)"]; if (usedLabel["(useOutsideOfScope)"] && !state.option.funcscope) { var usedTokens = usage["(tokens)"]; if (usedTokens) { for (j = 0; j < usedTokens.length; j++) { if (usedLabel["(function)"] === usedTokens[j]["(function)"]) { error("W038", usedTokens[j], usedLabelName); } } } } _current["(labels)"][usedLabelName]["(unused)"] = false; if (usedLabelType === "const" && usage["(modified)"]) { for (j = 0; j < usage["(modified)"].length; j++) { error("E013", usage["(modified)"][j], usedLabelName); } } if ((usedLabelType === "function" || usedLabelType === "class") && usage["(reassigned)"]) { for (j = 0; j < usage["(reassigned)"].length; j++) { error("W021", usage["(reassigned)"][j], usedLabelName, usedLabelType); } } continue; } if (isUnstackingFunctionOuter) { state.funct["(isCapturing)"] = true; } if (subScope) { if (!subScope["(usages)"][usedLabelName]) { subScope["(usages)"][usedLabelName] = usage; if (isUnstackingFunctionBody) { subScope["(usages)"][usedLabelName]["(onlyUsedSubFunction)"] = true; } } else { var subScopeUsage = subScope["(usages)"][usedLabelName]; subScopeUsage["(modified)"] = subScopeUsage["(modified)"].concat(usage["(modified)"]); subScopeUsage["(tokens)"] = subScopeUsage["(tokens)"].concat(usage["(tokens)"]); subScopeUsage["(reassigned)"] = subScopeUsage["(reassigned)"].concat(usage["(reassigned)"]); subScopeUsage["(onlyUsedSubFunction)"] = false; } } else { if (typeof _current["(predefined)"][usedLabelName] === "boolean") { delete declared[usedLabelName]; usedPredefinedAndGlobals[usedLabelName] = marker; if (_current["(predefined)"][usedLabelName] === false && usage["(reassigned)"]) { for (j = 0; j < usage["(reassigned)"].length; j++) { warning("W020", usage["(reassigned)"][j]); } } } else { if (usage["(tokens)"]) { for (j = 0; j < usage["(tokens)"].length; j++) { var undefinedToken = usage["(tokens)"][j]; if (!undefinedToken.forgiveUndef) { if (state.option.undef && !undefinedToken.ignoreUndef) { warning("W117", undefinedToken, usedLabelName); } if (impliedGlobals[usedLabelName]) { impliedGlobals[usedLabelName].line.push(undefinedToken.line); } else { impliedGlobals[usedLabelName] = { name: usedLabelName, line: [undefinedToken.line] }; } } } } } } } if (!subScope) { Object.keys(declared) .forEach(function(labelNotUsed) { _warnUnused(labelNotUsed, declared[labelNotUsed], "var"); }); } if (subScope && !isUnstackingFunctionBody && !isUnstackingFunctionParams && !isUnstackingFunctionOuter) { var labelNames = Object.keys(currentLabels); for (i = 0; i < labelNames.length; i++) { var defLabelName = labelNames[i]; if (!currentLabels[defLabelName]["(blockscoped)"] && currentLabels[defLabelName]["(type)"] !== "exception" && !this.funct.has(defLabelName, { excludeCurrent: true })) { subScope["(labels)"][defLabelName] = currentLabels[defLabelName]; if (_currentFunctBody["(type)"] !== "global") { subScope["(labels)"][defLabelName]["(useOutsideOfScope)"] = true; } delete currentLabels[defLabelName]; } } } _checkForUnused(); _scopeStack.pop(); if (isUnstackingFunctionBody) { _currentFunctBody = _scopeStack[_.findLastIndex(_scopeStack, function(scope) { return scope["(isFuncBody)"] || scope["(type)"] === "global"; })]; } _current = subScope; }, addParam: function(labelName, token, type) { type = type || "param"; if (type === "exception") { var previouslyDefinedLabelType = this.funct.labeltype(labelName); if (previouslyDefinedLabelType && previouslyDefinedLabelType !== "exception") { if (!state.option.node) { warning("W002", state.tokens.next, labelName); } } } if (_.has(_current["(labels)"], labelName)) { _current["(labels)"][labelName].duplicated = true; } else { _checkOuterShadow(labelName, token, type); _current["(labels)"][labelName] = { "(type)" : type, "(token)": token, "(unused)": true }; _current["(params)"].push(labelName); } if (_.has(_current["(usages)"], labelName)) { var usage = _current["(usages)"][labelName]; if (usage["(onlyUsedSubFunction)"]) { _latedefWarning(type, labelName, token); } else { warning("E056", token, labelName, type); } } }, validateParams: function() { if (_currentFunctBody["(type)"] === "global") { return; } var isStrict = state.isStrict(); var currentFunctParamScope = _currentFunctBody["(parent)"]; if (!currentFunctParamScope["(params)"]) { return; } currentFunctParamScope["(params)"].forEach(function(labelName) { var label = currentFunctParamScope["(labels)"][labelName]; if (label && label.duplicated) { if (isStrict) { warning("E011", label["(token)"], labelName); } else if (state.option.shadow !== true) { warning("W004", label["(token)"], labelName); } } }); }, getUsedOrDefinedGlobals: function() { var list = Object.keys(usedPredefinedAndGlobals); if (usedPredefinedAndGlobals.__proto__ === marker && list.indexOf("__proto__") === -1) { list.push("__proto__"); } return list; }, getImpliedGlobals: function() { var values = _.values(impliedGlobals); var hasProto = false; if (impliedGlobals.__proto__) { hasProto = values.some(function(value) { return value.name === "__proto__"; }); if (!hasProto) { values.push(impliedGlobals.__proto__); } } return values; }, getUnuseds: function() { return unuseds; }, has: function(labelName) { return Boolean(_getLabel(labelName)); }, labeltype: function(labelName) { var scopeLabels = _getLabel(labelName); if (scopeLabels) { return scopeLabels[labelName]["(type)"]; } return null; }, addExported: function(labelName) { var globalLabels = _scopeStack[0]["(labels)"]; if (_.has(declared, labelName)) { delete declared[labelName]; } else if (_.has(globalLabels, labelName)) { globalLabels[labelName]["(unused)"] = false; } else { for (var i = 1; i < _scopeStack.length; i++) { var scope = _scopeStack[i]; if (!scope["(type)"]) { if (_.has(scope["(labels)"], labelName) && !scope["(labels)"][labelName]["(blockscoped)"]) { scope["(labels)"][labelName]["(unused)"] = false; return; } } else { break; } } exported[labelName] = true; } }, setExported: function(labelName, token) { this.block.use(labelName, token); }, addlabel: function(labelName, opts) { var type = opts.type; var token = opts.token; var isblockscoped = type === "let" || type === "const" || type === "class"; var isexported = (isblockscoped ? _current : _currentFunctBody)["(type)"] === "global" && _.has(exported, labelName); _checkOuterShadow(labelName, token, type); if (isblockscoped) { var declaredInCurrentScope = _current["(labels)"][labelName]; if (!declaredInCurrentScope && _current === _currentFunctBody && _current["(type)"] !== "global") { declaredInCurrentScope = !!_currentFunctBody["(parent)"]["(labels)"][labelName]; } if (!declaredInCurrentScope && _current["(usages)"][labelName]) { var usage = _current["(usages)"][labelName]; if (usage["(onlyUsedSubFunction)"]) { _latedefWarning(type, labelName, token); } else { warning("E056", token, labelName, type); } } if (declaredInCurrentScope) { warning("E011", token, labelName); } else if (state.option.shadow === "outer") { if (scopeManagerInst.funct.has(labelName)) { warning("W004", token, labelName); } } scopeManagerInst.block.add(labelName, type, token, !isexported); } else { var declaredInCurrentFunctionScope = scopeManagerInst.funct.has(labelName); if (!declaredInCurrentFunctionScope && usedSoFarInCurrentFunction(labelName)) { _latedefWarning(type, labelName, token); } if (scopeManagerInst.funct.has(labelName, { onlyBlockscoped: true })) { warning("E011", token, labelName); } else if (state.option.shadow !== true) { if (declaredInCurrentFunctionScope && labelName !== "__proto__") { if (_currentFunctBody["(type)"] !== "global") { warning("W004", token, labelName); } } } scopeManagerInst.funct.add(labelName, type, token, !isexported); if (_currentFunctBody["(type)"] === "global") { usedPredefinedAndGlobals[labelName] = marker; } } }, funct: { labeltype: function(labelName, options) { var onlyBlockscoped = options && options.onlyBlockscoped; var excludeParams = options && options.excludeParams; var currentScopeIndex = _scopeStack.length - (options && options.excludeCurrent ? 2 : 1); for (var i = currentScopeIndex; i >= 0; i--) { var current = _scopeStack[i]; if (current["(labels)"][labelName] && (!onlyBlockscoped || current["(labels)"][labelName]["(blockscoped)"])) { return current["(labels)"][labelName]["(type)"]; } var scopeCheck = excludeParams ? _scopeStack[ i - 1 ] : current; if (scopeCheck && scopeCheck["(type)"] === "functionparams") { return null; } } return null; }, hasBreakLabel: function(labelName) { for (var i = _scopeStack.length - 1; i >= 0; i--) { var current = _scopeStack[i]; if (current["(breakLabels)"][labelName]) { return true; } if (current["(type)"] === "functionparams") { return false; } } return false; }, has: function(labelName, options) { return Boolean(this.labeltype(labelName, options)); }, add: function(labelName, type, tok, unused) { _current["(labels)"][labelName] = { "(type)" : type, "(token)": tok, "(blockscoped)": false, "(function)": _currentFunctBody, "(unused)": unused }; } }, block: { isGlobal: function() { return _current["(type)"] === "global"; }, use: function(labelName, token) { var paramScope = _currentFunctBody["(parent)"]; if (paramScope && paramScope["(labels)"][labelName] && paramScope["(labels)"][labelName]["(type)"] === "param") { if (!scopeManagerInst.funct.has(labelName, { excludeParams: true, onlyBlockscoped: true })) { paramScope["(labels)"][labelName]["(unused)"] = false; } } if (token && (state.ignored.W117 || state.option.undef === false)) { token.ignoreUndef = true; } _setupUsages(labelName); if (token) { token["(function)"] = _currentFunctBody; _current["(usages)"][labelName]["(tokens)"].push(token); } }, reassign: function(labelName, token) { this.modify(labelName, token); _current["(usages)"][labelName]["(reassigned)"].push(token); }, modify: function(labelName, token) { _setupUsages(labelName); _current["(usages)"][labelName]["(modified)"].push(token); }, add: function(labelName, type, tok, unused) { _current["(labels)"][labelName] = { "(type)" : type, "(token)": tok, "(blockscoped)": true, "(unused)": unused }; }, addBreakLabel: function(labelName, opts) { var token = opts.token; if (scopeManagerInst.funct.hasBreakLabel(labelName)) { warning("E011", token, labelName); } else if (state.option.shadow === "outer") { if (scopeManagerInst.funct.has(labelName)) { warning("W004", token, labelName); } else { _checkOuterShadow(labelName, token); } } _current["(breakLabels)"][labelName] = token; } } }; return scopeManagerInst; }; module.exports = scopeManager; },{"../lodash":"/node_modules/jshint/lodash.js","events":"/node_modules/browserify/node_modules/events/events.js"}],"/node_modules/jshint/src/state.js":[function(_dereq_,module,exports){ "use strict"; var NameStack = _dereq_("./name-stack.js"); var state = { syntax: {}, isStrict: function() { return this.directive["use strict"] || this.inClassBody || this.option.module || this.option.strict === "implied"; }, inMoz: function() { return this.option.moz; }, inES6: function() { return this.option.moz || this.option.esversion >= 6; }, inES5: function(strict) { if (strict) { return (!this.option.esversion || this.option.esversion === 5) && !this.option.moz; } return !this.option.esversion || this.option.esversion >= 5 || this.option.moz; }, reset: function() { this.tokens = { prev: null, next: null, curr: null }; this.option = {}; this.funct = null; this.ignored = {}; this.directive = {}; this.jsonMode = false; this.jsonWarnings = []; this.lines = []; this.tab = ""; this.cache = {}; // Node.JS doesn't have Map. Sniff. this.ignoredLines = {}; this.forinifcheckneeded = false; this.nameStack = new NameStack(); this.inClassBody = false; } }; exports.state = state; },{"./name-stack.js":"/node_modules/jshint/src/name-stack.js"}],"/node_modules/jshint/src/style.js":[function(_dereq_,module,exports){ "use strict"; exports.register = function(linter) { linter.on("Identifier", function style_scanProto(data) { if (linter.getOption("proto")) { return; } if (data.name === "__proto__") { linter.warn("W103", { line: data.line, char: data.char, data: [ data.name, "6" ] }); } }); linter.on("Identifier", function style_scanIterator(data) { if (linter.getOption("iterator")) { return; } if (data.name === "__iterator__") { linter.warn("W103", { line: data.line, char: data.char, data: [ data.name ] }); } }); linter.on("Identifier", function style_scanCamelCase(data) { if (!linter.getOption("camelcase")) { return; } if (data.name.replace(/^_+|_+$/g, "").indexOf("_") > -1 && !data.name.match(/^[A-Z0-9_]*$/)) { linter.warn("W106", { line: data.line, char: data.from, data: [ data.name ] }); } }); linter.on("String", function style_scanQuotes(data) { var quotmark = linter.getOption("quotmark"); var code; if (!quotmark) { return; } if (quotmark === "single" && data.quote !== "'") { code = "W109"; } if (quotmark === "double" && data.quote !== "\"") { code = "W108"; } if (quotmark === true) { if (!linter.getCache("quotmark")) { linter.setCache("quotmark", data.quote); } if (linter.getCache("quotmark") !== data.quote) { code = "W110"; } } if (code) { linter.warn(code, { line: data.line, char: data.char, }); } }); linter.on("Number", function style_scanNumbers(data) { if (data.value.charAt(0) === ".") { linter.warn("W008", { line: data.line, char: data.char, data: [ data.value ] }); } if (data.value.substr(data.value.length - 1) === ".") { linter.warn("W047", { line: data.line, char: data.char, data: [ data.value ] }); } if (/^00+/.test(data.value)) { linter.warn("W046", { line: data.line, char: data.char, data: [ data.value ] }); } }); linter.on("String", function style_scanJavaScriptURLs(data) { var re = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\s*:/i; if (linter.getOption("scripturl")) { return; } if (re.test(data.value)) { linter.warn("W107", { line: data.line, char: data.char }); } }); }; },{}],"/node_modules/jshint/src/vars.js":[function(_dereq_,module,exports){ "use strict"; exports.reservedVars = { arguments : false, NaN : false }; exports.ecmaIdentifiers = { 3: { Array : false, Boolean : false, Date : false, decodeURI : false, decodeURIComponent : false, encodeURI : false, encodeURIComponent : false, Error : false, "eval" : false, EvalError : false, Function : false, hasOwnProperty : false, isFinite : false, isNaN : false, Math : false, Number : false, Object : false, parseInt : false, parseFloat : false, RangeError : false, ReferenceError : false, RegExp : false, String : false, SyntaxError : false, TypeError : false, URIError : false }, 5: { JSON : false }, 6: { Map : false, Promise : false, Proxy : false, Reflect : false, Set : false, Symbol : false, WeakMap : false, WeakSet : false } }; exports.browser = { Audio : false, Blob : false, addEventListener : false, applicationCache : false, atob : false, blur : false, btoa : false, cancelAnimationFrame : false, CanvasGradient : false, CanvasPattern : false, CanvasRenderingContext2D: false, CSS : false, clearInterval : false, clearTimeout : false, close : false, closed : false, Comment : false, CustomEvent : false, DOMParser : false, defaultStatus : false, Document : false, document : false, DocumentFragment : false, Element : false, ElementTimeControl : false, Event : false, event : false, fetch : false, FileReader : false, FormData : false, focus : false, frames : false, getComputedStyle : false, HTMLElement : false, HTMLAnchorElement : false, HTMLBaseElement : false, HTMLBlockquoteElement: false, HTMLBodyElement : false, HTMLBRElement : false, HTMLButtonElement : false, HTMLCanvasElement : false, HTMLCollection : false, HTMLDirectoryElement : false, HTMLDivElement : false, HTMLDListElement : false, HTMLFieldSetElement : false, HTMLFontElement : false, HTMLFormElement : false, HTMLFrameElement : false, HTMLFrameSetElement : false, HTMLHeadElement : false, HTMLHeadingElement : false, HTMLHRElement : false, HTMLHtmlElement : false, HTMLIFrameElement : false, HTMLImageElement : false, HTMLInputElement : false, HTMLIsIndexElement : false, HTMLLabelElement : false, HTMLLayerElement : false, HTMLLegendElement : false, HTMLLIElement : false, HTMLLinkElement : false, HTMLMapElement : false, HTMLMenuElement : false, HTMLMetaElement : false, HTMLModElement : false, HTMLObjectElement : false, HTMLOListElement : false, HTMLOptGroupElement : false, HTMLOptionElement : false, HTMLParagraphElement : false, HTMLParamElement : false, HTMLPreElement : false, HTMLQuoteElement : false, HTMLScriptElement : false, HTMLSelectElement : false, HTMLStyleElement : false, HTMLTableCaptionElement: false, HTMLTableCellElement : false, HTMLTableColElement : false, HTMLTableElement : false, HTMLTableRowElement : false, HTMLTableSectionElement: false, HTMLTemplateElement : false, HTMLTextAreaElement : false, HTMLTitleElement : false, HTMLUListElement : false, HTMLVideoElement : false, history : false, Image : false, Intl : false, length : false, localStorage : false, location : false, matchMedia : false, MessageChannel : false, MessageEvent : false, MessagePort : false, MouseEvent : false, moveBy : false, moveTo : false, MutationObserver : false, name : false, Node : false, NodeFilter : false, NodeList : false, Notification : false, navigator : false, onbeforeunload : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : false, openDatabase : false, opener : false, Option : false, parent : false, performance : false, print : false, Range : false, requestAnimationFrame : false, removeEventListener : false, resizeBy : false, resizeTo : false, screen : false, scroll : false, scrollBy : false, scrollTo : false, sessionStorage : false, setInterval : false, setTimeout : false, SharedWorker : false, status : false, SVGAElement : false, SVGAltGlyphDefElement: false, SVGAltGlyphElement : false, SVGAltGlyphItemElement: false, SVGAngle : false, SVGAnimateColorElement: false, SVGAnimateElement : false, SVGAnimateMotionElement: false, SVGAnimateTransformElement: false, SVGAnimatedAngle : false, SVGAnimatedBoolean : false, SVGAnimatedEnumeration: false, SVGAnimatedInteger : false, SVGAnimatedLength : false, SVGAnimatedLengthList: false, SVGAnimatedNumber : false, SVGAnimatedNumberList: false, SVGAnimatedPathData : false, SVGAnimatedPoints : false, SVGAnimatedPreserveAspectRatio: false, SVGAnimatedRect : false, SVGAnimatedString : false, SVGAnimatedTransformList: false, SVGAnimationElement : false, SVGCSSRule : false, SVGCircleElement : false, SVGClipPathElement : false, SVGColor : false, SVGColorProfileElement: false, SVGColorProfileRule : false, SVGComponentTransferFunctionElement: false, SVGCursorElement : false, SVGDefsElement : false, SVGDescElement : false, SVGDocument : false, SVGElement : false, SVGElementInstance : false, SVGElementInstanceList: false, SVGEllipseElement : false, SVGExternalResourcesRequired: false, SVGFEBlendElement : false, SVGFEColorMatrixElement: false, SVGFEComponentTransferElement: false, SVGFECompositeElement: false, SVGFEConvolveMatrixElement: false, SVGFEDiffuseLightingElement: false, SVGFEDisplacementMapElement: false, SVGFEDistantLightElement: false, SVGFEFloodElement : false, SVGFEFuncAElement : false, SVGFEFuncBElement : false, SVGFEFuncGElement : false, SVGFEFuncRElement : false, SVGFEGaussianBlurElement: false, SVGFEImageElement : false, SVGFEMergeElement : false, SVGFEMergeNodeElement: false, SVGFEMorphologyElement: false, SVGFEOffsetElement : false, SVGFEPointLightElement: false, SVGFESpecularLightingElement: false, SVGFESpotLightElement: false, SVGFETileElement : false, SVGFETurbulenceElement: false, SVGFilterElement : false, SVGFilterPrimitiveStandardAttributes: false, SVGFitToViewBox : false, SVGFontElement : false, SVGFontFaceElement : false, SVGFontFaceFormatElement: false, SVGFontFaceNameElement: false, SVGFontFaceSrcElement: false, SVGFontFaceUriElement: false, SVGForeignObjectElement: false, SVGGElement : false, SVGGlyphElement : false, SVGGlyphRefElement : false, SVGGradientElement : false, SVGHKernElement : false, SVGICCColor : false, SVGImageElement : false, SVGLangSpace : false, SVGLength : false, SVGLengthList : false, SVGLineElement : false, SVGLinearGradientElement: false, SVGLocatable : false, SVGMPathElement : false, SVGMarkerElement : false, SVGMaskElement : false, SVGMatrix : false, SVGMetadataElement : false, SVGMissingGlyphElement: false, SVGNumber : false, SVGNumberList : false, SVGPaint : false, SVGPathElement : false, SVGPathSeg : false, SVGPathSegArcAbs : false, SVGPathSegArcRel : false, SVGPathSegClosePath : false, SVGPathSegCurvetoCubicAbs: false, SVGPathSegCurvetoCubicRel: false, SVGPathSegCurvetoCubicSmoothAbs: false, SVGPathSegCurvetoCubicSmoothRel: false, SVGPathSegCurvetoQuadraticAbs: false, SVGPathSegCurvetoQuadraticRel: false, SVGPathSegCurvetoQuadraticSmoothAbs: false, SVGPathSegCurvetoQuadraticSmoothRel: false, SVGPathSegLinetoAbs : false, SVGPathSegLinetoHorizontalAbs: false, SVGPathSegLinetoHorizontalRel: false, SVGPathSegLinetoRel : false, SVGPathSegLinetoVerticalAbs: false, SVGPathSegLinetoVerticalRel: false, SVGPathSegList : false, SVGPathSegMovetoAbs : false, SVGPathSegMovetoRel : false, SVGPatternElement : false, SVGPoint : false, SVGPointList : false, SVGPolygonElement : false, SVGPolylineElement : false, SVGPreserveAspectRatio: false, SVGRadialGradientElement: false, SVGRect : false, SVGRectElement : false, SVGRenderingIntent : false, SVGSVGElement : false, SVGScriptElement : false, SVGSetElement : false, SVGStopElement : false, SVGStringList : false, SVGStylable : false, SVGStyleElement : false, SVGSwitchElement : false, SVGSymbolElement : false, SVGTRefElement : false, SVGTSpanElement : false, SVGTests : false, SVGTextContentElement: false, SVGTextElement : false, SVGTextPathElement : false, SVGTextPositioningElement: false, SVGTitleElement : false, SVGTransform : false, SVGTransformList : false, SVGTransformable : false, SVGURIReference : false, SVGUnitTypes : false, SVGUseElement : false, SVGVKernElement : false, SVGViewElement : false, SVGViewSpec : false, SVGZoomAndPan : false, Text : false, TextDecoder : false, TextEncoder : false, TimeEvent : false, top : false, URL : false, WebGLActiveInfo : false, WebGLBuffer : false, WebGLContextEvent : false, WebGLFramebuffer : false, WebGLProgram : false, WebGLRenderbuffer : false, WebGLRenderingContext: false, WebGLShader : false, WebGLShaderPrecisionFormat: false, WebGLTexture : false, WebGLUniformLocation : false, WebSocket : false, window : false, Window : false, Worker : false, XDomainRequest : false, XMLHttpRequest : false, XMLSerializer : false, XPathEvaluator : false, XPathException : false, XPathExpression : false, XPathNamespace : false, XPathNSResolver : false, XPathResult : false }; exports.devel = { alert : false, confirm: false, console: false, Debug : false, opera : false, prompt : false }; exports.worker = { importScripts : true, postMessage : true, self : true, FileReaderSync : true }; exports.nonstandard = { escape : false, unescape: false }; exports.couch = { "require" : false, respond : false, getRow : false, emit : false, send : false, start : false, sum : false, log : false, exports : false, module : false, provides : false }; exports.node = { __filename : false, __dirname : false, GLOBAL : false, global : false, module : false, require : false, Buffer : true, console : true, exports : true, process : true, setTimeout : true, clearTimeout : true, setInterval : true, clearInterval : true, setImmediate : true, // v0.9.1+ clearImmediate: true // v0.9.1+ }; exports.browserify = { __filename : false, __dirname : false, global : false, module : false, require : false, Buffer : true, exports : true, process : true }; exports.phantom = { phantom : true, require : true, WebPage : true, console : true, // in examples, but undocumented exports : true // v1.7+ }; exports.qunit = { asyncTest : false, deepEqual : false, equal : false, expect : false, module : false, notDeepEqual : false, notEqual : false, notPropEqual : false, notStrictEqual : false, ok : false, propEqual : false, QUnit : false, raises : false, start : false, stop : false, strictEqual : false, test : false, "throws" : false }; exports.rhino = { defineClass : false, deserialize : false, gc : false, help : false, importClass : false, importPackage: false, "java" : false, load : false, loadClass : false, Packages : false, print : false, quit : false, readFile : false, readUrl : false, runCommand : false, seal : false, serialize : false, spawn : false, sync : false, toint32 : false, version : false }; exports.shelljs = { target : false, echo : false, exit : false, cd : false, pwd : false, ls : false, find : false, cp : false, rm : false, mv : false, mkdir : false, test : false, cat : false, sed : false, grep : false, which : false, dirs : false, pushd : false, popd : false, env : false, exec : false, chmod : false, config : false, error : false, tempdir : false }; exports.typed = { ArrayBuffer : false, ArrayBufferView : false, DataView : false, Float32Array : false, Float64Array : false, Int16Array : false, Int32Array : false, Int8Array : false, Uint16Array : false, Uint32Array : false, Uint8Array : false, Uint8ClampedArray : false }; exports.wsh = { ActiveXObject : true, Enumerator : true, GetObject : true, ScriptEngine : true, ScriptEngineBuildVersion : true, ScriptEngineMajorVersion : true, ScriptEngineMinorVersion : true, VBArray : true, WSH : true, WScript : true, XDomainRequest : true }; exports.dojo = { dojo : false, dijit : false, dojox : false, define : false, "require": false }; exports.jquery = { "$" : false, jQuery : false }; exports.mootools = { "$" : false, "$$" : false, Asset : false, Browser : false, Chain : false, Class : false, Color : false, Cookie : false, Core : false, Document : false, DomReady : false, DOMEvent : false, DOMReady : false, Drag : false, Element : false, Elements : false, Event : false, Events : false, Fx : false, Group : false, Hash : false, HtmlTable : false, IFrame : false, IframeShim : false, InputValidator: false, instanceOf : false, Keyboard : false, Locale : false, Mask : false, MooTools : false, Native : false, Options : false, OverText : false, Request : false, Scroller : false, Slick : false, Slider : false, Sortables : false, Spinner : false, Swiff : false, Tips : false, Type : false, typeOf : false, URI : false, Window : false }; exports.prototypejs = { "$" : false, "$$" : false, "$A" : false, "$F" : false, "$H" : false, "$R" : false, "$break" : false, "$continue" : false, "$w" : false, Abstract : false, Ajax : false, Class : false, Enumerable : false, Element : false, Event : false, Field : false, Form : false, Hash : false, Insertion : false, ObjectRange : false, PeriodicalExecuter: false, Position : false, Prototype : false, Selector : false, Template : false, Toggle : false, Try : false, Autocompleter : false, Builder : false, Control : false, Draggable : false, Draggables : false, Droppables : false, Effect : false, Sortable : false, SortableObserver : false, Sound : false, Scriptaculous : false }; exports.yui = { YUI : false, Y : false, YUI_config: false }; exports.mocha = { mocha : false, describe : false, xdescribe : false, it : false, xit : false, context : false, xcontext : false, before : false, after : false, beforeEach : false, afterEach : false, suite : false, test : false, setup : false, teardown : false, suiteSetup : false, suiteTeardown : false }; exports.jasmine = { jasmine : false, describe : false, xdescribe : false, it : false, xit : false, beforeEach : false, afterEach : false, setFixtures : false, loadFixtures: false, spyOn : false, expect : false, runs : false, waitsFor : false, waits : false, beforeAll : false, afterAll : false, fail : false, fdescribe : false, fit : false, pending : false }; },{}]},{},["/node_modules/jshint/src/jshint.js"]); }); ace.define("ace/mode/javascript_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/javascript/jshint"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var lint = require("./javascript/jshint").JSHINT; function startRegex(arr) { return RegExp("^(" + arr.join("|") + ")"); } var disabledWarningsRe = startRegex([ "Bad for in variable '(.+)'.", 'Missing "use strict"' ]); var errorsRe = startRegex([ "Unexpected", "Expected ", "Confusing (plus|minus)", "\\{a\\} unterminated regular expression", "Unclosed ", "Unmatched ", "Unbegun comment", "Bad invocation", "Missing space after", "Missing operator at" ]); var infoRe = startRegex([ "Expected an assignment", "Bad escapement of EOL", "Unexpected comma", "Unexpected space", "Missing radix parameter.", "A leading decimal point can", "\\['{a}'\\] is better written in dot notation.", "'{a}' used out of scope" ]); var JavaScriptWorker = exports.JavaScriptWorker = function(sender) { Mirror.call(this, sender); this.setTimeout(500); this.setOptions(); }; oop.inherits(JavaScriptWorker, Mirror); (function() { this.setOptions = function(options) { this.options = options || { esnext: true, moz: true, devel: true, browser: true, node: true, laxcomma: true, laxbreak: true, lastsemic: true, onevar: false, passfail: false, maxerr: 100, expr: true, multistr: true, globalstrict: true }; this.doc.getValue() && this.deferredUpdate.schedule(100); }; this.changeOptions = function(newOptions) { oop.mixin(this.options, newOptions); this.doc.getValue() && this.deferredUpdate.schedule(100); }; this.isValidJS = function(str) { try { eval("throw 0;" + str); } catch(e) { if (e === 0) return true; } return false }; this.onUpdate = function() { var value = this.doc.getValue(); value = value.replace(/^#!.*\n/, "\n"); if (!value) return this.sender.emit("annotate", []); var errors = []; var maxErrorLevel = this.isValidJS(value) ? "warning" : "error"; lint(value, this.options, this.options.globals); var results = lint.errors; var errorAdded = false for (var i = 0; i < results.length; i++) { var error = results[i]; if (!error) continue; var raw = error.raw; var type = "warning"; if (raw == "Missing semicolon.") { var str = error.evidence.substr(error.character); str = str.charAt(str.search(/\S/)); if (maxErrorLevel == "error" && str && /[\w\d{(['"]/.test(str)) { error.reason = 'Missing ";" before statement'; type = "error"; } else { type = "info"; } } else if (disabledWarningsRe.test(raw)) { continue; } else if (infoRe.test(raw)) { type = "info" } else if (errorsRe.test(raw)) { errorAdded = true; type = maxErrorLevel; } else if (raw == "'{a}' is not defined.") { type = "warning"; } else if (raw == "'{a}' is defined but never used.") { type = "info"; } errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: type, raw: raw }); if (errorAdded) { } } this.sender.emit("annotate", errors); }; }).call(JavaScriptWorker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace/mode-markdown.js
2,819
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ { token : "comment", regex : "\\/\\/", next : "line_comment" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "keyword.operator", regex : /--|\+\+|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/", next : "line_comment_regex_allowed" }, { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); return "paren"; } if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var getWrapped = function(selection, selected, opening, closing) { var rowDiff = selection.end.row - selection.start.row; return { text: opening + selected + closing, selection: [ 0, selection.start.column + 1, rowDiff, selection.end.column + (rowDiff ? 0 : 1) ] }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '{', '}'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '(', ')'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '[', ']'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, quote, quote); } else if (!selected) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); var rightChar = line.substring(cursor.column, cursor.column + 1); var token = session.getTokenAt(cursor.row, cursor.column); var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); if (leftChar == "\\" && token && /escape/.test(token.type)) return null; var stringBefore = token && /string|escape/.test(token.type); var stringAfter = !rightToken || /string|escape/.test(rightToken.type); var pair; if (rightChar == quote) { pair = stringBefore !== stringAfter; } else { if (stringBefore && !stringAfter) return null; // wrap string with different quote if (stringBefore && stringAfter) return null; // do not pair quotes inside strings var wordRe = session.$mode.tokenRe; wordRe.lastIndex = 0; var isWordBefore = wordRe.test(leftChar); wordRe.lastIndex = 0; var isWordAfter = wordRe.test(leftChar); if (isWordBefore || isWordAfter) return null; // before or after alphanumeric if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) return null; // there is rightChar and it isn't closing pair = true; } return { text: pair ? quote + quote : "", selection: [1,1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction", }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getCursorPosition(); var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.HighlightRules = XmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.voidElements = lang.arrayToMap([]); this.blockComment = {start: "<!--", end: "-->"}; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/xml_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/xml"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ], }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(JavaScriptHighlightRules, "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": ["manifest"], "head": [], "title": [], "base": ["href", "target"], "link": ["href", "hreflang", "rel", "media", "type", "sizes"], "meta": ["http-equiv", "name", "content", "charset"], "style": ["type", "media", "scoped"], "script": ["charset", "type", "src", "defer", "async"], "noscript": ["href"], "body": ["onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onmessage", "onoffline", "onpopstate", "onredo", "onresize", "onstorage", "onundo", "onunload"], "section": [], "nav": [], "article": ["pubdate"], "aside": [], "h1": [], "h2": [], "h3": [], "h4": [], "h5": [], "h6": [], "header": [], "footer": [], "address": [], "main": [], "p": [], "hr": [], "pre": [], "blockquote": ["cite"], "ol": ["start", "reversed"], "ul": [], "li": ["value"], "dl": [], "dt": [], "dd": [], "figure": [], "figcaption": [], "div": [], "a": ["href", "target", "ping", "rel", "media", "hreflang", "type"], "em": [], "strong": [], "small": [], "s": [], "cite": [], "q": ["cite"], "dfn": [], "abbr": [], "data": [], "time": ["datetime"], "code": [], "var": [], "samp": [], "kbd": [], "sub": [], "sup": [], "i": [], "b": [], "u": [], "mark": [], "ruby": [], "rt": [], "rp": [], "bdi": [], "bdo": [], "span": [], "br": [], "wbr": [], "ins": ["cite", "datetime"], "del": ["cite", "datetime"], "img": ["alt", "src", "height", "width", "usemap", "ismap"], "iframe": ["name", "src", "height", "width", "sandbox", "seamless"], "embed": ["src", "height", "width", "type"], "object": ["param", "data", "type", "height" , "width", "usemap", "name", "form", "classid"], "param": ["name", "value"], "video": ["src", "autobuffer", "autoplay", "loop", "controls", "width", "height", "poster"], "audio": ["src", "autobuffer", "autoplay", "loop", "controls"], "source": ["src", "type", "media"], "track": ["kind", "src", "srclang", "label", "default"], "canvas": ["width", "height"], "map": ["name"], "area": ["shape", "coords", "href", "hreflang", "alt", "target", "media", "rel", "ping", "type"], "svg": [], "math": [], "table": ["summary"], "caption": [], "colgroup": ["span"], "col": ["span"], "tbody": [], "thead": [], "tfoot": [], "tr": [], "td": ["headers", "rowspan", "colspan"], "th": ["headers", "rowspan", "colspan", "scope"], "form": ["accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target"], "fieldset": ["disabled", "form", "name"], "legend": [], "label": ["form", "for"], "input": ["type", "accept", "alt", "autocomplete", "checked", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "list", "max", "maxlength", "min", "multiple", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "width", "files", "value"], "button": ["autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "value", "type"], "select": ["autofocus", "disabled", "form", "multiple", "name", "size"], "datalist": [], "optgroup": ["disabled", "label"], "option": ["disabled", "selected", "label", "value"], "textarea": ["autofocus", "disabled", "form", "maxlength", "name", "placeholder", "readonly", "required", "rows", "cols", "wrap"], "keygen": ["autofocus", "challenge", "disabled", "form", "keytype", "name"], "output": ["for", "form", "name"], "progress": ["value", "max"], "meter": ["value", "min", "max", "low", "high", "optimum"], "details": ["open"], "summary": [], "command": ["type", "label", "icon", "disabled", "checked", "radiogroup", "command"], "menu": ["type", "label"], "dialog": ["open"] }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompetions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompetions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(attributeMap[tagName]); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/markdown_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules","ace/mode/html_highlight_rules","ace/mode/css_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var escaped = function(ch) { return "(?:[^" + lang.escapeRegExp(ch) + "\\\\]|\\\\.)*"; } function github_embed(tag, prefix) { return { // Github style block token : "support.function", regex : "^\\s*```" + tag + "\\s*$", push : prefix + "start" }; } var MarkdownHighlightRules = function() { HtmlHighlightRules.call(this); this.$rules["start"].unshift({ token : "empty_line", regex : '^$', next: "allowBlock" }, { // h1 token: "markup.heading.1", regex: "^=+(?=\\s*$)" }, { // h2 token: "markup.heading.2", regex: "^\\-+(?=\\s*$)" }, { token : function(value) { return "markup.heading." + value.length; }, regex : /^#{1,6}(?=\s*[^ #]|\s+#.)/, next : "header" }, github_embed("(?:javascript|js)", "jscode-"), github_embed("xml", "xmlcode-"), github_embed("html", "htmlcode-"), github_embed("css", "csscode-"), { // Github style block token : "support.function", regex : "^\\s*```\\s*\\S*(?:{.*?\\})?\\s*$", next : "githubblock" }, { // block quote token : "string.blockquote", regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+", next : "blockquote" }, { // HR * - _ token : "constant", regex : "^ {0,2}(?:(?: ?\\* ?){3,}|(?: ?\\- ?){3,}|(?: ?\\_ ?){3,})\\s*$", next: "allowBlock" }, { // list token : "markup.list", regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+", next : "listblock-start" }, { include : "basic" }); this.addRules({ "basic" : [{ token : "constant.language.escape", regex : /\\[\\`*_{}\[\]()#+\-.!]/ }, { // code span ` token : "support.function", regex : "(`+)(.*?[^`])(\\1)" }, { // reference token : ["text", "constant", "text", "url", "string", "text"], regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$" }, { // link by reference token : ["text", "string", "text", "constant", "text"], regex : "(\\[)(" + escaped("]") + ")(\\]\s*\\[)("+ escaped("]") + ")(\\])" }, { // link by url token : ["text", "string", "text", "markup.underline", "string", "text"], regex : "(\\[)(" + // [ escaped("]") + // link text ")(\\]\\()"+ // ]( '((?:[^\\)\\s\\\\]|\\\\.|\\s(?=[^"]))*)' + // href '(\\s*"' + escaped('"') + '"\\s*)?' + // "title" "(\\))" // ) }, { // strong ** __ token : "string.strong", regex : "([*]{2}|[_]{2}(?=\\S))(.*?\\S[*_]*)(\\1)" }, { // emphasis * _ token : "string.emphasis", regex : "([*]|[_](?=\\S))(.*?\\S[*_]*)(\\1)" }, { // token : ["text", "url", "text"], regex : "(<)("+ "(?:https?|ftp|dict):[^'\">\\s]+"+ "|"+ "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+ ")(>)" }], "allowBlock": [ {token : "support.function", regex : "^ {4}.+", next : "allowBlock"}, {token : "empty", regex : "", next : "start"} ], "header" : [{ regex: "$", next : "start" }, { include: "basic" }, { defaultToken : "heading" } ], "listblock-start" : [{ token : "support.variable", regex : /(?:\[[ x]\])?/, next : "listblock" }], "listblock" : [ { // Lists only escape on completely blank lines. token : "empty_line", regex : "^$", next : "start" }, { // list token : "markup.list", regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+", next : "listblock-start" }, { include : "basic", noEscape: true }, { // Github style block token : "support.function", regex : "^\\s*```\\s*[a-zA-Z]*(?:{.*?\\})?\\s*$", next : "githubblock" }, { defaultToken : "list" //do not use markup.list to allow stling leading `*` differntly } ], "blockquote" : [ { // Blockquotes only escape on blank lines. token : "empty_line", regex : "^\\s*$", next : "start" }, { // block quote token : "string.blockquote", regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+", next : "blockquote" }, { include : "basic", noEscape: true }, { defaultToken : "string.blockquote" } ], "githubblock" : [ { token : "support.function", regex : "^\\s*```", next : "start" }, { token : "support.function", regex : ".+" } ] }); this.embedRules(JavaScriptHighlightRules, "jscode-", [{ token : "support.function", regex : "^\\s*```", next : "pop" }]); this.embedRules(HtmlHighlightRules, "htmlcode-", [{ token : "support.function", regex : "^\\s*```", next : "pop" }]); this.embedRules(CssHighlightRules, "csscode-", [{ token : "support.function", regex : "^\\s*```", next : "pop" }]); this.embedRules(XmlHighlightRules, "xmlcode-", [{ token : "support.function", regex : "^\\s*```", next : "pop" }]); this.normalizeRules(); }; oop.inherits(MarkdownHighlightRules, TextHighlightRules); exports.MarkdownHighlightRules = MarkdownHighlightRules; }); ace.define("ace/mode/folding/markdown",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /^(?:[=-]+\s*$|#{1,6} |`{3})/; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (!this.foldingStartMarker.test(line)) return ""; if (line[0] == "`") { if (session.bgTokenizer.getState(row) == "start") return "end"; return "start"; } return "start"; }; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; if (!line.match(this.foldingStartMarker)) return; if (line[0] == "`") { if (session.bgTokenizer.getState(row) !== "start") { while (++row < maxRow) { line = session.getLine(row); if (line[0] == "`" & line.substring(0, 3) == "```") break; } return new Range(startRow, startColumn, row, 0); } else { while (row -- > 0) { line = session.getLine(row); if (line[0] == "`" & line.substring(0, 3) == "```") break; } return new Range(row, line.length, startRow, 0); } } var token; function isHeading(row) { token = session.getTokens(row)[0]; return token && token.type.lastIndexOf(heading, 0) === 0; } var heading = "markup.heading"; function getLevel() { var ch = token.value[0]; if (ch == "=") return 6; if (ch == "-") return 5; return 7 - token.value.search(/[^#]/); } if (isHeading(row)) { var startHeadingLevel = getLevel(); while (++row < maxRow) { if (!isHeading(row)) continue; var level = getLevel(); if (level >= startHeadingLevel) break; } endRow = row - (!token || ["=", "-"].indexOf(token.value[0]) == -1 ? 1 : 2); if (endRow > startRow) { while (endRow > startRow && /^\s*$/.test(session.getLine(endRow))) endRow--; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/markdown",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/xml","ace/mode/html","ace/mode/markdown_highlight_rules","ace/mode/folding/markdown"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var XmlMode = require("./xml").Mode; var HtmlMode = require("./html").Mode; var MarkdownHighlightRules = require("./markdown_highlight_rules").MarkdownHighlightRules; var MarkdownFoldMode = require("./folding/markdown").FoldMode; var Mode = function() { this.HighlightRules = MarkdownHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode, "xml-": XmlMode, "html-": HtmlMode }); this.foldingRules = new MarkdownFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.type = "text"; this.blockComment = {start: "<!--", end: "-->"}; this.getNextLineIndent = function(state, line, tab) { if (state == "listblock") { var match = /^(\s*)(?:([-+*])|(\d+)\.)(\s+)/.exec(line); if (!match) return ""; var marker = match[2]; if (!marker) marker = parseInt(match[3], 10) + 1 + "."; return match[1] + marker + match[4]; } else { return this.$getIndent(line); } }; this.$id = "ace/mode/markdown"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace/worker-javascript.js
11,614
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); }; } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, [\'\', \'\']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!range instanceof Range) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } var cons = obj.constructor; if (cons === RegExp) return obj; copy = cons(); for (var key in obj) { copy[key] = deepCopy(obj[key]); } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/javascript/jshint",["require","exports","module"], function(require, exports, module) { module.exports = (function outer (modules, cache, entry) { var previousRequire = typeof require == "function" && require; function newRequire(name, jumped){ if(!cache[name]) { if(!modules[name]) { var currentRequire = typeof require == "function" && require; if (!jumped && currentRequire) return currentRequire(name, true); if (previousRequire) return previousRequire(name, true); var err = new Error('Cannot find module \'' + name + '\''); err.code = 'MODULE_NOT_FOUND'; throw err; } var m = cache[name] = {exports:{}}; modules[name][0].call(m.exports, function(x){ var id = modules[name][1][x]; return newRequire(id ? id : x); },m,m.exports,outer,modules,cache,entry); } return cache[name].exports; } for(var i=0;i<entry.length;i++) newRequire(entry[i]); return newRequire(entry[0]); }) ({"/node_modules/browserify/node_modules/events/events.js":[function(_dereq_,module,exports){ function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; EventEmitter.defaultMaxListeners = 10; EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } throw TypeError('Uncaught, unspecified "error" event.'); } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) this._events[type] = listener; else if (isObject(this._events[type])) this._events[type].push(listener); else this._events[type] = [this._events[type], listener]; if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],"/node_modules/jshint/data/ascii-identifier-data.js":[function(_dereq_,module,exports){ var identifierStartTable = []; for (var i = 0; i < 128; i++) { identifierStartTable[i] = i === 36 || // $ i >= 65 && i <= 90 || // A-Z i === 95 || // _ i >= 97 && i <= 122; // a-z } var identifierPartTable = []; for (var i = 0; i < 128; i++) { identifierPartTable[i] = identifierStartTable[i] || // $, _, A-Z, a-z i >= 48 && i <= 57; // 0-9 } module.exports = { asciiIdentifierStartTable: identifierStartTable, asciiIdentifierPartTable: identifierPartTable }; },{}],"/node_modules/jshint/node_modules/underscore/underscore.js":[function(_dereq_,module,exports){ (function() { var root = this; var previousUnderscore = root._; var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype; var push = ArrayProto.push, slice = ArrayProto.slice, toString = ObjProto.toString, hasOwnProperty = ObjProto.hasOwnProperty; var nativeIsArray = Array.isArray, nativeKeys = Object.keys, nativeBind = FuncProto.bind, nativeCreate = Object.create; var Ctor = function(){}; var _ = function(obj) { if (obj instanceof _) return obj; if (!(this instanceof _)) return new _(obj); this._wrapped = obj; }; if (typeof exports !== 'undefined') { if (typeof module !== 'undefined' && module.exports) { exports = module.exports = _; } exports._ = _; } else { root._ = _; } _.VERSION = '1.8.3'; var optimizeCb = function(func, context, argCount) { if (context === void 0) return func; switch (argCount == null ? 3 : argCount) { case 1: return function(value) { return func.call(context, value); }; case 2: return function(value, other) { return func.call(context, value, other); }; case 3: return function(value, index, collection) { return func.call(context, value, index, collection); }; case 4: return function(accumulator, value, index, collection) { return func.call(context, accumulator, value, index, collection); }; } return function() { return func.apply(context, arguments); }; }; var cb = function(value, context, argCount) { if (value == null) return _.identity; if (_.isFunction(value)) return optimizeCb(value, context, argCount); if (_.isObject(value)) return _.matcher(value); return _.property(value); }; _.iteratee = function(value, context) { return cb(value, context, Infinity); }; var createAssigner = function(keysFunc, undefinedOnly) { return function(obj) { var length = arguments.length; if (length < 2 || obj == null) return obj; for (var index = 1; index < length; index++) { var source = arguments[index], keys = keysFunc(source), l = keys.length; for (var i = 0; i < l; i++) { var key = keys[i]; if (!undefinedOnly || obj[key] === void 0) obj[key] = source[key]; } } return obj; }; }; var baseCreate = function(prototype) { if (!_.isObject(prototype)) return {}; if (nativeCreate) return nativeCreate(prototype); Ctor.prototype = prototype; var result = new Ctor; Ctor.prototype = null; return result; }; var property = function(key) { return function(obj) { return obj == null ? void 0 : obj[key]; }; }; var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; var getLength = property('length'); var isArrayLike = function(collection) { var length = getLength(collection); return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; _.each = _.forEach = function(obj, iteratee, context) { iteratee = optimizeCb(iteratee, context); var i, length; if (isArrayLike(obj)) { for (i = 0, length = obj.length; i < length; i++) { iteratee(obj[i], i, obj); } } else { var keys = _.keys(obj); for (i = 0, length = keys.length; i < length; i++) { iteratee(obj[keys[i]], keys[i], obj); } } return obj; }; _.map = _.collect = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, results = Array(length); for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; results[index] = iteratee(obj[currentKey], currentKey, obj); } return results; }; function createReduce(dir) { function iterator(obj, iteratee, memo, keys, index, length) { for (; index >= 0 && index < length; index += dir) { var currentKey = keys ? keys[index] : index; memo = iteratee(memo, obj[currentKey], currentKey, obj); } return memo; } return function(obj, iteratee, memo, context) { iteratee = optimizeCb(iteratee, context, 4); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length, index = dir > 0 ? 0 : length - 1; if (arguments.length < 3) { memo = obj[keys ? keys[index] : index]; index += dir; } return iterator(obj, iteratee, memo, keys, index, length); }; } _.reduce = _.foldl = _.inject = createReduce(1); _.reduceRight = _.foldr = createReduce(-1); _.find = _.detect = function(obj, predicate, context) { var key; if (isArrayLike(obj)) { key = _.findIndex(obj, predicate, context); } else { key = _.findKey(obj, predicate, context); } if (key !== void 0 && key !== -1) return obj[key]; }; _.filter = _.select = function(obj, predicate, context) { var results = []; predicate = cb(predicate, context); _.each(obj, function(value, index, list) { if (predicate(value, index, list)) results.push(value); }); return results; }; _.reject = function(obj, predicate, context) { return _.filter(obj, _.negate(cb(predicate)), context); }; _.every = _.all = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (!predicate(obj[currentKey], currentKey, obj)) return false; } return true; }; _.some = _.any = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = !isArrayLike(obj) && _.keys(obj), length = (keys || obj).length; for (var index = 0; index < length; index++) { var currentKey = keys ? keys[index] : index; if (predicate(obj[currentKey], currentKey, obj)) return true; } return false; }; _.contains = _.includes = _.include = function(obj, item, fromIndex, guard) { if (!isArrayLike(obj)) obj = _.values(obj); if (typeof fromIndex != 'number' || guard) fromIndex = 0; return _.indexOf(obj, item, fromIndex) >= 0; }; _.invoke = function(obj, method) { var args = slice.call(arguments, 2); var isFunc = _.isFunction(method); return _.map(obj, function(value) { var func = isFunc ? method : value[method]; return func == null ? func : func.apply(value, args); }); }; _.pluck = function(obj, key) { return _.map(obj, _.property(key)); }; _.where = function(obj, attrs) { return _.filter(obj, _.matcher(attrs)); }; _.findWhere = function(obj, attrs) { return _.find(obj, _.matcher(attrs)); }; _.max = function(obj, iteratee, context) { var result = -Infinity, lastComputed = -Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value > result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed > lastComputed || computed === -Infinity && result === -Infinity) { result = value; lastComputed = computed; } }); } return result; }; _.min = function(obj, iteratee, context) { var result = Infinity, lastComputed = Infinity, value, computed; if (iteratee == null && obj != null) { obj = isArrayLike(obj) ? obj : _.values(obj); for (var i = 0, length = obj.length; i < length; i++) { value = obj[i]; if (value < result) { result = value; } } } else { iteratee = cb(iteratee, context); _.each(obj, function(value, index, list) { computed = iteratee(value, index, list); if (computed < lastComputed || computed === Infinity && result === Infinity) { result = value; lastComputed = computed; } }); } return result; }; _.shuffle = function(obj) { var set = isArrayLike(obj) ? obj : _.values(obj); var length = set.length; var shuffled = Array(length); for (var index = 0, rand; index < length; index++) { rand = _.random(0, index); if (rand !== index) shuffled[index] = shuffled[rand]; shuffled[rand] = set[index]; } return shuffled; }; _.sample = function(obj, n, guard) { if (n == null || guard) { if (!isArrayLike(obj)) obj = _.values(obj); return obj[_.random(obj.length - 1)]; } return _.shuffle(obj).slice(0, Math.max(0, n)); }; _.sortBy = function(obj, iteratee, context) { iteratee = cb(iteratee, context); return _.pluck(_.map(obj, function(value, index, list) { return { value: value, index: index, criteria: iteratee(value, index, list) }; }).sort(function(left, right) { var a = left.criteria; var b = right.criteria; if (a !== b) { if (a > b || a === void 0) return 1; if (a < b || b === void 0) return -1; } return left.index - right.index; }), 'value'); }; var group = function(behavior) { return function(obj, iteratee, context) { var result = {}; iteratee = cb(iteratee, context); _.each(obj, function(value, index) { var key = iteratee(value, index, obj); behavior(result, value, key); }); return result; }; }; _.groupBy = group(function(result, value, key) { if (_.has(result, key)) result[key].push(value); else result[key] = [value]; }); _.indexBy = group(function(result, value, key) { result[key] = value; }); _.countBy = group(function(result, value, key) { if (_.has(result, key)) result[key]++; else result[key] = 1; }); _.toArray = function(obj) { if (!obj) return []; if (_.isArray(obj)) return slice.call(obj); if (isArrayLike(obj)) return _.map(obj, _.identity); return _.values(obj); }; _.size = function(obj) { if (obj == null) return 0; return isArrayLike(obj) ? obj.length : _.keys(obj).length; }; _.partition = function(obj, predicate, context) { predicate = cb(predicate, context); var pass = [], fail = []; _.each(obj, function(value, key, obj) { (predicate(value, key, obj) ? pass : fail).push(value); }); return [pass, fail]; }; _.first = _.head = _.take = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[0]; return _.initial(array, array.length - n); }; _.initial = function(array, n, guard) { return slice.call(array, 0, Math.max(0, array.length - (n == null || guard ? 1 : n))); }; _.last = function(array, n, guard) { if (array == null) return void 0; if (n == null || guard) return array[array.length - 1]; return _.rest(array, Math.max(0, array.length - n)); }; _.rest = _.tail = _.drop = function(array, n, guard) { return slice.call(array, n == null || guard ? 1 : n); }; _.compact = function(array) { return _.filter(array, _.identity); }; var flatten = function(input, shallow, strict, startIndex) { var output = [], idx = 0; for (var i = startIndex || 0, length = getLength(input); i < length; i++) { var value = input[i]; if (isArrayLike(value) && (_.isArray(value) || _.isArguments(value))) { if (!shallow) value = flatten(value, shallow, strict); var j = 0, len = value.length; output.length += len; while (j < len) { output[idx++] = value[j++]; } } else if (!strict) { output[idx++] = value; } } return output; }; _.flatten = function(array, shallow) { return flatten(array, shallow, false); }; _.without = function(array) { return _.difference(array, slice.call(arguments, 1)); }; _.uniq = _.unique = function(array, isSorted, iteratee, context) { if (!_.isBoolean(isSorted)) { context = iteratee; iteratee = isSorted; isSorted = false; } if (iteratee != null) iteratee = cb(iteratee, context); var result = []; var seen = []; for (var i = 0, length = getLength(array); i < length; i++) { var value = array[i], computed = iteratee ? iteratee(value, i, array) : value; if (isSorted) { if (!i || seen !== computed) result.push(value); seen = computed; } else if (iteratee) { if (!_.contains(seen, computed)) { seen.push(computed); result.push(value); } } else if (!_.contains(result, value)) { result.push(value); } } return result; }; _.union = function() { return _.uniq(flatten(arguments, true, true)); }; _.intersection = function(array) { var result = []; var argsLength = arguments.length; for (var i = 0, length = getLength(array); i < length; i++) { var item = array[i]; if (_.contains(result, item)) continue; for (var j = 1; j < argsLength; j++) { if (!_.contains(arguments[j], item)) break; } if (j === argsLength) result.push(item); } return result; }; _.difference = function(array) { var rest = flatten(arguments, true, true, 1); return _.filter(array, function(value){ return !_.contains(rest, value); }); }; _.zip = function() { return _.unzip(arguments); }; _.unzip = function(array) { var length = array && _.max(array, getLength).length || 0; var result = Array(length); for (var index = 0; index < length; index++) { result[index] = _.pluck(array, index); } return result; }; _.object = function(list, values) { var result = {}; for (var i = 0, length = getLength(list); i < length; i++) { if (values) { result[list[i]] = values[i]; } else { result[list[i][0]] = list[i][1]; } } return result; }; function createPredicateIndexFinder(dir) { return function(array, predicate, context) { predicate = cb(predicate, context); var length = getLength(array); var index = dir > 0 ? 0 : length - 1; for (; index >= 0 && index < length; index += dir) { if (predicate(array[index], index, array)) return index; } return -1; }; } _.findIndex = createPredicateIndexFinder(1); _.findLastIndex = createPredicateIndexFinder(-1); _.sortedIndex = function(array, obj, iteratee, context) { iteratee = cb(iteratee, context, 1); var value = iteratee(obj); var low = 0, high = getLength(array); while (low < high) { var mid = Math.floor((low + high) / 2); if (iteratee(array[mid]) < value) low = mid + 1; else high = mid; } return low; }; function createIndexFinder(dir, predicateFind, sortedIndex) { return function(array, item, idx) { var i = 0, length = getLength(array); if (typeof idx == 'number') { if (dir > 0) { i = idx >= 0 ? idx : Math.max(idx + length, i); } else { length = idx >= 0 ? Math.min(idx + 1, length) : idx + length + 1; } } else if (sortedIndex && idx && length) { idx = sortedIndex(array, item); return array[idx] === item ? idx : -1; } if (item !== item) { idx = predicateFind(slice.call(array, i, length), _.isNaN); return idx >= 0 ? idx + i : -1; } for (idx = dir > 0 ? i : length - 1; idx >= 0 && idx < length; idx += dir) { if (array[idx] === item) return idx; } return -1; }; } _.indexOf = createIndexFinder(1, _.findIndex, _.sortedIndex); _.lastIndexOf = createIndexFinder(-1, _.findLastIndex); _.range = function(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }; var executeBound = function(sourceFunc, boundFunc, context, callingContext, args) { if (!(callingContext instanceof boundFunc)) return sourceFunc.apply(context, args); var self = baseCreate(sourceFunc.prototype); var result = sourceFunc.apply(self, args); if (_.isObject(result)) return result; return self; }; _.bind = function(func, context) { if (nativeBind && func.bind === nativeBind) return nativeBind.apply(func, slice.call(arguments, 1)); if (!_.isFunction(func)) throw new TypeError('Bind must be called on a function'); var args = slice.call(arguments, 2); var bound = function() { return executeBound(func, bound, context, this, args.concat(slice.call(arguments))); }; return bound; }; _.partial = function(func) { var boundArgs = slice.call(arguments, 1); var bound = function() { var position = 0, length = boundArgs.length; var args = Array(length); for (var i = 0; i < length; i++) { args[i] = boundArgs[i] === _ ? arguments[position++] : boundArgs[i]; } while (position < arguments.length) args.push(arguments[position++]); return executeBound(func, bound, this, this, args); }; return bound; }; _.bindAll = function(obj) { var i, length = arguments.length, key; if (length <= 1) throw new Error('bindAll must be passed function names'); for (i = 1; i < length; i++) { key = arguments[i]; obj[key] = _.bind(obj[key], obj); } return obj; }; _.memoize = function(func, hasher) { var memoize = function(key) { var cache = memoize.cache; var address = '' + (hasher ? hasher.apply(this, arguments) : key); if (!_.has(cache, address)) cache[address] = func.apply(this, arguments); return cache[address]; }; memoize.cache = {}; return memoize; }; _.delay = function(func, wait) { var args = slice.call(arguments, 2); return setTimeout(function(){ return func.apply(null, args); }, wait); }; _.defer = _.partial(_.delay, _, 1); _.throttle = function(func, wait, options) { var context, args, result; var timeout = null; var previous = 0; if (!options) options = {}; var later = function() { previous = options.leading === false ? 0 : _.now(); timeout = null; result = func.apply(context, args); if (!timeout) context = args = null; }; return function() { var now = _.now(); if (!previous && options.leading === false) previous = now; var remaining = wait - (now - previous); context = this; args = arguments; if (remaining <= 0 || remaining > wait) { if (timeout) { clearTimeout(timeout); timeout = null; } previous = now; result = func.apply(context, args); if (!timeout) context = args = null; } else if (!timeout && options.trailing !== false) { timeout = setTimeout(later, remaining); } return result; }; }; _.debounce = function(func, wait, immediate) { var timeout, args, context, timestamp, result; var later = function() { var last = _.now() - timestamp; if (last < wait && last >= 0) { timeout = setTimeout(later, wait - last); } else { timeout = null; if (!immediate) { result = func.apply(context, args); if (!timeout) context = args = null; } } }; return function() { context = this; args = arguments; timestamp = _.now(); var callNow = immediate && !timeout; if (!timeout) timeout = setTimeout(later, wait); if (callNow) { result = func.apply(context, args); context = args = null; } return result; }; }; _.wrap = function(func, wrapper) { return _.partial(wrapper, func); }; _.negate = function(predicate) { return function() { return !predicate.apply(this, arguments); }; }; _.compose = function() { var args = arguments; var start = args.length - 1; return function() { var i = start; var result = args[start].apply(this, arguments); while (i--) result = args[i].call(this, result); return result; }; }; _.after = function(times, func) { return function() { if (--times < 1) { return func.apply(this, arguments); } }; }; _.before = function(times, func) { var memo; return function() { if (--times > 0) { memo = func.apply(this, arguments); } if (times <= 1) func = null; return memo; }; }; _.once = _.partial(_.before, 2); var hasEnumBug = !{toString: null}.propertyIsEnumerable('toString'); var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString', 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString']; function collectNonEnumProps(obj, keys) { var nonEnumIdx = nonEnumerableProps.length; var constructor = obj.constructor; var proto = (_.isFunction(constructor) && constructor.prototype) || ObjProto; var prop = 'constructor'; if (_.has(obj, prop) && !_.contains(keys, prop)) keys.push(prop); while (nonEnumIdx--) { prop = nonEnumerableProps[nonEnumIdx]; if (prop in obj && obj[prop] !== proto[prop] && !_.contains(keys, prop)) { keys.push(prop); } } } _.keys = function(obj) { if (!_.isObject(obj)) return []; if (nativeKeys) return nativeKeys(obj); var keys = []; for (var key in obj) if (_.has(obj, key)) keys.push(key); if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; _.allKeys = function(obj) { if (!_.isObject(obj)) return []; var keys = []; for (var key in obj) keys.push(key); if (hasEnumBug) collectNonEnumProps(obj, keys); return keys; }; _.values = function(obj) { var keys = _.keys(obj); var length = keys.length; var values = Array(length); for (var i = 0; i < length; i++) { values[i] = obj[keys[i]]; } return values; }; _.mapObject = function(obj, iteratee, context) { iteratee = cb(iteratee, context); var keys = _.keys(obj), length = keys.length, results = {}, currentKey; for (var index = 0; index < length; index++) { currentKey = keys[index]; results[currentKey] = iteratee(obj[currentKey], currentKey, obj); } return results; }; _.pairs = function(obj) { var keys = _.keys(obj); var length = keys.length; var pairs = Array(length); for (var i = 0; i < length; i++) { pairs[i] = [keys[i], obj[keys[i]]]; } return pairs; }; _.invert = function(obj) { var result = {}; var keys = _.keys(obj); for (var i = 0, length = keys.length; i < length; i++) { result[obj[keys[i]]] = keys[i]; } return result; }; _.functions = _.methods = function(obj) { var names = []; for (var key in obj) { if (_.isFunction(obj[key])) names.push(key); } return names.sort(); }; _.extend = createAssigner(_.allKeys); _.extendOwn = _.assign = createAssigner(_.keys); _.findKey = function(obj, predicate, context) { predicate = cb(predicate, context); var keys = _.keys(obj), key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; if (predicate(obj[key], key, obj)) return key; } }; _.pick = function(object, oiteratee, context) { var result = {}, obj = object, iteratee, keys; if (obj == null) return result; if (_.isFunction(oiteratee)) { keys = _.allKeys(obj); iteratee = optimizeCb(oiteratee, context); } else { keys = flatten(arguments, false, false, 1); iteratee = function(value, key, obj) { return key in obj; }; obj = Object(obj); } for (var i = 0, length = keys.length; i < length; i++) { var key = keys[i]; var value = obj[key]; if (iteratee(value, key, obj)) result[key] = value; } return result; }; _.omit = function(obj, iteratee, context) { if (_.isFunction(iteratee)) { iteratee = _.negate(iteratee); } else { var keys = _.map(flatten(arguments, false, false, 1), String); iteratee = function(value, key) { return !_.contains(keys, key); }; } return _.pick(obj, iteratee, context); }; _.defaults = createAssigner(_.allKeys, true); _.create = function(prototype, props) { var result = baseCreate(prototype); if (props) _.extendOwn(result, props); return result; }; _.clone = function(obj) { if (!_.isObject(obj)) return obj; return _.isArray(obj) ? obj.slice() : _.extend({}, obj); }; _.tap = function(obj, interceptor) { interceptor(obj); return obj; }; _.isMatch = function(object, attrs) { var keys = _.keys(attrs), length = keys.length; if (object == null) return !length; var obj = Object(object); for (var i = 0; i < length; i++) { var key = keys[i]; if (attrs[key] !== obj[key] || !(key in obj)) return false; } return true; }; var eq = function(a, b, aStack, bStack) { if (a === b) return a !== 0 || 1 / a === 1 / b; if (a == null || b == null) return a === b; if (a instanceof _) a = a._wrapped; if (b instanceof _) b = b._wrapped; var className = toString.call(a); if (className !== toString.call(b)) return false; switch (className) { case '[object RegExp]': case '[object String]': return '' + a === '' + b; case '[object Number]': if (+a !== +a) return +b !== +b; return +a === 0 ? 1 / +a === 1 / b : +a === +b; case '[object Date]': case '[object Boolean]': return +a === +b; } var areArrays = className === '[object Array]'; if (!areArrays) { if (typeof a != 'object' || typeof b != 'object') return false; var aCtor = a.constructor, bCtor = b.constructor; if (aCtor !== bCtor && !(_.isFunction(aCtor) && aCtor instanceof aCtor && _.isFunction(bCtor) && bCtor instanceof bCtor) && ('constructor' in a && 'constructor' in b)) { return false; } } aStack = aStack || []; bStack = bStack || []; var length = aStack.length; while (length--) { if (aStack[length] === a) return bStack[length] === b; } aStack.push(a); bStack.push(b); if (areArrays) { length = a.length; if (length !== b.length) return false; while (length--) { if (!eq(a[length], b[length], aStack, bStack)) return false; } } else { var keys = _.keys(a), key; length = keys.length; if (_.keys(b).length !== length) return false; while (length--) { key = keys[length]; if (!(_.has(b, key) && eq(a[key], b[key], aStack, bStack))) return false; } } aStack.pop(); bStack.pop(); return true; }; _.isEqual = function(a, b) { return eq(a, b); }; _.isEmpty = function(obj) { if (obj == null) return true; if (isArrayLike(obj) && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; return _.keys(obj).length === 0; }; _.isElement = function(obj) { return !!(obj && obj.nodeType === 1); }; _.isArray = nativeIsArray || function(obj) { return toString.call(obj) === '[object Array]'; }; _.isObject = function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }; _.each(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Error'], function(name) { _['is' + name] = function(obj) { return toString.call(obj) === '[object ' + name + ']'; }; }); if (!_.isArguments(arguments)) { _.isArguments = function(obj) { return _.has(obj, 'callee'); }; } if (typeof /./ != 'function' && typeof Int8Array != 'object') { _.isFunction = function(obj) { return typeof obj == 'function' || false; }; } _.isFinite = function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }; _.isNaN = function(obj) { return _.isNumber(obj) && obj !== +obj; }; _.isBoolean = function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }; _.isNull = function(obj) { return obj === null; }; _.isUndefined = function(obj) { return obj === void 0; }; _.has = function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }; _.noConflict = function() { root._ = previousUnderscore; return this; }; _.identity = function(value) { return value; }; _.constant = function(value) { return function() { return value; }; }; _.noop = function(){}; _.property = property; _.propertyOf = function(obj) { return obj == null ? function(){} : function(key) { return obj[key]; }; }; _.matcher = _.matches = function(attrs) { attrs = _.extendOwn({}, attrs); return function(obj) { return _.isMatch(obj, attrs); }; }; _.times = function(n, iteratee, context) { var accum = Array(Math.max(0, n)); iteratee = optimizeCb(iteratee, context, 1); for (var i = 0; i < n; i++) accum[i] = iteratee(i); return accum; }; _.random = function(min, max) { if (max == null) { max = min; min = 0; } return min + Math.floor(Math.random() * (max - min + 1)); }; _.now = Date.now || function() { return new Date().getTime(); }; var escapeMap = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#x27;', '`': '&#x60;' }; var unescapeMap = _.invert(escapeMap); var createEscaper = function(map) { var escaper = function(match) { return map[match]; }; var source = '(?:' + _.keys(map).join('|') + ')'; var testRegexp = RegExp(source); var replaceRegexp = RegExp(source, 'g'); return function(string) { string = string == null ? '' : '' + string; return testRegexp.test(string) ? string.replace(replaceRegexp, escaper) : string; }; }; _.escape = createEscaper(escapeMap); _.unescape = createEscaper(unescapeMap); _.result = function(object, property, fallback) { var value = object == null ? void 0 : object[property]; if (value === void 0) { value = fallback; } return _.isFunction(value) ? value.call(object) : value; }; var idCounter = 0; _.uniqueId = function(prefix) { var id = ++idCounter + ''; return prefix ? prefix + id : id; }; _.templateSettings = { evaluate : /<%([\s\S]+?)%>/g, interpolate : /<%=([\s\S]+?)%>/g, escape : /<%-([\s\S]+?)%>/g }; var noMatch = /(.)^/; var escapes = { "'": "'", '\\': '\\', '\r': 'r', '\n': 'n', '\u2028': 'u2028', '\u2029': 'u2029' }; var escaper = /\\|'|\r|\n|\u2028|\u2029/g; var escapeChar = function(match) { return '\\' + escapes[match]; }; _.template = function(text, settings, oldSettings) { if (!settings && oldSettings) settings = oldSettings; settings = _.defaults({}, settings, _.templateSettings); var matcher = RegExp([ (settings.escape || noMatch).source, (settings.interpolate || noMatch).source, (settings.evaluate || noMatch).source ].join('|') + '|$', 'g'); var index = 0; var source = "__p+='"; text.replace(matcher, function(match, escape, interpolate, evaluate, offset) { source += text.slice(index, offset).replace(escaper, escapeChar); index = offset + match.length; if (escape) { source += "'+\n((__t=(" + escape + "))==null?'':_.escape(__t))+\n'"; } else if (interpolate) { source += "'+\n((__t=(" + interpolate + "))==null?'':__t)+\n'"; } else if (evaluate) { source += "';\n" + evaluate + "\n__p+='"; } return match; }); source += "';\n"; if (!settings.variable) source = 'with(obj||{}){\n' + source + '}\n'; source = "var __t,__p='',__j=Array.prototype.join," + "print=function(){__p+=__j.call(arguments,'');};\n" + source + 'return __p;\n'; try { var render = new Function(settings.variable || 'obj', '_', source); } catch (e) { e.source = source; throw e; } var template = function(data) { return render.call(this, data, _); }; var argument = settings.variable || 'obj'; template.source = 'function(' + argument + '){\n' + source + '}'; return template; }; _.chain = function(obj) { var instance = _(obj); instance._chain = true; return instance; }; var result = function(instance, obj) { return instance._chain ? _(obj).chain() : obj; }; _.mixin = function(obj) { _.each(_.functions(obj), function(name) { var func = _[name] = obj[name]; _.prototype[name] = function() { var args = [this._wrapped]; push.apply(args, arguments); return result(this, func.apply(_, args)); }; }); }; _.mixin(_); _.each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { var obj = this._wrapped; method.apply(obj, arguments); if ((name === 'shift' || name === 'splice') && obj.length === 0) delete obj[0]; return result(this, obj); }; }); _.each(['concat', 'join', 'slice'], function(name) { var method = ArrayProto[name]; _.prototype[name] = function() { return result(this, method.apply(this._wrapped, arguments)); }; }); _.prototype.value = function() { return this._wrapped; }; _.prototype.valueOf = _.prototype.toJSON = _.prototype.value; _.prototype.toString = function() { return '' + this._wrapped; }; if (typeof define === 'function' && define.amd) { ace.define('underscore', [], function() { return _; }); } }.call(this)); },{}],"/node_modules/jshint/src/jshint.js":[function(_dereq_,module,exports){ var _ = _dereq_("underscore"); var events = _dereq_("events"); var vars = _dereq_("./vars.js"); var messages = _dereq_("./messages.js"); var Lexer = _dereq_("./lex.js").Lexer; var reg = _dereq_("./reg.js"); var state = _dereq_("./state.js").state; var style = _dereq_("./style.js"); var options = _dereq_("./options.js"); var JSHINT = (function() { "use strict"; var api, // Extension API bang = { "<" : true, "<=" : true, "==" : true, "===": true, "!==": true, "!=" : true, ">" : true, ">=" : true, "+" : true, "-" : true, "*" : true, "/" : true, "%" : true }, declared, // Globals that were declared using /*global ... */ syntax. exported, // Variables that are used outside of the current file. functionicity = [ "closure", "exception", "global", "label", "outer", "unused", "var" ], functions, // All of the functions global, // The global scope implied, // Implied globals inblock, indent, lookahead, lex, member, membersOnly, predefined, // Global variables defined by option scope, // The current scope stack, unuseds, urls, extraModules = [], emitter = new events.EventEmitter(); function checkOption(name, t) { name = name.trim(); if (/^[+-]W\d{3}$/g.test(name)) { return true; } if (options.validNames.indexOf(name) === -1) { if (t.type !== "jslint" && !_.has(options.removed, name)) { error("E001", t, name); return false; } } return true; } function isString(obj) { return Object.prototype.toString.call(obj) === "[object String]"; } function isIdentifier(tkn, value) { if (!tkn) return false; if (!tkn.identifier || tkn.value !== value) return false; return true; } function isReserved(token) { if (!token.reserved) { return false; } var meta = token.meta; if (meta && meta.isFutureReservedWord && state.inES5()) { if (!meta.es5) { return false; } if (meta.strictOnly) { if (!state.option.strict && !state.isStrict()) { return false; } } if (token.isProperty) { return false; } } return true; } function supplant(str, data) { return str.replace(/\{([^{}]*)\}/g, function(a, b) { var r = data[b]; return typeof r === "string" || typeof r === "number" ? r : a; }); } function combine(dest, src) { Object.keys(src).forEach(function(name) { if (_.has(JSHINT.blacklist, name)) return; dest[name] = src[name]; }); } function processenforceall() { if (state.option.enforceall) { for (var enforceopt in options.bool.enforcing) { if (state.option[enforceopt] === undefined && !options.noenforceall[enforceopt]) { state.option[enforceopt] = true; } } for (var relaxopt in options.bool.relaxing) { if (state.option[relaxopt] === undefined) { state.option[relaxopt] = false; } } } } function assume() { processenforceall(); if (!state.option.es3) { combine(predefined, vars.ecmaIdentifiers[5]); } if (state.option.esnext) { combine(predefined, vars.ecmaIdentifiers[6]); } if (state.option.module) { if (!hasParsedCode(state.funct)) { error("E055", state.tokens.next, "module"); } if (!state.inESNext()) { warning("W134", state.tokens.next, "module", 6); } } if (state.option.couch) { combine(predefined, vars.couch); } if (state.option.qunit) { combine(predefined, vars.qunit); } if (state.option.rhino) { combine(predefined, vars.rhino); } if (state.option.shelljs) { combine(predefined, vars.shelljs); combine(predefined, vars.node); } if (state.option.typed) { combine(predefined, vars.typed); } if (state.option.phantom) { combine(predefined, vars.phantom); } if (state.option.prototypejs) { combine(predefined, vars.prototypejs); } if (state.option.node) { combine(predefined, vars.node); combine(predefined, vars.typed); } if (state.option.devel) { combine(predefined, vars.devel); } if (state.option.dojo) { combine(predefined, vars.dojo); } if (state.option.browser) { combine(predefined, vars.browser); combine(predefined, vars.typed); } if (state.option.browserify) { combine(predefined, vars.browser); combine(predefined, vars.typed); combine(predefined, vars.browserify); } if (state.option.nonstandard) { combine(predefined, vars.nonstandard); } if (state.option.jasmine) { combine(predefined, vars.jasmine); } if (state.option.jquery) { combine(predefined, vars.jquery); } if (state.option.mootools) { combine(predefined, vars.mootools); } if (state.option.worker) { combine(predefined, vars.worker); } if (state.option.wsh) { combine(predefined, vars.wsh); } if (state.option.globalstrict && state.option.strict !== false) { state.option.strict = true; } if (state.option.yui) { combine(predefined, vars.yui); } if (state.option.mocha) { combine(predefined, vars.mocha); } } function quit(code, line, chr) { var percentage = Math.floor((line / state.lines.length) * 100); var message = messages.errors[code].desc; throw { name: "JSHintError", line: line, character: chr, message: message + " (" + percentage + "% scanned).", raw: message, code: code }; } function isundef(scope, code, token, a) { if (!state.ignored[code] && state.option.undef !== false) { JSHINT.undefs.push([scope, code, token, a]); } } function removeIgnoredMessages() { var ignored = state.ignoredLines; if (_.isEmpty(ignored)) return; JSHINT.errors = _.reject(JSHINT.errors, function(err) { return ignored[err.line] }); } function warning(code, t, a, b, c, d) { var ch, l, w, msg; if (/^W\d{3}$/.test(code)) { if (state.ignored[code]) return; msg = messages.warnings[code]; } else if (/E\d{3}/.test(code)) { msg = messages.errors[code]; } else if (/I\d{3}/.test(code)) { msg = messages.info[code]; } t = t || state.tokens.next || {}; if (t.id === "(end)") { // `~ t = state.tokens.curr; } l = t.line || 0; ch = t.from || 0; w = { id: "(error)", raw: msg.desc, code: msg.code, evidence: state.lines[l - 1] || "", line: l, character: ch, scope: JSHINT.scope, a: a, b: b, c: c, d: d }; w.reason = supplant(msg.desc, w); JSHINT.errors.push(w); removeIgnoredMessages(); if (JSHINT.errors.length >= state.option.maxerr) quit("E043", l, ch); return w; } function warningAt(m, l, ch, a, b, c, d) { return warning(m, { line: l, from: ch }, a, b, c, d); } function error(m, t, a, b, c, d) { warning(m, t, a, b, c, d); } function errorAt(m, l, ch, a, b, c, d) { return error(m, { line: l, from: ch }, a, b, c, d); } function addInternalSrc(elem, src) { var i; i = { id: "(internal)", elem: elem, value: src }; JSHINT.internals.push(i); return i; } function addlabel(name, opts) { var type = opts.type; var token = opts.token; var isblockscoped = opts.isblockscoped; if (type === "exception") { if (_.has(state.funct["(context)"], name)) { if (state.funct[name] !== true && !state.option.node) { warning("W002", state.tokens.next, name); } } } if (_.has(state.funct, name) && !state.funct["(global)"]) { if (state.funct[name] === true) { if (state.option.latedef) { if ((state.option.latedef === true && _.contains([state.funct[name], type], "unction")) || !_.contains([state.funct[name], type], "unction")) { warning("W003", state.tokens.next, name); } } } else { if ((!state.option.shadow || _.contains([ "inner", "outer" ], state.option.shadow)) && type !== "exception" || state.funct["(blockscope)"].getlabel(name)) { warning("W004", state.tokens.next, name); } } } if (state.funct["(context)"] && _.has(state.funct["(context)"], name) && type !== "function") { if (state.option.shadow === "outer") { warning("W123", state.tokens.next, name); } } if (isblockscoped) { state.funct["(blockscope)"].current.add(name, type, state.tokens.curr); if (state.funct["(blockscope)"].atTop() && exported[name]) { state.tokens.curr.exported = true; } } else { state.funct["(blockscope)"].shadow(name); state.funct[name] = type; if (token) { state.funct["(tokens)"][name] = token; } if (state.funct["(global)"]) { global[name] = state.funct; if (_.has(implied, name)) { if (state.option.latedef) { if ((state.option.latedef === true && _.contains([state.funct[name], type], "unction")) || !_.contains([state.funct[name], type], "unction")) { warning("W003", state.tokens.next, name); } } delete implied[name]; } } else { scope[name] = state.funct; } } } function doOption() { var nt = state.tokens.next; var body = nt.body.match(/(-\s+)?[^\s,:]+(?:\s*:\s*(-\s+)?[^\s,]+)?/g) || []; var predef = {}; if (nt.type === "globals") { body.forEach(function(g, idx) { g = g.split(":"); var key = (g[0] || "").trim(); var val = (g[1] || "").trim(); if (key === "-" || !key.length) { if (idx > 0 && idx === body.length - 1) { return; } error("E002", nt); return; } if (key.charAt(0) === "-") { key = key.slice(1); val = false; JSHINT.blacklist[key] = key; delete predefined[key]; } else { predef[key] = (val === "true"); } }); combine(predefined, predef); for (var key in predef) { if (_.has(predef, key)) { declared[key] = nt; } } } if (nt.type === "exported") { body.forEach(function(e, idx) { if (!e.length) { if (idx > 0 && idx === body.length - 1) { return; } error("E002", nt); return; } exported[e] = true; }); } if (nt.type === "members") { membersOnly = membersOnly || {}; body.forEach(function(m) { var ch1 = m.charAt(0); var ch2 = m.charAt(m.length - 1); if (ch1 === ch2 && (ch1 === "\"" || ch1 === "'")) { m = m .substr(1, m.length - 2) .replace("\\\"", "\""); } membersOnly[m] = false; }); } var numvals = [ "maxstatements", "maxparams", "maxdepth", "maxcomplexity", "maxerr", "maxlen", "indent" ]; if (nt.type === "jshint" || nt.type === "jslint") { body.forEach(function(g) { g = g.split(":"); var key = (g[0] || "").trim(); var val = (g[1] || "").trim(); if (!checkOption(key, nt)) { return; } if (numvals.indexOf(key) >= 0) { if (val !== "false") { val = +val; if (typeof val !== "number" || !isFinite(val) || val <= 0 || Math.floor(val) !== val) { error("E032", nt, g[1].trim()); return; } state.option[key] = val; } else { state.option[key] = key === "indent" ? 4 : false; } return; } if (key === "validthis") { if (state.funct["(global)"]) return void error("E009"); if (val !== "true" && val !== "false") return void error("E002", nt); state.option.validthis = (val === "true"); return; } if (key === "quotmark") { switch (val) { case "true": case "false": state.option.quotmark = (val === "true"); break; case "double": case "single": state.option.quotmark = val; break; default: error("E002", nt); } return; } if (key === "shadow") { switch (val) { case "true": state.option.shadow = true; break; case "outer": state.option.shadow = "outer"; break; case "false": case "inner": state.option.shadow = "inner"; break; default: error("E002", nt); } return; } if (key === "unused") { switch (val) { case "true": state.option.unused = true; break; case "false": state.option.unused = false; break; case "vars": case "strict": state.option.unused = val; break; default: error("E002", nt); } return; } if (key === "latedef") { switch (val) { case "true": state.option.latedef = true; break; case "false": state.option.latedef = false; break; case "nofunc": state.option.latedef = "nofunc"; break; default: error("E002", nt); } return; } if (key === "ignore") { switch (val) { case "start": state.ignoreLinterErrors = true; break; case "end": state.ignoreLinterErrors = false; break; case "line": state.ignoredLines[nt.line] = true; removeIgnoredMessages(); break; default: error("E002", nt); } return; } var match = /^([+-])(W\d{3})$/g.exec(key); if (match) { state.ignored[match[2]] = (match[1] === "-"); return; } var tn; if (val === "true" || val === "false") { if (nt.type === "jslint") { tn = options.renamed[key] || key; state.option[tn] = (val === "true"); if (options.inverted[tn] !== undefined) { state.option[tn] = !state.option[tn]; } } else { state.option[key] = (val === "true"); } if (key === "newcap") { state.option["(explicitNewcap)"] = true; } return; } error("E002", nt); }); assume(); } } function peek(p) { var i = p || 0, j = 0, t; while (j <= i) { t = lookahead[j]; if (!t) { t = lookahead[j] = lex.token(); } j += 1; } if (!t && state.tokens.next.id === "(end)") { return state.tokens.next; } return t; } function peekIgnoreEOL() { var i = 0; var t; do { t = peek(i++); } while (t.id === "(endline)"); return t; } function advance(id, t) { switch (state.tokens.curr.id) { case "(number)": if (state.tokens.next.id === ".") { warning("W005", state.tokens.curr); } break; case "-": if (state.tokens.next.id === "-" || state.tokens.next.id === "--") { warning("W006"); } break; case "+": if (state.tokens.next.id === "+" || state.tokens.next.id === "++") { warning("W007"); } break; } if (id && state.tokens.next.id !== id) { if (t) { if (state.tokens.next.id === "(end)") { error("E019", t, t.id); } else { error("E020", state.tokens.next, id, t.id, t.line, state.tokens.next.value); } } else if (state.tokens.next.type !== "(identifier)" || state.tokens.next.value !== id) { warning("W116", state.tokens.next, id, state.tokens.next.value); } } state.tokens.prev = state.tokens.curr; state.tokens.curr = state.tokens.next; for (;;) { state.tokens.next = lookahead.shift() || lex.token(); if (!state.tokens.next) { // No more tokens left, give up quit("E041", state.tokens.curr.line); } if (state.tokens.next.id === "(end)" || state.tokens.next.id === "(error)") { return; } if (state.tokens.next.check) { state.tokens.next.check(); } if (state.tokens.next.isSpecial) { doOption(); } else { if (state.tokens.next.id !== "(endline)") { break; } } } } function isInfix(token) { return token.infix || (!token.identifier && !token.template && !!token.led); } function isEndOfExpr() { var curr = state.tokens.curr; var next = state.tokens.next; if (next.id === ";" || next.id === "}" || next.id === ":") { return true; } if (isInfix(next) === isInfix(curr) || (curr.id === "yield" && state.inMoz())) { return curr.line !== startLine(next); } return false; } function isBeginOfExpr(prev) { return !prev.left && prev.arity !== "unary"; } function expression(rbp, initial) { var left, isArray = false, isObject = false, isLetExpr = false; state.nameStack.push(); if (!initial && state.tokens.next.value === "let" && peek(0).value === "(") { if (!state.inMoz()) { warning("W118", state.tokens.next, "let expressions"); } isLetExpr = true; state.funct["(blockscope)"].stack(); advance("let"); advance("("); state.tokens.prev.fud(); advance(")"); } if (state.tokens.next.id === "(end)") error("E006", state.tokens.curr); var isDangerous = state.option.asi && state.tokens.prev.line !== startLine(state.tokens.curr) && _.contains(["]", ")"], state.tokens.prev.id) && _.contains(["[", "("], state.tokens.curr.id); if (isDangerous) warning("W014", state.tokens.curr, state.tokens.curr.id); advance(); if (initial) { state.funct["(verb)"] = state.tokens.curr.value; state.tokens.curr.beginsStmt = true; } if (initial === true && state.tokens.curr.fud) { left = state.tokens.curr.fud(); } else { if (state.tokens.curr.nud) { left = state.tokens.curr.nud(); } else { error("E030", state.tokens.curr, state.tokens.curr.id); } while ((rbp < state.tokens.next.lbp || state.tokens.next.type === "(template)") && !isEndOfExpr()) { isArray = state.tokens.curr.value === "Array"; isObject = state.tokens.curr.value === "Object"; if (left && (left.value || (left.first && left.first.value))) { if (left.value !== "new" || (left.first && left.first.value && left.first.value === ".")) { isArray = false; if (left.value !== state.tokens.curr.value) { isObject = false; } } } advance(); if (isArray && state.tokens.curr.id === "(" && state.tokens.next.id === ")") { warning("W009", state.tokens.curr); } if (isObject && state.tokens.curr.id === "(" && state.tokens.next.id === ")") { warning("W010", state.tokens.curr); } if (left && state.tokens.curr.led) { left = state.tokens.curr.led(left); } else { error("E033", state.tokens.curr, state.tokens.curr.id); } } } if (isLetExpr) { state.funct["(blockscope)"].unstack(); } state.nameStack.pop(); return left; } function startLine(token) { return token.startLine || token.line; } function nobreaknonadjacent(left, right) { left = left || state.tokens.curr; right = right || state.tokens.next; if (!state.option.laxbreak && left.line !== startLine(right)) { warning("W014", right, right.value); } } function nolinebreak(t) { t = t || state.tokens.curr; if (t.line !== startLine(state.tokens.next)) { warning("E022", t, t.value); } } function nobreakcomma(left, right) { if (left.line !== startLine(right)) { if (!state.option.laxcomma) { if (comma.first) { warning("I001"); comma.first = false; } warning("W014", left, right.value); } } } function comma(opts) { opts = opts || {}; if (!opts.peek) { nobreakcomma(state.tokens.curr, state.tokens.next); advance(","); } else { nobreakcomma(state.tokens.prev, state.tokens.curr); } if (state.tokens.next.identifier && !(opts.property && state.inES5())) { switch (state.tokens.next.value) { case "break": case "case": case "catch": case "continue": case "default": case "do": case "else": case "finally": case "for": case "if": case "in": case "instanceof": case "return": case "switch": case "throw": case "try": case "var": case "let": case "while": case "with": error("E024", state.tokens.next, state.tokens.next.value); return false; } } if (state.tokens.next.type === "(punctuator)") { switch (state.tokens.next.value) { case "}": case "]": case ",": if (opts.allowTrailing) { return true; } case ")": error("E024", state.tokens.next, state.tokens.next.value); return false; } } return true; } function symbol(s, p) { var x = state.syntax[s]; if (!x || typeof x !== "object") { state.syntax[s] = x = { id: s, lbp: p, value: s }; } return x; } function delim(s) { var x = symbol(s, 0); x.delim = true; return x; } function stmt(s, f) { var x = delim(s); x.identifier = x.reserved = true; x.fud = f; return x; } function blockstmt(s, f) { var x = stmt(s, f); x.block = true; return x; } function reserveName(x) { var c = x.id.charAt(0); if ((c >= "a" && c <= "z") || (c >= "A" && c <= "Z")) { x.identifier = x.reserved = true; } return x; } function prefix(s, f) { var x = symbol(s, 150); reserveName(x); x.nud = (typeof f === "function") ? f : function() { this.arity = "unary"; this.right = expression(150); if (this.id === "++" || this.id === "--") { if (state.option.plusplus) { warning("W016", this, this.id); } else if (this.right && (!this.right.identifier || isReserved(this.right)) && this.right.id !== "." && this.right.id !== "[") { warning("W017", this); } if (this.right && this.right.identifier) { if (state.funct["(blockscope)"].labeltype(this.right.value) === "const") { error("E013", this, this.right.value); } } } return this; }; return x; } function type(s, f) { var x = delim(s); x.type = s; x.nud = f; return x; } function reserve(name, func) { var x = type(name, func); x.identifier = true; x.reserved = true; return x; } function FutureReservedWord(name, meta) { var x = type(name, (meta && meta.nud) || function() { return this; }); meta = meta || {}; meta.isFutureReservedWord = true; x.value = name; x.identifier = true; x.reserved = true; x.meta = meta; return x; } function reservevar(s, v) { return reserve(s, function() { if (typeof v === "function") { v(this); } return this; }); } function infix(s, f, p, w) { var x = symbol(s, p); reserveName(x); x.infix = true; x.led = function(left) { if (!w) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); } if ((s === "in" || s === "instanceof") && left.id === "!") { warning("W018", left, "!"); } if (typeof f === "function") { return f(left, this); } else { this.left = left; this.right = expression(p); return this; } }; return x; } function application(s) { var x = symbol(s, 42); x.led = function(left) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); this.left = left; this.right = doFunction({ type: "arrow", loneArg: left }); return this; }; return x; } function relation(s, f) { var x = symbol(s, 100); x.led = function(left) { nobreaknonadjacent(state.tokens.prev, state.tokens.curr); this.left = left; var right = this.right = expression(100); if (isIdentifier(left, "NaN") || isIdentifier(right, "NaN")) { warning("W019", this); } else if (f) { f.apply(this, [left, right]); } if (!left || !right) { quit("E041", state.tokens.curr.line); } if (left.id === "!") { warning("W018", left, "!"); } if (right.id === "!") { warning("W018", right, "!"); } return this; }; return x; } function isPoorRelation(node) { return node && ((node.type === "(number)" && +node.value === 0) || (node.type === "(string)" && node.value === "") || (node.type === "null" && !state.option.eqnull) || node.type === "true" || node.type === "false" || node.type === "undefined"); } var typeofValues = {}; typeofValues.legacy = [ "xml", "unknown" ]; typeofValues.es3 = [ "undefined", "boolean", "number", "string", "function", "object", ]; typeofValues.es3 = typeofValues.es3.concat(typeofValues.legacy); typeofValues.es6 = typeofValues.es3.concat("symbol"); function isTypoTypeof(left, right, state) { var values; if (state.option.notypeof) return false; if (!left || !right) return false; values = state.inESNext() ? typeofValues.es6 : typeofValues.es3; if (right.type === "(identifier)" && right.value === "typeof" && left.type === "(string)") return !_.contains(values, left.value); return false; } function isGlobalEval(left, state) { var isGlobal = false; if (left.type === "this" && state.funct["(context)"] === null) { isGlobal = true; } else if (left.type === "(identifier)") { if (state.option.node && left.value === "global") { isGlobal = true; } else if (state.option.browser && (left.value === "window" || left.value === "document")) { isGlobal = true; } } return isGlobal; } function findNativePrototype(left) { var natives = [ "Array", "ArrayBuffer", "Boolean", "Collator", "DataView", "Date", "DateTimeFormat", "Error", "EvalError", "Float32Array", "Float64Array", "Function", "Infinity", "Intl", "Int16Array", "Int32Array", "Int8Array", "Iterator", "Number", "NumberFormat", "Object", "RangeError", "ReferenceError", "RegExp", "StopIteration", "String", "SyntaxError", "TypeError", "Uint16Array", "Uint32Array", "Uint8Array", "Uint8ClampedArray", "URIError" ]; function walkPrototype(obj) { if (typeof obj !== "object") return; return obj.right === "prototype" ? obj : walkPrototype(obj.left); } function walkNative(obj) { while (!obj.identifier && typeof obj.left === "object") obj = obj.left; if (obj.identifier && natives.indexOf(obj.value) >= 0) return obj.value; } var prototype = walkPrototype(left); if (prototype) return walkNative(prototype); } function assignop(s, f, p) { var x = infix(s, typeof f === "function" ? f : function(left, that) { that.left = left; if (left) { if (state.option.freeze) { var nativeObject = findNativePrototype(left); if (nativeObject) warning("W121", left, nativeObject); } if (predefined[left.value] === false && scope[left.value]["(global)"] === true) { warning("W020", left); } else if (left["function"]) { warning("W021", left, left.value); } if (state.funct["(blockscope)"].labeltype(left.value) === "const") { error("E013", left, left.value); } if (left.id === ".") { if (!left.left) { warning("E031", that); } else if (left.left.value === "arguments" && !state.isStrict()) { warning("E031", that); } state.nameStack.set(state.tokens.prev); that.right = expression(10); return that; } else if (left.id === "[") { if (state.tokens.curr.left.first) { state.tokens.curr.left.first.forEach(function(t) { if (t && state.funct[t.value] === "const") { error("E013", t, t.value); } }); } else if (!left.left) { warning("E031", that); } else if (left.left.value === "arguments" && !state.isStrict()) { warning("E031", that); } state.nameStack.set(left.right); that.right = expression(10); return that; } else if (left.identifier && !isReserved(left)) { if (state.funct[left.value] === "exception") { warning("W022", left); } state.nameStack.set(left); that.right = expression(10); return that; } if (left === state.syntax["function"]) { warning("W023", state.tokens.curr); } } error("E031", that); }, p); x.exps = true; x.assign = true; return x; } function bitwise(s, f, p) { var x = symbol(s, p); reserveName(x); x.led = (typeof f === "function") ? f : function(left) { if (state.option.bitwise) { warning("W016", this, this.id); } this.left = left; this.right = expression(p); return this; }; return x; } function bitwiseassignop(s) { return assignop(s, function(left, that) { if (state.option.bitwise) { warning("W016", that, that.id); } if (left) { if (left.id === "." || left.id === "[" || (left.identifier && !isReserved(left))) { expression(10); return that; } if (left === state.syntax["function"]) { warning("W023", state.tokens.curr); } return that; } error("E031", that); }, 20); } function suffix(s) { var x = symbol(s, 150); x.led = function(left) { if (state.option.plusplus) { warning("W016", this, this.id); } else if ((!left.identifier || isReserved(left)) && left.id !== "." && left.id !== "[") { warning("W017", this); } if (left && left.identifier) { if (state.funct["(blockscope)"].labeltype(left.value) === "const") { error("E013", this, left.value); } } this.left = left; return this; }; return x; } function optionalidentifier(fnparam, prop, preserve) { if (!state.tokens.next.identifier) { return; } if (!preserve) { advance(); } var curr = state.tokens.curr; var val = state.tokens.curr.value; if (!isReserved(curr)) { return val; } if (prop) { if (state.inES5()) { return val; } } if (fnparam && val === "undefined") { return val; } warning("W024", state.tokens.curr, state.tokens.curr.id); return val; } function identifier(fnparam, prop) { var i = optionalidentifier(fnparam, prop, false); if (i) { return i; } if (state.tokens.next.value === "...") { if (!state.option.esnext) { warning("W119", state.tokens.next, "spread/rest operator"); } advance(); if (checkPunctuators(state.tokens.next, ["..."])) { warning("E024", state.tokens.next, "..."); while (checkPunctuators(state.tokens.next, ["..."])) { advance(); } } if (!state.tokens.next.identifier) { warning("E024", state.tokens.curr, "..."); return; } return identifier(fnparam, prop); } else { error("E030", state.tokens.next, state.tokens.next.value); if (state.tokens.next.id !== ";") { advance(); } } } function reachable(controlToken) { var i = 0, t; if (state.tokens.next.id !== ";" || controlToken.inBracelessBlock) { return; } for (;;) { do { t = peek(i); i += 1; } while (t.id !== "(end)" && t.id === "(comment)"); if (t.reach) { return; } if (t.id !== "(endline)") { if (t.id === "function") { if (state.option.latedef === true) { warning("W026", t); } break; } warning("W027", t, t.value, controlToken.value); break; } } } function parseFinalSemicolon() { if (state.tokens.next.id !== ";") { if (state.tokens.next.isUnclosed) return advance(); if (!state.option.asi) { if (!state.option.lastsemic || state.tokens.next.id !== "}" || startLine(state.tokens.next) !== state.tokens.curr.line) { warningAt("W033", state.tokens.curr.line, state.tokens.curr.character); } } } else { advance(";"); } } function statement() { var i = indent, r, s = scope, t = state.tokens.next; if (t.id === ";") { advance(";"); return; } var res = isReserved(t); if (res && t.meta && t.meta.isFutureReservedWord && peek().id === ":") { warning("W024", t, t.id); res = false; } if (t.value === "module" && t.type === "(identifier)") { if (peek().type === "(identifier)") { if (!state.inESNext()) { warning("W119", state.tokens.curr, "module"); } advance("module"); var name = identifier(); addlabel(name, { type: "unused", token: state.tokens.curr }); advance("from"); advance("(string)"); parseFinalSemicolon(); return; } } if (t.identifier && !res && peek().id === ":") { advance(); advance(":"); scope = Object.create(s); addlabel(t.value, { type: "label" }); if (!state.tokens.next.labelled && state.tokens.next.value !== "{") { warning("W028", state.tokens.next, t.value, state.tokens.next.value); } state.tokens.next.label = t.value; t = state.tokens.next; } if (t.id === "{") { var iscase = (state.funct["(verb)"] === "case" && state.tokens.curr.value === ":"); block(true, true, false, false, iscase); return; } r = expression(0, true); if (r && (!r.identifier || r.value !== "function") && (r.type !== "(punctuator)")) { if (!state.isStrict() && state.option.globalstrict && state.option.strict) { warning("E007"); } } if (!t.block) { if (!state.option.expr && (!r || !r.exps)) { warning("W030", state.tokens.curr); } else if (state.option.nonew && r && r.left && r.id === "(" && r.left.id === "new") { warning("W031", t); } parseFinalSemicolon(); } indent = i; scope = s; return r; } function statements() { var a = [], p; while (!state.tokens.next.reach && state.tokens.next.id !== "(end)") { if (state.tokens.next.id === ";") { p = peek(); if (!p || (p.id !== "(" && p.id !== "[")) { warning("W032"); } advance(";"); } else { a.push(statement()); } } return a; } function directives() { var i, p, pn; while (state.tokens.next.id === "(string)") { p = peek(0); if (p.id === "(endline)") { i = 1; do { pn = peek(i++); } while (pn.id === "(endline)"); if (pn.id === ";") { p = pn; } else if (pn.value === "[" || pn.value === ".") { return; } else if (!state.option.asi || pn.value === "(") { warning("W033", state.tokens.next); } } else if (p.id === "." || p.id === "[") { return; } else if (p.id !== ";") { warning("W033", p); } advance(); if (state.directive[state.tokens.curr.value]) { warning("W034", state.tokens.curr, state.tokens.curr.value); } if (state.tokens.curr.value === "use strict") { if (!state.option["(explicitNewcap)"]) { state.option.newcap = true; } state.option.undef = true; } state.directive[state.tokens.curr.value] = true; if (p.id === ";") { advance(";"); } } } function block(ordinary, stmt, isfunc, isfatarrow, iscase) { var a, b = inblock, old_indent = indent, m, s = scope, t, line, d; inblock = ordinary; if (!ordinary || !state.option.funcscope) scope = Object.create(scope); t = state.tokens.next; var metrics = state.funct["(metrics)"]; metrics.nestedBlockDepth += 1; metrics.verifyMaxNestedBlockDepthPerFunction(); if (state.tokens.next.id === "{") { advance("{"); state.funct["(blockscope)"].stack(); line = state.tokens.curr.line; if (state.tokens.next.id !== "}") { indent += state.option.indent; while (!ordinary && state.tokens.next.from > indent) { indent += state.option.indent; } if (isfunc) { m = {}; for (d in state.directive) { if (_.has(state.directive, d)) { m[d] = state.directive[d]; } } directives(); if (state.option.strict && state.funct["(context)"]["(global)"]) { if (!m["use strict"] && !state.isStrict()) { warning("E007"); } } } a = statements(); metrics.statementCount += a.length; if (isfunc) { state.directive = m; } indent -= state.option.indent; } advance("}", t); state.funct["(blockscope)"].unstack(); indent = old_indent; } else if (!ordinary) { if (isfunc) { m = {}; if (stmt && !isfatarrow && !state.inMoz()) { error("W118", state.tokens.curr, "function closure expressions"); } if (!stmt) { for (d in state.directive) { if (_.has(state.directive, d)) { m[d] = state.directive[d]; } } } expression(10); if (state.option.strict && state.funct["(context)"]["(global)"]) { if (!m["use strict"] && !state.isStrict()) { warning("E007"); } } } else { error("E021", state.tokens.next, "{", state.tokens.next.value); } } else { state.funct["(noblockscopedvar)"] = true; if (!stmt || state.option.curly) { warning("W116", state.tokens.next, "{", state.tokens.next.value); } state.tokens.next.inBracelessBlock = true; indent += state.option.indent; a = [statement()]; indent -= state.option.indent; delete state.funct["(noblockscopedvar)"]; } switch (state.funct["(verb)"]) { case "break": case "continue": case "return": case "throw": if (iscase) { break; } default: state.funct["(verb)"] = null; } if (!ordinary || !state.option.funcscope) scope = s; inblock = b; if (ordinary && state.option.noempty && (!a || a.length === 0)) { warning("W035", state.tokens.prev); } metrics.nestedBlockDepth -= 1; return a; } function countMember(m) { if (membersOnly && typeof membersOnly[m] !== "boolean") { warning("W036", state.tokens.curr, m); } if (typeof member[m] === "number") { member[m] += 1; } else { member[m] = 1; } } function note_implied(tkn) { var name = tkn.value; var desc = Object.getOwnPropertyDescriptor(implied, name); if (!desc) implied[name] = [tkn.line]; else desc.value.push(tkn.line); } type("(number)", function() { return this; }); type("(string)", function() { return this; }); state.syntax["(identifier)"] = { type: "(identifier)", lbp: 0, identifier: true, nud: function() { var v = this.value; var s = scope[v]; var f; var block; if (state.tokens.next.id === "=>") { return this; } block = state.funct["(blockscope)"].getlabel(v); if (typeof s === "function") { s = undefined; } else if (!block && typeof s === "boolean") { f = state.funct; state.funct = functions[0]; addlabel(v, { type: "var" }); s = state.funct; state.funct = f; } if (state.funct === s || block) { switch (block ? block[v]["(type)"] : state.funct[v]) { case "unused": if (block) block[v]["(type)"] = "var"; else state.funct[v] = "var"; break; case "unction": if (block) block[v]["(type)"] = "function"; else state.funct[v] = "function"; this["function"] = true; break; case "const": block[v]["(unused)"] = false; break; case "function": this["function"] = true; break; case "label": warning("W037", state.tokens.curr, v); break; } } else { switch (state.funct[v]) { case "closure": case "function": case "var": case "unused": warning("W038", state.tokens.curr, v); break; case "label": warning("W037", state.tokens.curr, v); break; case "outer": case "global": break; default: if (s === true) { state.funct[v] = true; } else if (s === null) { warning("W039", state.tokens.curr, v); note_implied(state.tokens.curr); } else if (typeof s !== "object") { if (!state.funct["(comparray)"].check(v)) { isundef(state.funct, "W117", state.tokens.curr, v); } if (!state.funct["(global)"]) { state.funct[v] = true; } note_implied(state.tokens.curr); } else { switch (s[v]) { case "function": case "unction": this["function"] = true; s[v] = "closure"; state.funct[v] = s["(global)"] ? "global" : "outer"; break; case "var": case "unused": s[v] = "closure"; state.funct[v] = s["(global)"] ? "global" : "outer"; break; case "closure": state.funct[v] = s["(global)"] ? "global" : "outer"; break; case "label": warning("W037", state.tokens.curr, v); } } } } return this; }, led: function() { error("E033", state.tokens.next, state.tokens.next.value); } }; var baseTemplateSyntax = { lbp: 0, identifier: false, template: true, }; state.syntax["(template)"] = _.extend({ type: "(template)", nud: doTemplateLiteral, led: doTemplateLiteral, noSubst: false }, baseTemplateSyntax); state.syntax["(template middle)"] = _.extend({ type: "(template middle)", middle: true, noSubst: false }, baseTemplateSyntax); state.syntax["(template tail)"] = _.extend({ type: "(template tail)", tail: true, noSubst: false }, baseTemplateSyntax); state.syntax["(no subst template)"] = _.extend({ type: "(template)", nud: doTemplateLiteral, led: doTemplateLiteral, noSubst: true, tail: true // mark as tail, since it's always the last component }, baseTemplateSyntax); type("(regexp)", function() { return this; }); delim("(endline)"); delim("(begin)"); delim("(end)").reach = true; delim("(error)").reach = true; delim("}").reach = true; delim(")"); delim("]"); delim("\"").reach = true; delim("'").reach = true; delim(";"); delim(":").reach = true; delim("#"); reserve("else"); reserve("case").reach = true; reserve("catch"); reserve("default").reach = true; reserve("finally"); reservevar("arguments", function(x) { if (state.isStrict() && state.funct["(global)"]) { warning("E008", x); } }); reservevar("eval"); reservevar("false"); reservevar("Infinity"); reservevar("null"); reservevar("this", function(x) { if (state.isStrict() && !isMethod() && !state.option.validthis && ((state.funct["(statement)"] && state.funct["(name)"].charAt(0) > "Z") || state.funct["(global)"])) { warning("W040", x); } }); reservevar("true"); reservevar("undefined"); assignop("=", "assign", 20); assignop("+=", "assignadd", 20); assignop("-=", "assignsub", 20); assignop("*=", "assignmult", 20); assignop("/=", "assigndiv", 20).nud = function() { error("E014"); }; assignop("%=", "assignmod", 20); bitwiseassignop("&="); bitwiseassignop("|="); bitwiseassignop("^="); bitwiseassignop("<<="); bitwiseassignop(">>="); bitwiseassignop(">>>="); infix(",", function(left, that) { var expr; that.exprs = [left]; if (state.option.nocomma) { warning("W127"); } if (!comma({ peek: true })) { return that; } while (true) { if (!(expr = expression(10))) { break; } that.exprs.push(expr); if (state.tokens.next.value !== "," || !comma()) { break; } } return that; }, 10, true); infix("?", function(left, that) { increaseComplexityCount(); that.left = left; that.right = expression(10); advance(":"); that["else"] = expression(10); return that; }, 30); var orPrecendence = 40; infix("||", function(left, that) { increaseComplexityCount(); that.left = left; that.right = expression(orPrecendence); return that; }, orPrecendence); infix("&&", "and", 50); bitwise("|", "bitor", 70); bitwise("^", "bitxor", 80); bitwise("&", "bitand", 90); relation("==", function(left, right) { var eqnull = state.option.eqnull && (left.value === "null" || right.value === "null"); switch (true) { case !eqnull && state.option.eqeqeq: this.from = this.character; warning("W116", this, "===", "=="); break; case isPoorRelation(left): warning("W041", this, "===", left.value); break; case isPoorRelation(right): warning("W041", this, "===", right.value); break; case isTypoTypeof(right, left, state): warning("W122", this, right.value); break; case isTypoTypeof(left, right, state): warning("W122", this, left.value); break; } return this; }); relation("===", function(left, right) { if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("!=", function(left, right) { var eqnull = state.option.eqnull && (left.value === "null" || right.value === "null"); if (!eqnull && state.option.eqeqeq) { this.from = this.character; warning("W116", this, "!==", "!="); } else if (isPoorRelation(left)) { warning("W041", this, "!==", left.value); } else if (isPoorRelation(right)) { warning("W041", this, "!==", right.value); } else if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("!==", function(left, right) { if (isTypoTypeof(right, left, state)) { warning("W122", this, right.value); } else if (isTypoTypeof(left, right, state)) { warning("W122", this, left.value); } return this; }); relation("<"); relation(">"); relation("<="); relation(">="); bitwise("<<", "shiftleft", 120); bitwise(">>", "shiftright", 120); bitwise(">>>", "shiftrightunsigned", 120); infix("in", "in", 120); infix("instanceof", "instanceof", 120); infix("+", function(left, that) { var right; that.left = left; that.right = right = expression(130); if (left && right && left.id === "(string)" && right.id === "(string)") { left.value += right.value; left.character = right.character; if (!state.option.scripturl && reg.javascriptURL.test(left.value)) { warning("W050", left); } return left; } return that; }, 130); prefix("+", "num"); prefix("+++", function() { warning("W007"); this.arity = "unary"; this.right = expression(150); return this; }); infix("+++", function(left) { warning("W007"); this.left = left; this.right = expression(130); return this; }, 130); infix("-", "sub", 130); prefix("-", "neg"); prefix("---", function() { warning("W006"); this.arity = "unary"; this.right = expression(150); return this; }); infix("---", function(left) { warning("W006"); this.left = left; this.right = expression(130); return this; }, 130); infix("*", "mult", 140); infix("/", "div", 140); infix("%", "mod", 140); suffix("++"); prefix("++", "preinc"); state.syntax["++"].exps = true; suffix("--"); prefix("--", "predec"); state.syntax["--"].exps = true; prefix("delete", function() { var p = expression(10); if (!p) { return this; } if (p.id !== "." && p.id !== "[") { warning("W051"); } this.first = p; if (p.identifier && !state.isStrict()) { p.forgiveUndef = true; } return this; }).exps = true; prefix("~", function() { if (state.option.bitwise) { warning("W016", this, "~"); } this.arity = "unary"; expression(150); return this; }); prefix("...", function() { if (!state.option.esnext) { warning("W119", this, "spread/rest operator"); } if (!state.tokens.next.identifier && state.tokens.next.type !== "(string)" && !checkPunctuators(state.tokens.next, ["[", "("])) { error("E030", state.tokens.next, state.tokens.next.value); } expression(150); return this; }); prefix("!", function() { this.arity = "unary"; this.right = expression(150); if (!this.right) { // '!' followed by nothing? Give up. quit("E041", this.line || 0); } if (bang[this.right.id] === true) { warning("W018", this, "!"); } return this; }); prefix("typeof", (function() { var p = expression(150); this.first = p; if (p.identifier) { p.forgiveUndef = true; } return this; })); prefix("new", function() { var c = expression(155), i; if (c && c.id !== "function") { if (c.identifier) { c["new"] = true; switch (c.value) { case "Number": case "String": case "Boolean": case "Math": case "JSON": warning("W053", state.tokens.prev, c.value); break; case "Symbol": if (state.option.esnext) { warning("W053", state.tokens.prev, c.value); } break; case "Function": if (!state.option.evil) { warning("W054"); } break; case "Date": case "RegExp": case "this": break; default: if (c.id !== "function") { i = c.value.substr(0, 1); if (state.option.newcap && (i < "A" || i > "Z") && !_.has(global, c.value)) { warning("W055", state.tokens.curr); } } } } else { if (c.id !== "." && c.id !== "[" && c.id !== "(") { warning("W056", state.tokens.curr); } } } else { if (!state.option.supernew) warning("W057", this); } if (state.tokens.next.id !== "(" && !state.option.supernew) { warning("W058", state.tokens.curr, state.tokens.curr.value); } this.first = c; return this; }); state.syntax["new"].exps = true; prefix("void").exps = true; infix(".", function(left, that) { var m = identifier(false, true); if (typeof m === "string") { countMember(m); } that.left = left; that.right = m; if (m && m === "hasOwnProperty" && state.tokens.next.value === "=") { warning("W001"); } if (left && left.value === "arguments" && (m === "callee" || m === "caller")) { if (state.option.noarg) warning("W059", left, m); else if (state.isStrict()) error("E008"); } else if (!state.option.evil && left && left.value === "document" && (m === "write" || m === "writeln")) { warning("W060", left); } if (!state.option.evil && (m === "eval" || m === "execScript")) { if (isGlobalEval(left, state)) { warning("W061"); } } return that; }, 160, true); infix("(", function(left, that) { if (state.option.immed && left && !left.immed && left.id === "function") { warning("W062"); } var n = 0; var p = []; if (left) { if (left.type === "(identifier)") { if (left.value.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { if ("Number String Boolean Date Object Error Symbol".indexOf(left.value) === -1) { if (left.value === "Math") { warning("W063", left); } else if (state.option.newcap) { warning("W064", left); } } } } } if (state.tokens.next.id !== ")") { for (;;) { p[p.length] = expression(10); n += 1; if (state.tokens.next.id !== ",") { break; } comma(); } } advance(")"); if (typeof left === "object") { if (state.inES3() && left.value === "parseInt" && n === 1) { warning("W065", state.tokens.curr); } if (!state.option.evil) { if (left.value === "eval" || left.value === "Function" || left.value === "execScript") { warning("W061", left); if (p[0] && [0].id === "(string)") { addInternalSrc(left, p[0].value); } } else if (p[0] && p[0].id === "(string)" && (left.value === "setTimeout" || left.value === "setInterval")) { warning("W066", left); addInternalSrc(left, p[0].value); } else if (p[0] && p[0].id === "(string)" && left.value === "." && left.left.value === "window" && (left.right === "setTimeout" || left.right === "setInterval")) { warning("W066", left); addInternalSrc(left, p[0].value); } } if (!left.identifier && left.id !== "." && left.id !== "[" && left.id !== "(" && left.id !== "&&" && left.id !== "||" && left.id !== "?" && !(state.option.esnext && left["(name)"])) { warning("W067", that); } } that.left = left; return that; }, 155, true).exps = true; prefix("(", function() { var pn = state.tokens.next, pn1, i = -1; var ret, triggerFnExpr, first, last; var parens = 1; var opening = state.tokens.curr; var preceeding = state.tokens.prev; var isNecessary = !state.option.singleGroups; do { if (pn.value === "(") { parens += 1; } else if (pn.value === ")") { parens -= 1; } i += 1; pn1 = pn; pn = peek(i); } while (!(parens === 0 && pn1.value === ")") && pn.value !== ";" && pn.type !== "(end)"); if (state.tokens.next.id === "function") { triggerFnExpr = state.tokens.next.immed = true; } if (pn.value === "=>") { return doFunction({ type: "arrow", parsedOpening: true }); } var exprs = []; if (state.tokens.next.id !== ")") { for (;;) { exprs.push(expression(10)); if (state.tokens.next.id !== ",") { break; } if (state.option.nocomma) { warning("W127"); } comma(); } } advance(")", this); if (state.option.immed && exprs[0] && exprs[0].id === "function") { if (state.tokens.next.id !== "(" && state.tokens.next.id !== "." && state.tokens.next.id !== "[") { warning("W068", this); } } if (!exprs.length) { return; } if (exprs.length > 1) { ret = Object.create(state.syntax[","]); ret.exprs = exprs; first = exprs[0]; last = exprs[exprs.length - 1]; if (!isNecessary) { isNecessary = preceeding.assign || preceeding.delim; } } else { ret = first = last = exprs[0]; if (!isNecessary) { isNecessary = (opening.beginsStmt && (ret.id === "{" || triggerFnExpr || isFunctor(ret))) || (triggerFnExpr && (!isEndOfExpr() || state.tokens.prev.id !== "}")) || (isFunctor(ret) && !isEndOfExpr()) || (ret.id === "{" && preceeding.id === "=>"); } } if (ret) { if (!isNecessary && (first.left || ret.exprs)) { isNecessary = (!isBeginOfExpr(preceeding) && first.lbp <= preceeding.lbp) || (!isEndOfExpr() && last.lbp < state.tokens.next.lbp); } if (!isNecessary) { warning("W126", opening); } ret.paren = true; } return ret; }); application("=>"); infix("[", function(left, that) { var e = expression(10), s; if (e && e.type === "(string)") { if (!state.option.evil && (e.value === "eval" || e.value === "execScript")) { if (isGlobalEval(left, state)) { warning("W061"); } } countMember(e.value); if (!state.option.sub && reg.identifier.test(e.value)) { s = state.syntax[e.value]; if (!s || !isReserved(s)) { warning("W069", state.tokens.prev, e.value); } } } advance("]", that); if (e && e.value === "hasOwnProperty" && state.tokens.next.value === "=") { warning("W001"); } that.left = left; that.right = e; return that; }, 160, true); function comprehensiveArrayExpression() { var res = {}; res.exps = true; state.funct["(comparray)"].stack(); var reversed = false; if (state.tokens.next.value !== "for") { reversed = true; if (!state.inMoz()) { warning("W116", state.tokens.next, "for", state.tokens.next.value); } state.funct["(comparray)"].setState("use"); res.right = expression(10); } advance("for"); if (state.tokens.next.value === "each") { advance("each"); if (!state.inMoz()) { warning("W118", state.tokens.curr, "for each"); } } advance("("); state.funct["(comparray)"].setState("define"); res.left = expression(130); if (_.contains(["in", "of"], state.tokens.next.value)) { advance(); } else { error("E045", state.tokens.curr); } state.funct["(comparray)"].setState("generate"); expression(10); advance(")"); if (state.tokens.next.value === "if") { advance("if"); advance("("); state.funct["(comparray)"].setState("filter"); res.filter = expression(10); advance(")"); } if (!reversed) { state.funct["(comparray)"].setState("use"); res.right = expression(10); } advance("]"); state.funct["(comparray)"].unstack(); return res; } prefix("[", function() { var blocktype = lookupBlockType(); if (blocktype.isCompArray) { if (!state.inESNext()) { warning("W119", state.tokens.curr, "array comprehension"); } return comprehensiveArrayExpression(); } else if (blocktype.isDestAssign && !state.inESNext()) { warning("W104", state.tokens.curr, "destructuring assignment"); } var b = state.tokens.curr.line !== startLine(state.tokens.next); this.first = []; if (b) { indent += state.option.indent; if (state.tokens.next.from === indent + state.option.indent) { indent += state.option.indent; } } while (state.tokens.next.id !== "(end)") { while (state.tokens.next.id === ",") { if (!state.option.elision) { if (!state.inES5()) { warning("W070"); } else { warning("W128"); do { advance(","); } while (state.tokens.next.id === ","); continue; } } advance(","); } if (state.tokens.next.id === "]") { break; } this.first.push(expression(10)); if (state.tokens.next.id === ",") { comma({ allowTrailing: true }); if (state.tokens.next.id === "]" && !state.inES5(true)) { warning("W070", state.tokens.curr); break; } } else { break; } } if (b) { indent -= state.option.indent; } advance("]", this); return this; }); function isMethod() { return state.funct["(statement)"] && state.funct["(statement)"].type === "class" || state.funct["(context)"] && state.funct["(context)"]["(verb)"] === "class"; } function isPropertyName(token) { return token.identifier || token.id === "(string)" || token.id === "(number)"; } function propertyName(preserveOrToken) { var id; var preserve = true; if (typeof preserveOrToken === "object") { id = preserveOrToken; } else { preserve = preserveOrToken; id = optionalidentifier(false, true, preserve); } if (!id) { if (state.tokens.next.id === "(string)") { id = state.tokens.next.value; if (!preserve) { advance(); } } else if (state.tokens.next.id === "(number)") { id = state.tokens.next.value.toString(); if (!preserve) { advance(); } } } else if (typeof id === "object") { if (id.id === "(string)" || id.id === "(identifier)") id = id.value; else if (id.id === "(number)") id = id.value.toString(); } if (id === "hasOwnProperty") { warning("W001"); } return id; } function functionparams(options) { var next; var params = []; var ident; var tokens = []; var t; var pastDefault = false; var pastRest = false; var loneArg = options && options.loneArg; if (loneArg && loneArg.identifier === true) { addlabel(loneArg.value, { type: "unused", token: loneArg }); return [loneArg.value]; } next = state.tokens.next; if (!options || !options.parsedOpening) { advance("("); } if (state.tokens.next.id === ")") { advance(")"); return; } for (;;) { if (_.contains(["{", "["], state.tokens.next.id)) { tokens = destructuringExpression(); for (t in tokens) { t = tokens[t]; if (t.id) { params.push(t.id); addlabel(t.id, { type: "unused", token: t.token }); } } } else { if (checkPunctuators(state.tokens.next, ["..."])) pastRest = true; ident = identifier(true); if (ident) { params.push(ident); addlabel(ident, { type: "unused", token: state.tokens.curr }); } else { while (!checkPunctuators(state.tokens.next, [",", ")"])) advance(); } } if (pastDefault) { if (state.tokens.next.id !== "=") { error("E051", state.tokens.current); } } if (state.tokens.next.id === "=") { if (!state.inESNext()) { warning("W119", state.tokens.next, "default parameters"); } advance("="); pastDefault = true; expression(10); } if (state.tokens.next.id === ",") { if (pastRest) { warning("W131", state.tokens.next); } comma(); } else { advance(")", next); return params; } } } function functor(name, token, scope, overwrites) { var funct = { "(name)" : name, "(breakage)" : 0, "(loopage)" : 0, "(scope)" : scope, "(tokens)" : {}, "(properties)": {}, "(catch)" : false, "(global)" : false, "(line)" : null, "(character)" : null, "(metrics)" : null, "(statement)" : null, "(context)" : null, "(blockscope)": null, "(comparray)" : null, "(generator)" : null, "(params)" : null }; if (token) { _.extend(funct, { "(line)" : token.line, "(character)": token.character, "(metrics)" : createMetrics(token) }); } _.extend(funct, overwrites); if (funct["(context)"]) { funct["(blockscope)"] = funct["(context)"]["(blockscope)"]; funct["(comparray)"] = funct["(context)"]["(comparray)"]; } return funct; } function isFunctor(token) { return "(scope)" in token; } function hasParsedCode(funct) { return funct["(global)"] && !funct["(verb)"]; } function doTemplateLiteral(left) { var ctx = this.context; var noSubst = this.noSubst; var depth = this.depth; if (!noSubst) { while (!end()) { if (!state.tokens.next.template || state.tokens.next.depth > depth) { expression(0); // should probably have different rbp? } else { advance(); } } } return { id: "(template)", type: "(template)", tag: left }; function end() { if (state.tokens.curr.template && state.tokens.curr.tail && state.tokens.curr.context === ctx) return true; var complete = (state.tokens.next.template && state.tokens.next.tail && state.tokens.next.context === ctx); if (complete) advance(); return complete || state.tokens.next.isUnclosed; } } function doFunction(options) { var f, name, statement, classExprBinding, isGenerator, isArrow; var oldOption = state.option; var oldIgnored = state.ignored; var oldScope = scope; if (options) { name = options.name; statement = options.statement; classExprBinding = options.classExprBinding; isGenerator = options.type === "generator"; isArrow = options.type === "arrow"; } state.option = Object.create(state.option); state.ignored = Object.create(state.ignored); scope = Object.create(scope); state.funct = functor(name || state.nameStack.infer(), state.tokens.next, scope, { "(statement)": statement, "(context)": state.funct, "(generator)": isGenerator }); f = state.funct; state.tokens.curr.funct = state.funct; functions.push(state.funct); if (name) { addlabel(name, { type: "function" }); } if (classExprBinding) { addlabel(classExprBinding, { type: "function" }); } state.funct["(params)"] = functionparams(options); state.funct["(metrics)"].verifyMaxParametersPerFunction(state.funct["(params)"]); if (isArrow) { if (!state.option.esnext) { warning("W119", state.tokens.curr, "arrow function syntax (=>)"); } if (!options.loneArg) { advance("=>"); } } block(false, true, true, isArrow); if (!state.option.noyield && isGenerator && state.funct["(generator)"] !== "yielded") { warning("W124", state.tokens.curr); } state.funct["(metrics)"].verifyMaxStatementsPerFunction(); state.funct["(metrics)"].verifyMaxComplexityPerFunction(); state.funct["(unusedOption)"] = state.option.unused; scope = oldScope; state.option = oldOption; state.ignored = oldIgnored; state.funct["(last)"] = state.tokens.curr.line; state.funct["(lastcharacter)"] = state.tokens.curr.character; _.map(Object.keys(state.funct), function(key) { if (key[0] === "(") return; state.funct["(blockscope)"].unshadow(key); }); state.funct = state.funct["(context)"]; return f; } function createMetrics(functionStartToken) { return { statementCount: 0, nestedBlockDepth: -1, ComplexityCount: 1, verifyMaxStatementsPerFunction: function() { if (state.option.maxstatements && this.statementCount > state.option.maxstatements) { warning("W071", functionStartToken, this.statementCount); } }, verifyMaxParametersPerFunction: function(params) { params = params || []; if (_.isNumber(state.option.maxparams) && params.length > state.option.maxparams) { warning("W072", functionStartToken, params.length); } }, verifyMaxNestedBlockDepthPerFunction: function() { if (state.option.maxdepth && this.nestedBlockDepth > 0 && this.nestedBlockDepth === state.option.maxdepth + 1) { warning("W073", null, this.nestedBlockDepth); } }, verifyMaxComplexityPerFunction: function() { var max = state.option.maxcomplexity; var cc = this.ComplexityCount; if (max && cc > max) { warning("W074", functionStartToken, cc); } } }; } function increaseComplexityCount() { state.funct["(metrics)"].ComplexityCount += 1; } function checkCondAssignment(expr) { var id, paren; if (expr) { id = expr.id; paren = expr.paren; if (id === "," && (expr = expr.exprs[expr.exprs.length - 1])) { id = expr.id; paren = paren || expr.paren; } } switch (id) { case "=": case "+=": case "-=": case "*=": case "%=": case "&=": case "|=": case "^=": case "/=": if (!paren && !state.option.boss) { warning("W084"); } } } function checkProperties(props) { if (state.inES5()) { for (var name in props) { if (_.has(props, name) && props[name].setterToken && !props[name].getterToken) { warning("W078", props[name].setterToken); } } } } (function(x) { x.nud = function() { var b, f, i, p, t, isGeneratorMethod = false, nextVal; var props = {}; // All properties, including accessors b = state.tokens.curr.line !== startLine(state.tokens.next); if (b) { indent += state.option.indent; if (state.tokens.next.from === indent + state.option.indent) { indent += state.option.indent; } } for (;;) { if (state.tokens.next.id === "}") { break; } nextVal = state.tokens.next.value; if (state.tokens.next.identifier && (peekIgnoreEOL().id === "," || peekIgnoreEOL().id === "}")) { if (!state.inESNext()) { warning("W104", state.tokens.next, "object short notation"); } i = propertyName(true); saveProperty(props, i, state.tokens.next); expression(10); } else if (peek().id !== ":" && (nextVal === "get" || nextVal === "set")) { advance(nextVal); if (!state.inES5()) { error("E034"); } i = propertyName(); if (!i && !state.inESNext()) { error("E035"); } if (i) { saveAccessor(nextVal, props, i, state.tokens.curr); } t = state.tokens.next; f = doFunction(); p = f["(params)"]; if (nextVal === "get" && i && p) { warning("W076", t, p[0], i); } else if (nextVal === "set" && i && (!p || p.length !== 1)) { warning("W077", t, i); } } else { if (state.tokens.next.value === "*" && state.tokens.next.type === "(punctuator)") { if (!state.inESNext()) { warning("W104", state.tokens.next, "generator functions"); } advance("*"); isGeneratorMethod = true; } else { isGeneratorMethod = false; } if (state.tokens.next.id === "[") { i = computedPropertyName(); state.nameStack.set(i); } else { state.nameStack.set(state.tokens.next); i = propertyName(); saveProperty(props, i, state.tokens.next); if (typeof i !== "string") { break; } } if (state.tokens.next.value === "(") { if (!state.inESNext()) { warning("W104", state.tokens.curr, "concise methods"); } doFunction({ type: isGeneratorMethod ? "generator" : null }); } else { advance(":"); expression(10); } } countMember(i); if (state.tokens.next.id === ",") { comma({ allowTrailing: true, property: true }); if (state.tokens.next.id === ",") { warning("W070", state.tokens.curr); } else if (state.tokens.next.id === "}" && !state.inES5(true)) { warning("W070", state.tokens.curr); } } else { break; } } if (b) { indent -= state.option.indent; } advance("}", this); checkProperties(props); return this; }; x.fud = function() { error("E036", state.tokens.curr); }; }(delim("{"))); function destructuringExpression() { var id, ids; var identifiers = []; if (!state.inESNext()) { warning("W104", state.tokens.curr, "destructuring expression"); } var nextInnerDE = function() { var ident; if (checkPunctuators(state.tokens.next, ["[", "{"])) { ids = destructuringExpression(); for (var id in ids) { id = ids[id]; identifiers.push({ id: id.id, token: id.token }); } } else if (checkPunctuators(state.tokens.next, [","])) { identifiers.push({ id: null, token: state.tokens.curr }); } else if (checkPunctuators(state.tokens.next, ["("])) { advance("("); nextInnerDE(); advance(")"); } else { var is_rest = checkPunctuators(state.tokens.next, ["..."]); ident = identifier(); if (ident) identifiers.push({ id: ident, token: state.tokens.curr }); return is_rest; } return false; }; if (checkPunctuators(state.tokens.next, ["["])) { advance("["); var element_after_rest = false; if (nextInnerDE() && checkPunctuators(state.tokens.next, [","]) && !element_after_rest) { warning("W130", state.tokens.next); element_after_rest = true; } while (!checkPunctuators(state.tokens.next, ["]"])) { advance(","); if (checkPunctuators(state.tokens.next, ["]"])) { break; } if (nextInnerDE() && checkPunctuators(state.tokens.next, [","]) && !element_after_rest) { warning("W130", state.tokens.next); element_after_rest = true; } } advance("]"); } else if (checkPunctuators(state.tokens.next, ["{"])) { advance("{"); id = identifier(); if (checkPunctuators(state.tokens.next, [":"])) { advance(":"); nextInnerDE(); } else { identifiers.push({ id: id, token: state.tokens.curr }); } while (!checkPunctuators(state.tokens.next, ["}"])) { advance(","); if (checkPunctuators(state.tokens.next, ["}"])) { break; } id = identifier(); if (checkPunctuators(state.tokens.next, [":"])) { advance(":"); nextInnerDE(); } else { identifiers.push({ id: id, token: state.tokens.curr }); } } advance("}"); } return identifiers; } function destructuringExpressionMatch(tokens, value) { var first = value.first; if (!first) return; _.zip(tokens, Array.isArray(first) ? first : [ first ]).forEach(function(val) { var token = val[0]; var value = val[1]; if (token && value) token.first = value; else if (token && token.first && !value) warning("W080", token.first, token.first.value); }); } function blockVariableStatement(type, statement, context) { var prefix = context && context.prefix; var inexport = context && context.inexport; var isLet = type === "let"; var isConst = type === "const"; var tokens, lone, value, letblock; if (!state.inESNext()) { warning("W104", state.tokens.curr, type); } if (isLet && state.tokens.next.value === "(") { if (!state.inMoz()) { warning("W118", state.tokens.next, "let block"); } advance("("); state.funct["(blockscope)"].stack(); letblock = true; } else if (state.funct["(noblockscopedvar)"]) { error("E048", state.tokens.curr, isConst ? "Const" : "Let"); } statement.first = []; for (;;) { var names = []; if (_.contains(["{", "["], state.tokens.next.value)) { tokens = destructuringExpression(); lone = false; } else { tokens = [ { id: identifier(), token: state.tokens.curr } ]; lone = true; if (inexport) { exported[state.tokens.curr.value] = true; state.tokens.curr.exported = true; } } for (var t in tokens) { if (tokens.hasOwnProperty(t)) { t = tokens[t]; if (state.inESNext()) { if (state.funct["(blockscope)"].current.labeltype(t.id) === "const") { warning("E011", null, t.id); } } if (state.funct["(global)"]) { if (predefined[t.id] === false) { warning("W079", t.token, t.id); } } if (t.id && !state.funct["(noblockscopedvar)"]) { addlabel(t.id, { type: isConst ? "const" : "unused", token: t.token, isblockscoped: true }); names.push(t.token); } } } statement.first = statement.first.concat(names); if (!prefix && isConst && state.tokens.next.id !== "=") { warning("E012", state.tokens.curr, state.tokens.curr.value); } if (state.tokens.next.id === "=") { advance("="); if (!prefix && state.tokens.next.id === "undefined") { warning("W080", state.tokens.prev, state.tokens.prev.value); } if (!prefix && peek(0).id === "=" && state.tokens.next.identifier) { warning("W120", state.tokens.next, state.tokens.next.value); } value = expression(prefix ? 120 : 10); if (lone) { tokens[0].first = value; } else { destructuringExpressionMatch(names, value); } } if (state.tokens.next.id !== ",") { break; } comma(); } if (letblock) { advance(")"); block(true, true); statement.block = true; state.funct["(blockscope)"].unstack(); } return statement; } var conststatement = stmt("const", function(context) { return blockVariableStatement("const", this, context); }); conststatement.exps = true; var letstatement = stmt("let", function(context) { return blockVariableStatement("let", this, context); }); letstatement.exps = true; var varstatement = stmt("var", function(context) { var prefix = context && context.prefix; var inexport = context && context.inexport; var tokens, lone, value; var implied = context && context.implied; var report = !(context && context.ignore); this.first = []; for (;;) { var names = []; if (_.contains(["{", "["], state.tokens.next.value)) { tokens = destructuringExpression(); lone = false; } else { tokens = [ { id: identifier(), token: state.tokens.curr } ]; lone = true; if (inexport) { exported[state.tokens.curr.value] = true; state.tokens.curr.exported = true; } } for (var t in tokens) { if (tokens.hasOwnProperty(t)) { t = tokens[t]; if (state.inESNext()) { if (state.funct["(blockscope)"].labeltype(t.id) === "const") { warning("E011", null, t.id); } } if (!implied && state.funct["(global)"]) { if (predefined[t.id] === false) { warning("W079", t.token, t.id); } else if (state.option.futurehostile === false) { if ((!state.inES5() && vars.ecmaIdentifiers[5][t.id] === false) || (!state.inESNext() && vars.ecmaIdentifiers[6][t.id] === false)) { warning("W129", t.token, t.id); } } } if (t.id) { if (implied === "for") { var ident = t.token.value; switch (state.funct[ident]) { case "unused": state.funct[ident] = "var"; break; case "var": break; default: if (!state.funct["(blockscope)"].getlabel(ident) && !(scope[ident] || {})[ident]) { if (report) warning("W088", t.token, ident); } } } else { addlabel(t.id, { type: "unused", token: t.token }); } names.push(t.token); } } } if (!prefix && report && state.option.varstmt) { warning("W132", this); } this.first = this.first.concat(names); if (state.tokens.next.id === "=") { state.nameStack.set(state.tokens.curr); advance("="); if (!prefix && report && state.tokens.next.id === "undefined") { warning("W080", state.tokens.prev, state.tokens.prev.value); } if (peek(0).id === "=" && state.tokens.next.identifier) { if (!prefix && report && !state.funct["(params)"] || state.funct["(params)"].indexOf(state.tokens.next.value) === -1) { warning("W120", state.tokens.next, state.tokens.next.value); } } value = expression(prefix ? 120 : 10); if (lone) { tokens[0].first = value; } else { destructuringExpressionMatch(names, value); } } if (state.tokens.next.id !== ",") { break; } comma(); } return this; }); varstatement.exps = true; blockstmt("class", function() { return classdef.call(this, true); }); function classdef(isStatement) { if (!state.inESNext()) { warning("W104", state.tokens.curr, "class"); } if (isStatement) { this.name = identifier(); addlabel(this.name, { type: "unused", token: state.tokens.curr }); } else if (state.tokens.next.identifier && state.tokens.next.value !== "extends") { this.name = identifier(); this.namedExpr = true; } else { this.name = state.nameStack.infer(); } classtail(this); return this; } function classtail(c) { var wasInClassBody = state.inClassBody; if (state.tokens.next.value === "extends") { advance("extends"); c.heritage = expression(10); } state.inClassBody = true; advance("{"); c.body = classbody(c); advance("}"); state.inClassBody = wasInClassBody; } function classbody(c) { var name; var isStatic; var isGenerator; var getset; var props = {}; var staticProps = {}; var computed; for (var i = 0; state.tokens.next.id !== "}"; ++i) { name = state.tokens.next; isStatic = false; isGenerator = false; getset = null; if (name.id === ";") { warning("W032"); advance(";"); continue; } if (name.id === "*") { isGenerator = true; advance("*"); name = state.tokens.next; } if (name.id === "[") { name = computedPropertyName(); computed = true; } else if (isPropertyName(name)) { advance(); computed = false; if (name.identifier && name.value === "static") { if (checkPunctuators(state.tokens.next, ["*"])) { isGenerator = true; advance("*"); } if (isPropertyName(state.tokens.next) || state.tokens.next.id === "[") { computed = state.tokens.next.id === "["; isStatic = true; name = state.tokens.next; if (state.tokens.next.id === "[") { name = computedPropertyName(); } else advance(); } } if (name.identifier && (name.value === "get" || name.value === "set")) { if (isPropertyName(state.tokens.next) || state.tokens.next.id === "[") { computed = state.tokens.next.id === "["; getset = name; name = state.tokens.next; if (state.tokens.next.id === "[") { name = computedPropertyName(); } else advance(); } } } else { warning("W052", state.tokens.next, state.tokens.next.value || state.tokens.next.type); advance(); continue; } if (!checkPunctuators(state.tokens.next, ["("])) { error("E054", state.tokens.next, state.tokens.next.value); while (state.tokens.next.id !== "}" && !checkPunctuators(state.tokens.next, ["("])) { advance(); } if (state.tokens.next.value !== "(") { doFunction({ statement: c }); } } if (!computed) { if (getset) { saveAccessor( getset.value, isStatic ? staticProps : props, name.value, name, true, isStatic); } else { if (name.value === "constructor") { state.nameStack.set(c); } else { state.nameStack.set(name); } saveProperty(isStatic ? staticProps : props, name.value, name, true, isStatic); } } if (getset && name.value === "constructor") { var propDesc = getset.value === "get" ? "class getter method" : "class setter method"; error("E049", name, propDesc, "constructor"); } else if (name.value === "prototype") { error("E049", name, "class method", "prototype"); } propertyName(name); doFunction({ statement: c, type: isGenerator ? "generator" : null, classExprBinding: c.namedExpr ? c.name : null }); } checkProperties(props); } blockstmt("function", function() { var generator = false; if (state.tokens.next.value === "*") { advance("*"); if (state.inESNext({ strict: true })) { generator = true; } else { warning("W119", state.tokens.curr, "function*"); } } if (inblock) { warning("W082", state.tokens.curr); } var i = optionalidentifier(); if (i === undefined) { warning("W025"); } if (state.funct["(blockscope)"].labeltype(i) === "const") { warning("E011", null, i); } addlabel(i, { type: "unction", token: state.tokens.curr }); doFunction({ name: i, statement: this, type: generator ? "generator" : null }); if (state.tokens.next.id === "(" && state.tokens.next.line === state.tokens.curr.line) { error("E039"); } return this; }); prefix("function", function() { var generator = false; if (state.tokens.next.value === "*") { if (!state.inESNext()) { warning("W119", state.tokens.curr, "function*"); } advance("*"); generator = true; } var i = optionalidentifier(); var fn = doFunction({ name: i, type: generator ? "generator" : null }); function isVariable(name) { return name[0] !== "("; } function isLocal(name) { return fn[name] === "var"; } if (!state.option.loopfunc && state.funct["(loopage)"]) { if (_.some(fn, function(val, name) { return isVariable(name) && !isLocal(name); })) { warning("W083"); } } return this; }); blockstmt("if", function() { var t = state.tokens.next; increaseComplexityCount(); state.condition = true; advance("("); var expr = expression(0); checkCondAssignment(expr); var forinifcheck = null; if (state.option.forin && state.forinifcheckneeded) { state.forinifcheckneeded = false; // We only need to analyze the first if inside the loop forinifcheck = state.forinifchecks[state.forinifchecks.length - 1]; if (expr.type === "(punctuator)" && expr.value === "!") { forinifcheck.type = "(negative)"; } else { forinifcheck.type = "(positive)"; } } advance(")", t); state.condition = false; var s = block(true, true); if (forinifcheck && forinifcheck.type === "(negative)") { if (s && s.length === 1 && s[0].type === "(identifier)" && s[0].value === "continue") { forinifcheck.type = "(negative-with-continue)"; } } if (state.tokens.next.id === "else") { advance("else"); if (state.tokens.next.id === "if" || state.tokens.next.id === "switch") { statement(); } else { block(true, true); } } return this; }); blockstmt("try", function() { var b; function doCatch() { var oldScope = scope; var e; advance("catch"); advance("("); scope = Object.create(oldScope); e = state.tokens.next.value; if (state.tokens.next.type !== "(identifier)") { e = null; warning("E030", state.tokens.next, e); } advance(); state.funct = functor("(catch)", state.tokens.next, scope, { "(context)" : state.funct, "(breakage)" : state.funct["(breakage)"], "(loopage)" : state.funct["(loopage)"], "(statement)": false, "(catch)" : true }); if (e) { addlabel(e, { type: "exception" }); } if (state.tokens.next.value === "if") { if (!state.inMoz()) { warning("W118", state.tokens.curr, "catch filter"); } advance("if"); expression(0); } advance(")"); state.tokens.curr.funct = state.funct; functions.push(state.funct); block(false); scope = oldScope; state.funct["(last)"] = state.tokens.curr.line; state.funct["(lastcharacter)"] = state.tokens.curr.character; state.funct = state.funct["(context)"]; } block(true); while (state.tokens.next.id === "catch") { increaseComplexityCount(); if (b && (!state.inMoz())) { warning("W118", state.tokens.next, "multiple catch blocks"); } doCatch(); b = true; } if (state.tokens.next.id === "finally") { advance("finally"); block(true); return; } if (!b) { error("E021", state.tokens.next, "catch", state.tokens.next.value); } return this; }); blockstmt("while", function() { var t = state.tokens.next; state.funct["(breakage)"] += 1; state.funct["(loopage)"] += 1; increaseComplexityCount(); advance("("); checkCondAssignment(expression(0)); advance(")", t); block(true, true); state.funct["(breakage)"] -= 1; state.funct["(loopage)"] -= 1; return this; }).labelled = true; blockstmt("with", function() { var t = state.tokens.next; if (state.isStrict()) { error("E010", state.tokens.curr); } else if (!state.option.withstmt) { warning("W085", state.tokens.curr); } advance("("); expression(0); advance(")", t); block(true, true); return this; }); blockstmt("switch", function() { var t = state.tokens.next; var g = false; var noindent = false; state.funct["(breakage)"] += 1; advance("("); checkCondAssignment(expression(0)); advance(")", t); t = state.tokens.next; advance("{"); if (state.tokens.next.from === indent) noindent = true; if (!noindent) indent += state.option.indent; this.cases = []; for (;;) { switch (state.tokens.next.id) { case "case": switch (state.funct["(verb)"]) { case "yield": case "break": case "case": case "continue": case "return": case "switch": case "throw": break; default: if (!reg.fallsThrough.test(state.lines[state.tokens.next.line - 2])) { warning("W086", state.tokens.curr, "case"); } } advance("case"); this.cases.push(expression(0)); increaseComplexityCount(); g = true; advance(":"); state.funct["(verb)"] = "case"; break; case "default": switch (state.funct["(verb)"]) { case "yield": case "break": case "continue": case "return": case "throw": break; default: if (this.cases.length) { if (!reg.fallsThrough.test(state.lines[state.tokens.next.line - 2])) { warning("W086", state.tokens.curr, "default"); } } } advance("default"); g = true; advance(":"); break; case "}": if (!noindent) indent -= state.option.indent; advance("}", t); state.funct["(breakage)"] -= 1; state.funct["(verb)"] = undefined; return; case "(end)": error("E023", state.tokens.next, "}"); return; default: indent += state.option.indent; if (g) { switch (state.tokens.curr.id) { case ",": error("E040"); return; case ":": g = false; statements(); break; default: error("E025", state.tokens.curr); return; } } else { if (state.tokens.curr.id === ":") { advance(":"); error("E024", state.tokens.curr, ":"); statements(); } else { error("E021", state.tokens.next, "case", state.tokens.next.value); return; } } indent -= state.option.indent; } } }).labelled = true; stmt("debugger", function() { if (!state.option.debug) { warning("W087", this); } return this; }).exps = true; (function() { var x = stmt("do", function() { state.funct["(breakage)"] += 1; state.funct["(loopage)"] += 1; increaseComplexityCount(); this.first = block(true, true); advance("while"); var t = state.tokens.next; advance("("); checkCondAssignment(expression(0)); advance(")", t); state.funct["(breakage)"] -= 1; state.funct["(loopage)"] -= 1; return this; }); x.labelled = true; x.exps = true; }()); blockstmt("for", function() { var s, t = state.tokens.next; var letscope = false; var foreachtok = null; if (t.value === "each") { foreachtok = t; advance("each"); if (!state.inMoz()) { warning("W118", state.tokens.curr, "for each"); } } state.funct["(breakage)"] += 1; state.funct["(loopage)"] += 1; increaseComplexityCount(); advance("("); var nextop; // contains the token of the "in" or "of" operator var i = 0; var inof = ["in", "of"]; var level = 0; // BindingPattern "level" --- level 0 === no BindingPattern var comma; // First comma punctuator at level 0 var initializer; // First initializer at level 0 if (checkPunctuators(state.tokens.next, ["{", "["])) ++level; do { nextop = peek(i); ++i; if (checkPunctuators(nextop, ["{", "["])) ++level; else if (checkPunctuators(nextop, ["}", "]"])) --level; if (level < 0) break; if (level === 0) { if (!comma && checkPunctuators(nextop, [","])) comma = nextop; else if (!initializer && checkPunctuators(nextop, ["="])) initializer = nextop; } } while (level > 0 || !_.contains(inof, nextop.value) && nextop.value !== ";" && nextop.type !== "(end)"); // Is this a JSCS bug? This looks really weird. if (_.contains(inof, nextop.value)) { if (!state.inESNext() && nextop.value === "of") { error("W104", nextop, "for of"); } var ok = !(initializer || comma); if (initializer) { error("W133", comma, nextop.value, "initializer is forbidden"); } if (comma) { error("W133", comma, nextop.value, "more than one ForBinding"); } if (state.tokens.next.id === "var") { advance("var"); state.tokens.curr.fud({ prefix: true }); } else if (state.tokens.next.id === "let" || state.tokens.next.id === "const") { advance(state.tokens.next.id); letscope = true; state.funct["(blockscope)"].stack(); state.tokens.curr.fud({ prefix: true }); } else { Object.create(varstatement).fud({ prefix: true, implied: "for", ignore: !ok }); } advance(nextop.value); expression(20); advance(")", t); if (nextop.value === "in" && state.option.forin) { state.forinifcheckneeded = true; if (state.forinifchecks === undefined) { state.forinifchecks = []; } state.forinifchecks.push({ type: "(none)" }); } s = block(true, true); if (nextop.value === "in" && state.option.forin) { if (state.forinifchecks && state.forinifchecks.length > 0) { var check = state.forinifchecks.pop(); if (// No if statement or not the first statement in loop body s && s.length > 0 && (typeof s[0] !== "object" || s[0].value !== "if") || check.type === "(positive)" && s.length > 1 || check.type === "(negative)") { warning("W089", this); } } state.forinifcheckneeded = false; } state.funct["(breakage)"] -= 1; state.funct["(loopage)"] -= 1; } else { if (foreachtok) { error("E045", foreachtok); } if (state.tokens.next.id !== ";") { if (state.tokens.next.id === "var") { advance("var"); state.tokens.curr.fud(); } else if (state.tokens.next.id === "let") { advance("let"); letscope = true; state.funct["(blockscope)"].stack(); state.tokens.curr.fud(); } else { for (;;) { expression(0, "for"); if (state.tokens.next.id !== ",") { break; } comma(); } } } nolinebreak(state.tokens.curr); advance(";"); if (state.tokens.next.id !== ";") { checkCondAssignment(expression(0)); } nolinebreak(state.tokens.curr); advance(";"); if (state.tokens.next.id === ";") { error("E021", state.tokens.next, ")", ";"); } if (state.tokens.next.id !== ")") { for (;;) { expression(0, "for"); if (state.tokens.next.id !== ",") { break; } comma(); } } advance(")", t); block(true, true); state.funct["(breakage)"] -= 1; state.funct["(loopage)"] -= 1; } if (letscope) { state.funct["(blockscope)"].unstack(); } return this; }).labelled = true; stmt("break", function() { var v = state.tokens.next.value; if (state.funct["(breakage)"] === 0) warning("W052", state.tokens.next, this.value); if (!state.option.asi) nolinebreak(this); if (state.tokens.next.id !== ";" && !state.tokens.next.reach) { if (state.tokens.curr.line === startLine(state.tokens.next)) { if (state.funct[v] !== "label") { warning("W090", state.tokens.next, v); } else if (scope[v] !== state.funct) { warning("W091", state.tokens.next, v); } this.first = state.tokens.next; advance(); } } reachable(this); return this; }).exps = true; stmt("continue", function() { var v = state.tokens.next.value; if (state.funct["(breakage)"] === 0) warning("W052", state.tokens.next, this.value); if (!state.option.asi) nolinebreak(this); if (state.tokens.next.id !== ";" && !state.tokens.next.reach) { if (state.tokens.curr.line === startLine(state.tokens.next)) { if (state.funct[v] !== "label") { warning("W090", state.tokens.next, v); } else if (scope[v] !== state.funct) { warning("W091", state.tokens.next, v); } this.first = state.tokens.next; advance(); } } else if (!state.funct["(loopage)"]) { warning("W052", state.tokens.next, this.value); } reachable(this); return this; }).exps = true; stmt("return", function() { if (this.line === startLine(state.tokens.next)) { if (state.tokens.next.id !== ";" && !state.tokens.next.reach) { this.first = expression(0); if (this.first && this.first.type === "(punctuator)" && this.first.value === "=" && !this.first.paren && !state.option.boss) { warningAt("W093", this.first.line, this.first.character); } } } else { if (state.tokens.next.type === "(punctuator)" && ["[", "{", "+", "-"].indexOf(state.tokens.next.value) > -1) { nolinebreak(this); // always warn (Line breaking error) } } reachable(this); return this; }).exps = true; (function(x) { x.exps = true; x.lbp = 25; }(prefix("yield", function() { var prev = state.tokens.prev; if (state.inESNext(true) && !state.funct["(generator)"]) { if (!("(catch)" === state.funct["(name)"] && state.funct["(context)"]["(generator)"])) { error("E046", state.tokens.curr, "yield"); } } else if (!state.inESNext()) { warning("W104", state.tokens.curr, "yield"); } state.funct["(generator)"] = "yielded"; var delegatingYield = false; if (state.tokens.next.value === "*") { delegatingYield = true; advance("*"); } if (this.line === startLine(state.tokens.next) || !state.inMoz()) { if (delegatingYield || (state.tokens.next.id !== ";" && !state.tokens.next.reach && state.tokens.next.nud)) { nobreaknonadjacent(state.tokens.curr, state.tokens.next); this.first = expression(10); if (this.first.type === "(punctuator)" && this.first.value === "=" && !this.first.paren && !state.option.boss) { warningAt("W093", this.first.line, this.first.character); } } if (state.inMoz() && state.tokens.next.id !== ")" && (prev.lbp > 30 || (!prev.assign && !isEndOfExpr()) || prev.id === "yield")) { error("E050", this); } } else if (!state.option.asi) { nolinebreak(this); // always warn (Line breaking error) } return this; }))); stmt("throw", function() { nolinebreak(this); this.first = expression(20); reachable(this); return this; }).exps = true; stmt("import", function() { if (!state.inESNext()) { warning("W119", state.tokens.curr, "import"); } if (state.tokens.next.type === "(string)") { advance("(string)"); return this; } if (state.tokens.next.identifier) { this.name = identifier(); addlabel(this.name, { type: "unused", token: state.tokens.curr }); if (state.tokens.next.value === ",") { advance(","); } else { advance("from"); advance("(string)"); return this; } } if (state.tokens.next.id === "*") { advance("*"); advance("as"); if (state.tokens.next.identifier) { this.name = identifier(); addlabel(this.name, { type: "unused", token: state.tokens.curr }); } } else { advance("{"); for (;;) { if (state.tokens.next.value === "}") { advance("}"); break; } var importName; if (state.tokens.next.type === "default") { importName = "default"; advance("default"); } else { importName = identifier(); } if (state.tokens.next.value === "as") { advance("as"); importName = identifier(); } addlabel(importName, { type: "unused", token: state.tokens.curr }); if (state.tokens.next.value === ",") { advance(","); } else if (state.tokens.next.value === "}") { advance("}"); break; } else { error("E024", state.tokens.next, state.tokens.next.value); break; } } } advance("from"); advance("(string)"); return this; }).exps = true; stmt("export", function() { var ok = true; var token; var identifier; if (!state.inESNext()) { warning("W119", state.tokens.curr, "export"); ok = false; } if (!state.funct["(global)"] || !state.funct["(blockscope)"].atTop()) { error("E053", state.tokens.curr); ok = false; } if (state.tokens.next.value === "*") { advance("*"); advance("from"); advance("(string)"); return this; } if (state.tokens.next.type === "default") { state.nameStack.set(state.tokens.next); advance("default"); if (state.tokens.next.id === "function" || state.tokens.next.id === "class") { this.block = true; } token = peek(); expression(10); if (state.tokens.next.id === "class") { identifier = token.name; } else { identifier = token.value; } addlabel(identifier, { type: "function", token: token }); return this; } if (state.tokens.next.value === "{") { advance("{"); var exportedTokens = []; for (;;) { if (!state.tokens.next.identifier) { error("E030", state.tokens.next, state.tokens.next.value); } advance(); state.tokens.curr.exported = ok; exportedTokens.push(state.tokens.curr); if (state.tokens.next.value === "as") { advance("as"); if (!state.tokens.next.identifier) { error("E030", state.tokens.next, state.tokens.next.value); } advance(); } if (state.tokens.next.value === ",") { advance(","); } else if (state.tokens.next.value === "}") { advance("}"); break; } else { error("E024", state.tokens.next, state.tokens.next.value); break; } } if (state.tokens.next.value === "from") { advance("from"); advance("(string)"); } else if (ok) { exportedTokens.forEach(function(token) { if (!state.funct[token.value]) { isundef(state.funct, "W117", token, token.value); } exported[token.value] = true; state.funct["(blockscope)"].setExported(token.value); }); } return this; } if (state.tokens.next.id === "var") { advance("var"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "let") { advance("let"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "const") { advance("const"); state.tokens.curr.fud({ inexport:true }); } else if (state.tokens.next.id === "function") { this.block = true; advance("function"); exported[state.tokens.next.value] = ok; state.tokens.next.exported = true; state.syntax["function"].fud(); } else if (state.tokens.next.id === "class") { this.block = true; advance("class"); exported[state.tokens.next.value] = ok; state.tokens.next.exported = true; state.syntax["class"].fud(); } else { error("E024", state.tokens.next, state.tokens.next.value); } return this; }).exps = true; FutureReservedWord("abstract"); FutureReservedWord("boolean"); FutureReservedWord("byte"); FutureReservedWord("char"); FutureReservedWord("class", { es5: true, nud: classdef }); FutureReservedWord("double"); FutureReservedWord("enum", { es5: true }); FutureReservedWord("export", { es5: true }); FutureReservedWord("extends", { es5: true }); FutureReservedWord("final"); FutureReservedWord("float"); FutureReservedWord("goto"); FutureReservedWord("implements", { es5: true, strictOnly: true }); FutureReservedWord("import", { es5: true }); FutureReservedWord("int"); FutureReservedWord("interface", { es5: true, strictOnly: true }); FutureReservedWord("long"); FutureReservedWord("native"); FutureReservedWord("package", { es5: true, strictOnly: true }); FutureReservedWord("private", { es5: true, strictOnly: true }); FutureReservedWord("protected", { es5: true, strictOnly: true }); FutureReservedWord("public", { es5: true, strictOnly: true }); FutureReservedWord("short"); FutureReservedWord("static", { es5: true, strictOnly: true }); FutureReservedWord("super", { es5: true }); FutureReservedWord("synchronized"); FutureReservedWord("transient"); FutureReservedWord("volatile"); var lookupBlockType = function() { var pn, pn1; var i = -1; var bracketStack = 0; var ret = {}; if (checkPunctuators(state.tokens.curr, ["[", "{"])) bracketStack += 1; do { pn = (i === -1) ? state.tokens.next : peek(i); pn1 = peek(i + 1); i = i + 1; if (checkPunctuators(pn, ["[", "{"])) { bracketStack += 1; } else if (checkPunctuators(pn, ["]", "}"])) { bracketStack -= 1; } if (pn.identifier && pn.value === "for" && bracketStack === 1) { ret.isCompArray = true; ret.notJson = true; break; } if (checkPunctuators(pn, ["}", "]"]) && bracketStack === 0) { if (pn1.value === "=") { ret.isDestAssign = true; ret.notJson = true; break; } else if (pn1.value === ".") { ret.notJson = true; break; } } if (pn.value === ";") { ret.isBlock = true; ret.notJson = true; } } while (bracketStack > 0 && pn.id !== "(end)"); return ret; }; function saveProperty(props, name, tkn, isClass, isStatic) { var msg = ["key", "class method", "static class method"]; msg = msg[(isClass || false) + (isStatic || false)]; if (tkn.identifier) { name = tkn.value; } if (props[name] && _.has(props, name)) { warning("W075", state.tokens.next, msg, name); } else { props[name] = {}; } props[name].basic = true; props[name].basictkn = tkn; } function saveAccessor(accessorType, props, name, tkn, isClass, isStatic) { var flagName = accessorType === "get" ? "getterToken" : "setterToken"; var msg = ""; if (isClass) { if (isStatic) { msg += "static "; } msg += accessorType + "ter method"; } else { msg = "key"; } state.tokens.curr.accessorType = accessorType; state.nameStack.set(tkn); if (props[name] && _.has(props, name)) { if (props[name].basic || props[name][flagName]) { warning("W075", state.tokens.next, msg, name); } } else { props[name] = {}; } props[name][flagName] = tkn; } function computedPropertyName() { advance("["); if (!state.option.esnext) { warning("W119", state.tokens.curr, "computed property names"); } var value = expression(10); advance("]"); return value; } function checkPunctuators(token, values) { return token.type === "(punctuator)" && _.contains(values, token.value); } function destructuringAssignOrJsonValue() { var block = lookupBlockType(); if (block.notJson) { if (!state.inESNext() && block.isDestAssign) { warning("W104", state.tokens.curr, "destructuring assignment"); } statements(); } else { state.option.laxbreak = true; state.jsonMode = true; jsonValue(); } } var arrayComprehension = function() { var CompArray = function() { this.mode = "use"; this.variables = []; }; var _carrays = []; var _current; function declare(v) { var l = _current.variables.filter(function(elt) { if (elt.value === v) { elt.undef = false; return v; } }).length; return l !== 0; } function use(v) { var l = _current.variables.filter(function(elt) { if (elt.value === v && !elt.undef) { if (elt.unused === true) { elt.unused = false; } return v; } }).length; return (l === 0); } return { stack: function() { _current = new CompArray(); _carrays.push(_current); }, unstack: function() { _current.variables.filter(function(v) { if (v.unused) warning("W098", v.token, v.raw_text || v.value); if (v.undef) isundef(v.state.funct, "W117", v.token, v.value); }); _carrays.splice(-1, 1); _current = _carrays[_carrays.length - 1]; }, setState: function(s) { if (_.contains(["use", "define", "generate", "filter"], s)) _current.mode = s; }, check: function(v) { if (!_current) { return; } if (_current && _current.mode === "use") { if (use(v)) { _current.variables.push({ funct: state.funct, token: state.tokens.curr, value: v, undef: true, unused: false }); } return true; } else if (_current && _current.mode === "define") { if (!declare(v)) { _current.variables.push({ funct: state.funct, token: state.tokens.curr, value: v, undef: false, unused: true }); } return true; } else if (_current && _current.mode === "generate") { isundef(state.funct, "W117", state.tokens.curr, v); return true; } else if (_current && _current.mode === "filter") { if (use(v)) { isundef(state.funct, "W117", state.tokens.curr, v); } return true; } return false; } }; }; function jsonValue() { function jsonObject() { var o = {}, t = state.tokens.next; advance("{"); if (state.tokens.next.id !== "}") { for (;;) { if (state.tokens.next.id === "(end)") { error("E026", state.tokens.next, t.line); } else if (state.tokens.next.id === "}") { warning("W094", state.tokens.curr); break; } else if (state.tokens.next.id === ",") { error("E028", state.tokens.next); } else if (state.tokens.next.id !== "(string)") { warning("W095", state.tokens.next, state.tokens.next.value); } if (o[state.tokens.next.value] === true) { warning("W075", state.tokens.next, "key", state.tokens.next.value); } else if ((state.tokens.next.value === "__proto__" && !state.option.proto) || (state.tokens.next.value === "__iterator__" && !state.option.iterator)) { warning("W096", state.tokens.next, state.tokens.next.value); } else { o[state.tokens.next.value] = true; } advance(); advance(":"); jsonValue(); if (state.tokens.next.id !== ",") { break; } advance(","); } } advance("}"); } function jsonArray() { var t = state.tokens.next; advance("["); if (state.tokens.next.id !== "]") { for (;;) { if (state.tokens.next.id === "(end)") { error("E027", state.tokens.next, t.line); } else if (state.tokens.next.id === "]") { warning("W094", state.tokens.curr); break; } else if (state.tokens.next.id === ",") { error("E028", state.tokens.next); } jsonValue(); if (state.tokens.next.id !== ",") { break; } advance(","); } } advance("]"); } switch (state.tokens.next.id) { case "{": jsonObject(); break; case "[": jsonArray(); break; case "true": case "false": case "null": case "(number)": case "(string)": advance(); break; case "-": advance("-"); advance("(number)"); break; default: error("E003", state.tokens.next); } } var warnUnused = function(name, tkn, type, unused_opt) { var line = tkn.line; var chr = tkn.from; var raw_name = tkn.raw_text || name; if (unused_opt === undefined) { unused_opt = state.option.unused; } if (unused_opt === true) { unused_opt = "last-param"; } var warnable_types = { "vars": ["var"], "last-param": ["var", "param"], "strict": ["var", "param", "last-param"] }; if (unused_opt) { if (warnable_types[unused_opt] && warnable_types[unused_opt].indexOf(type) !== -1) { if (!tkn.exported) { warningAt("W098", line, chr, raw_name); } } } unuseds.push({ name: name, line: line, character: chr }); }; var blockScope = function() { var _current = {}; var _variables = [_current]; function _checkBlockLabels() { for (var t in _current) { var label = _current[t], labelType = label["(type)"]; if (labelType === "unused" || (labelType === "const" && label["(unused)"])) { if (state.option.unused) { var tkn = _current[t]["(token)"]; if (tkn.exported) { continue; } warnUnused(t, tkn, "var"); } } } } function _getLabel(l) { for (var i = _variables.length - 1 ; i >= 0; --i) { if (_.has(_variables[i], l) && !_variables[i][l]["(shadowed)"]) { return _variables[i]; } } } return { stack: function() { _current = {}; _variables.push(_current); }, unstack: function() { _checkBlockLabels(); _variables.splice(_variables.length - 1, 1); _current = _.last(_variables); }, getlabel: _getLabel, labeltype: function(l) { var block = _getLabel(l); if (block) { return block[l]["(type)"]; } return null; }, shadow: function(name) { for (var i = _variables.length - 1; i >= 0; i--) { if (_.has(_variables[i], name)) { _variables[i][name]["(shadowed)"] = true; } } }, unshadow: function(name) { for (var i = _variables.length - 1; i >= 0; i--) { if (_.has(_variables[i], name)) { _variables[i][name]["(shadowed)"] = false; } } }, atTop: function() { return _variables.length === 1; }, setExported: function(id) { if (state.funct["(blockscope)"].atTop()) { var item = _current[id]; if (item && item["(token)"]) { item["(token)"].exported = true; } } }, current: { labeltype: function(t) { if (_current[t]) { return _current[t]["(type)"]; } return null; }, has: function(t) { return _.has(_current, t); }, add: function(t, type, tok) { _current[t] = { "(type)" : type, "(token)": tok, "(shadowed)": false, "(unused)": true }; } } }; }; var escapeRegex = function(str) { return str.replace(/[-\/\\^$*+?.()|[\]{}]/g, "\\$&"); }; var itself = function(s, o, g) { var i, k, x, reIgnoreStr, reIgnore; var optionKeys; var newOptionObj = {}; var newIgnoredObj = {}; o = _.clone(o); state.reset(); if (o && o.scope) { JSHINT.scope = o.scope; } else { JSHINT.errors = []; JSHINT.undefs = []; JSHINT.internals = []; JSHINT.blacklist = {}; JSHINT.scope = "(main)"; } predefined = Object.create(null); combine(predefined, vars.ecmaIdentifiers[3]); combine(predefined, vars.reservedVars); combine(predefined, g || {}); declared = Object.create(null); exported = Object.create(null); function each(obj, cb) { if (!obj) return; if (!Array.isArray(obj) && typeof obj === "object") obj = Object.keys(obj); obj.forEach(cb); } if (o) { each(o.predef || null, function(item) { var slice, prop; if (item[0] === "-") { slice = item.slice(1); JSHINT.blacklist[slice] = slice; delete predefined[slice]; } else { prop = Object.getOwnPropertyDescriptor(o.predef, item); predefined[item] = prop ? prop.value : false; } }); each(o.exported || null, function(item) { exported[item] = true; }); delete o.predef; delete o.exported; optionKeys = Object.keys(o); for (x = 0; x < optionKeys.length; x++) { if (/^-W\d{3}$/g.test(optionKeys[x])) { newIgnoredObj[optionKeys[x].slice(1)] = true; } else { var optionKey = optionKeys[x]; newOptionObj[optionKey] = o[optionKey]; if (optionKey === "es5") { if (o[optionKey]) { warning("I003"); } } if (optionKeys[x] === "newcap" && o[optionKey] === false) newOptionObj["(explicitNewcap)"] = true; } } } state.option = newOptionObj; state.ignored = newIgnoredObj; state.option.indent = state.option.indent || 4; state.option.maxerr = state.option.maxerr || 50; indent = 1; global = Object.create(predefined); scope = global; state.funct = functor("(global)", null, scope, { "(global)" : true, "(blockscope)": blockScope(), "(comparray)" : arrayComprehension(), "(metrics)" : createMetrics(state.tokens.next) }); functions = [state.funct]; urls = []; stack = null; member = {}; membersOnly = null; implied = {}; inblock = false; lookahead = []; unuseds = []; if (!isString(s) && !Array.isArray(s)) { errorAt("E004", 0); return false; } api = { get isJSON() { return state.jsonMode; }, getOption: function(name) { return state.option[name] || null; }, getCache: function(name) { return state.cache[name]; }, setCache: function(name, value) { state.cache[name] = value; }, warn: function(code, data) { warningAt.apply(null, [ code, data.line, data.char ].concat(data.data)); }, on: function(names, listener) { names.split(" ").forEach(function(name) { emitter.on(name, listener); }.bind(this)); } }; emitter.removeAllListeners(); (extraModules || []).forEach(function(func) { func(api); }); state.tokens.prev = state.tokens.curr = state.tokens.next = state.syntax["(begin)"]; if (o && o.ignoreDelimiters) { if (!Array.isArray(o.ignoreDelimiters)) { o.ignoreDelimiters = [o.ignoreDelimiters]; } o.ignoreDelimiters.forEach(function(delimiterPair) { if (!delimiterPair.start || !delimiterPair.end) return; reIgnoreStr = escapeRegex(delimiterPair.start) + "[\\s\\S]*?" + escapeRegex(delimiterPair.end); reIgnore = new RegExp(reIgnoreStr, "ig"); s = s.replace(reIgnore, function(match) { return match.replace(/./g, " "); }); }); } lex = new Lexer(s); lex.on("warning", function(ev) { warningAt.apply(null, [ ev.code, ev.line, ev.character].concat(ev.data)); }); lex.on("error", function(ev) { errorAt.apply(null, [ ev.code, ev.line, ev.character ].concat(ev.data)); }); lex.on("fatal", function(ev) { quit("E041", ev.line, ev.from); }); lex.on("Identifier", function(ev) { emitter.emit("Identifier", ev); }); lex.on("String", function(ev) { emitter.emit("String", ev); }); lex.on("Number", function(ev) { emitter.emit("Number", ev); }); lex.start(); for (var name in o) { if (_.has(o, name)) { checkOption(name, state.tokens.curr); } } assume(); combine(predefined, g || {}); comma.first = true; try { advance(); switch (state.tokens.next.id) { case "{": case "[": destructuringAssignOrJsonValue(); break; default: directives(); if (state.isStrict()) { if (!state.option.globalstrict) { if (!(state.option.module || state.option.node || state.option.phantom || state.option.browserify)) { warning("W097", state.tokens.prev); } } } statements(); } if (state.tokens.next.id !== "(end)") { quit("E041", state.tokens.curr.line); } state.funct["(blockscope)"].unstack(); var markDefined = function(name, context) { do { if (typeof context[name] === "string") { if (context[name] === "unused") context[name] = "var"; else if (context[name] === "unction") context[name] = "closure"; return true; } context = context["(context)"]; } while (context); return false; }; var clearImplied = function(name, line) { if (!implied[name]) return; var newImplied = []; for (var i = 0; i < implied[name].length; i += 1) { if (implied[name][i] !== line) newImplied.push(implied[name][i]); } if (newImplied.length === 0) delete implied[name]; else implied[name] = newImplied; }; var checkUnused = function(func, key) { var type = func[key]; var tkn = func["(tokens)"][key]; if (key.charAt(0) === "(") return; if (type !== "unused" && type !== "unction") return; if (func["(params)"] && func["(params)"].indexOf(key) !== -1) return; if (func["(global)"] && _.has(exported, key)) return; warnUnused(key, tkn, "var"); }; for (i = 0; i < JSHINT.undefs.length; i += 1) { k = JSHINT.undefs[i].slice(0); if (markDefined(k[2].value, k[0]) || k[2].forgiveUndef) { clearImplied(k[2].value, k[2].line); } else if (state.option.undef) { warning.apply(warning, k.slice(1)); } } functions.forEach(function(func) { if (func["(unusedOption)"] === false) { return; } for (var key in func) { if (_.has(func, key)) { checkUnused(func, key); } } if (!func["(params)"]) return; var params = func["(params)"].slice(); var param = params.pop(); var type, unused_opt; while (param) { type = func[param]; unused_opt = func["(unusedOption)"] || state.option.unused; unused_opt = unused_opt === true ? "last-param" : unused_opt; if (param === "undefined") return; if (type === "unused" || type === "unction") { warnUnused(param, func["(tokens)"][param], "param", func["(unusedOption)"]); } else if (unused_opt === "last-param") { return; } param = params.pop(); } }); for (var key in declared) { if (_.has(declared, key) && !_.has(global, key) && !_.has(exported, key)) { warnUnused(key, declared[key], "var"); } } } catch (err) { if (err && err.name === "JSHintError") { var nt = state.tokens.next || {}; JSHINT.errors.push({ scope : "(main)", raw : err.raw, code : err.code, reason : err.message, line : err.line || nt.line, character : err.character || nt.from }, null); } else { throw err; } } if (JSHINT.scope === "(main)") { o = o || {}; for (i = 0; i < JSHINT.internals.length; i += 1) { k = JSHINT.internals[i]; o.scope = k.elem; itself(k.value, o, g); } } return JSHINT.errors.length === 0; }; itself.addModule = function(func) { extraModules.push(func); }; itself.addModule(style.register); itself.data = function() { var data = { functions: [], options: state.option }; var implieds = []; var members = []; var fu, f, i, j, n, globals; if (itself.errors.length) { data.errors = itself.errors; } if (state.jsonMode) { data.json = true; } for (n in implied) { if (_.has(implied, n)) { implieds.push({ name: n, line: implied[n] }); } } if (implieds.length > 0) { data.implieds = implieds; } if (urls.length > 0) { data.urls = urls; } globals = Object.keys(scope); if (globals.length > 0) { data.globals = globals; } for (i = 1; i < functions.length; i += 1) { f = functions[i]; fu = {}; for (j = 0; j < functionicity.length; j += 1) { fu[functionicity[j]] = []; } for (j = 0; j < functionicity.length; j += 1) { if (fu[functionicity[j]].length === 0) { delete fu[functionicity[j]]; } } fu.name = f["(name)"]; fu.param = f["(params)"]; fu.line = f["(line)"]; fu.character = f["(character)"]; fu.last = f["(last)"]; fu.lastcharacter = f["(lastcharacter)"]; fu.metrics = { complexity: f["(metrics)"].ComplexityCount, parameters: (f["(params)"] || []).length, statements: f["(metrics)"].statementCount }; data.functions.push(fu); } if (unuseds.length > 0) { data.unused = unuseds; } members = []; for (n in member) { if (typeof member[n] === "number") { data.member = member; break; } } return data; }; itself.jshint = itself; return itself; }()); if (typeof exports === "object" && exports) { exports.JSHINT = JSHINT; } },{"./lex.js":"/node_modules/jshint/src/lex.js","./messages.js":"/node_modules/jshint/src/messages.js","./options.js":"/node_modules/jshint/src/options.js","./reg.js":"/node_modules/jshint/src/reg.js","./state.js":"/node_modules/jshint/src/state.js","./style.js":"/node_modules/jshint/src/style.js","./vars.js":"/node_modules/jshint/src/vars.js","events":"/node_modules/browserify/node_modules/events/events.js","underscore":"/node_modules/jshint/node_modules/underscore/underscore.js"}],"/node_modules/jshint/src/lex.js":[function(_dereq_,module,exports){ "use strict"; var _ = _dereq_("underscore"); var events = _dereq_("events"); var reg = _dereq_("./reg.js"); var state = _dereq_("./state.js").state; var unicodeData = _dereq_("../data/ascii-identifier-data.js"); var asciiIdentifierStartTable = unicodeData.asciiIdentifierStartTable; var asciiIdentifierPartTable = unicodeData.asciiIdentifierPartTable; var Token = { Identifier: 1, Punctuator: 2, NumericLiteral: 3, StringLiteral: 4, Comment: 5, Keyword: 6, NullLiteral: 7, BooleanLiteral: 8, RegExp: 9, TemplateHead: 10, TemplateMiddle: 11, TemplateTail: 12, NoSubstTemplate: 13 }; var Context = { Block: 1, Template: 2 }; function asyncTrigger() { var _checks = []; return { push: function(fn) { _checks.push(fn); }, check: function() { for (var check = 0; check < _checks.length; ++check) { _checks[check](); } _checks.splice(0, _checks.length); } }; } function Lexer(source) { var lines = source; if (typeof lines === "string") { lines = lines .replace(/\r\n/g, "\n") .replace(/\r/g, "\n") .split("\n"); } if (lines[0] && lines[0].substr(0, 2) === "#!") { if (lines[0].indexOf("node") !== -1) { state.option.node = true; } lines[0] = ""; } this.emitter = new events.EventEmitter(); this.source = source; this.setLines(lines); this.prereg = true; this.line = 0; this.char = 1; this.from = 1; this.input = ""; this.inComment = false; this.context = []; this.templateStarts = []; for (var i = 0; i < state.option.indent; i += 1) { state.tab += " "; } } Lexer.prototype = { _lines: [], inContext: function(ctxType) { return this.context.length > 0 && this.context[this.context.length - 1].type === ctxType; }, pushContext: function(ctxType) { this.context.push({ type: ctxType }); }, popContext: function() { return this.context.pop(); }, isContext: function(context) { return this.context.length > 0 && this.context[this.context.length - 1] === context; }, currentContext: function() { return this.context.length > 0 && this.context[this.context.length - 1]; }, getLines: function() { this._lines = state.lines; return this._lines; }, setLines: function(val) { this._lines = val; state.lines = this._lines; }, peek: function(i) { return this.input.charAt(i || 0); }, skip: function(i) { i = i || 1; this.char += i; this.input = this.input.slice(i); }, on: function(names, listener) { names.split(" ").forEach(function(name) { this.emitter.on(name, listener); }.bind(this)); }, trigger: function() { this.emitter.emit.apply(this.emitter, Array.prototype.slice.call(arguments)); }, triggerAsync: function(type, args, checks, fn) { checks.push(function() { if (fn()) { this.trigger(type, args); } }.bind(this)); }, scanPunctuator: function() { var ch1 = this.peek(); var ch2, ch3, ch4; switch (ch1) { case ".": if ((/^[0-9]$/).test(this.peek(1))) { return null; } if (this.peek(1) === "." && this.peek(2) === ".") { return { type: Token.Punctuator, value: "..." }; } case "(": case ")": case ";": case ",": case "[": case "]": case ":": case "~": case "?": return { type: Token.Punctuator, value: ch1 }; case "{": this.pushContext(Context.Block); return { type: Token.Punctuator, value: ch1 }; case "}": if (this.inContext(Context.Block)) { this.popContext(); } return { type: Token.Punctuator, value: ch1 }; case "#": return { type: Token.Punctuator, value: ch1 }; case "": return null; } ch2 = this.peek(1); ch3 = this.peek(2); ch4 = this.peek(3); if (ch1 === ">" && ch2 === ">" && ch3 === ">" && ch4 === "=") { return { type: Token.Punctuator, value: ">>>=" }; } if (ch1 === "=" && ch2 === "=" && ch3 === "=") { return { type: Token.Punctuator, value: "===" }; } if (ch1 === "!" && ch2 === "=" && ch3 === "=") { return { type: Token.Punctuator, value: "!==" }; } if (ch1 === ">" && ch2 === ">" && ch3 === ">") { return { type: Token.Punctuator, value: ">>>" }; } if (ch1 === "<" && ch2 === "<" && ch3 === "=") { return { type: Token.Punctuator, value: "<<=" }; } if (ch1 === ">" && ch2 === ">" && ch3 === "=") { return { type: Token.Punctuator, value: ">>=" }; } if (ch1 === "=" && ch2 === ">") { return { type: Token.Punctuator, value: ch1 + ch2 }; } if (ch1 === ch2 && ("+-<>&|".indexOf(ch1) >= 0)) { return { type: Token.Punctuator, value: ch1 + ch2 }; } if ("<>=!+-*%&|^".indexOf(ch1) >= 0) { if (ch2 === "=") { return { type: Token.Punctuator, value: ch1 + ch2 }; } return { type: Token.Punctuator, value: ch1 }; } if (ch1 === "/") { if (ch2 === "=") { return { type: Token.Punctuator, value: "/=" }; } return { type: Token.Punctuator, value: "/" }; } return null; }, scanComments: function() { var ch1 = this.peek(); var ch2 = this.peek(1); var rest = this.input.substr(2); var startLine = this.line; var startChar = this.char; function commentToken(label, body, opt) { var special = ["jshint", "jslint", "members", "member", "globals", "global", "exported"]; var isSpecial = false; var value = label + body; var commentType = "plain"; opt = opt || {}; if (opt.isMultiline) { value += "*/"; } body = body.replace(/\n/g, " "); special.forEach(function(str) { if (isSpecial) { return; } if (label === "//" && str !== "jshint") { return; } if (body.charAt(str.length) === " " && body.substr(0, str.length) === str) { isSpecial = true; label = label + str; body = body.substr(str.length); } if (!isSpecial && body.charAt(0) === " " && body.charAt(str.length + 1) === " " && body.substr(1, str.length) === str) { isSpecial = true; label = label + " " + str; body = body.substr(str.length + 1); } if (!isSpecial) { return; } switch (str) { case "member": commentType = "members"; break; case "global": commentType = "globals"; break; default: commentType = str; } }); return { type: Token.Comment, commentType: commentType, value: value, body: body, isSpecial: isSpecial, isMultiline: opt.isMultiline || false, isMalformed: opt.isMalformed || false }; } if (ch1 === "*" && ch2 === "/") { this.trigger("error", { code: "E018", line: startLine, character: startChar }); this.skip(2); return null; } if (ch1 !== "/" || (ch2 !== "*" && ch2 !== "/")) { return null; } if (ch2 === "/") { this.skip(this.input.length); // Skip to the EOL. return commentToken("//", rest); } var body = ""; if (ch2 === "*") { this.inComment = true; this.skip(2); while (this.peek() !== "*" || this.peek(1) !== "/") { if (this.peek() === "") { // End of Line body += "\n"; if (!this.nextLine()) { this.trigger("error", { code: "E017", line: startLine, character: startChar }); this.inComment = false; return commentToken("/*", body, { isMultiline: true, isMalformed: true }); } } else { body += this.peek(); this.skip(); } } this.skip(2); this.inComment = false; return commentToken("/*", body, { isMultiline: true }); } }, scanKeyword: function() { var result = /^[a-zA-Z_$][a-zA-Z0-9_$]*/.exec(this.input); var keywords = [ "if", "in", "do", "var", "for", "new", "try", "let", "this", "else", "case", "void", "with", "enum", "while", "break", "catch", "throw", "const", "yield", "class", "super", "return", "typeof", "delete", "switch", "export", "import", "default", "finally", "extends", "function", "continue", "debugger", "instanceof" ]; if (result && keywords.indexOf(result[0]) >= 0) { return { type: Token.Keyword, value: result[0] }; } return null; }, scanIdentifier: function() { var id = ""; var index = 0; var type, char; function isNonAsciiIdentifierStart(code) { return code > 256; } function isNonAsciiIdentifierPart(code) { return code > 256; } function isHexDigit(str) { return (/^[0-9a-fA-F]$/).test(str); } var readUnicodeEscapeSequence = function() { index += 1; if (this.peek(index) !== "u") { return null; } var ch1 = this.peek(index + 1); var ch2 = this.peek(index + 2); var ch3 = this.peek(index + 3); var ch4 = this.peek(index + 4); var code; if (isHexDigit(ch1) && isHexDigit(ch2) && isHexDigit(ch3) && isHexDigit(ch4)) { code = parseInt(ch1 + ch2 + ch3 + ch4, 16); if (asciiIdentifierPartTable[code] || isNonAsciiIdentifierPart(code)) { index += 5; return "\\u" + ch1 + ch2 + ch3 + ch4; } return null; } return null; }.bind(this); var getIdentifierStart = function() { var chr = this.peek(index); var code = chr.charCodeAt(0); if (code === 92) { return readUnicodeEscapeSequence(); } if (code < 128) { if (asciiIdentifierStartTable[code]) { index += 1; return chr; } return null; } if (isNonAsciiIdentifierStart(code)) { index += 1; return chr; } return null; }.bind(this); var getIdentifierPart = function() { var chr = this.peek(index); var code = chr.charCodeAt(0); if (code === 92) { return readUnicodeEscapeSequence(); } if (code < 128) { if (asciiIdentifierPartTable[code]) { index += 1; return chr; } return null; } if (isNonAsciiIdentifierPart(code)) { index += 1; return chr; } return null; }.bind(this); function removeEscapeSequences(id) { return id.replace(/\\u([0-9a-fA-F]{4})/g, function(m0, codepoint) { return String.fromCharCode(parseInt(codepoint, 16)); }); } char = getIdentifierStart(); if (char === null) { return null; } id = char; for (;;) { char = getIdentifierPart(); if (char === null) { break; } id += char; } switch (id) { case "true": case "false": type = Token.BooleanLiteral; break; case "null": type = Token.NullLiteral; break; default: type = Token.Identifier; } return { type: type, value: removeEscapeSequences(id), text: id, tokenLength: id.length }; }, scanNumericLiteral: function() { var index = 0; var value = ""; var length = this.input.length; var char = this.peek(index); var bad; var isAllowedDigit = isDecimalDigit; var base = 10; var isLegacy = false; function isDecimalDigit(str) { return (/^[0-9]$/).test(str); } function isOctalDigit(str) { return (/^[0-7]$/).test(str); } function isBinaryDigit(str) { return (/^[01]$/).test(str); } function isHexDigit(str) { return (/^[0-9a-fA-F]$/).test(str); } function isIdentifierStart(ch) { return (ch === "$") || (ch === "_") || (ch === "\\") || (ch >= "a" && ch <= "z") || (ch >= "A" && ch <= "Z"); } if (char !== "." && !isDecimalDigit(char)) { return null; } if (char !== ".") { value = this.peek(index); index += 1; char = this.peek(index); if (value === "0") { if (char === "x" || char === "X") { isAllowedDigit = isHexDigit; base = 16; index += 1; value += char; } if (char === "o" || char === "O") { isAllowedDigit = isOctalDigit; base = 8; if (!state.option.esnext) { this.trigger("warning", { code: "W119", line: this.line, character: this.char, data: [ "Octal integer literal" ] }); } index += 1; value += char; } if (char === "b" || char === "B") { isAllowedDigit = isBinaryDigit; base = 2; if (!state.option.esnext) { this.trigger("warning", { code: "W119", line: this.line, character: this.char, data: [ "Binary integer literal" ] }); } index += 1; value += char; } if (isOctalDigit(char)) { isAllowedDigit = isOctalDigit; base = 8; isLegacy = true; bad = false; index += 1; value += char; } if (!isOctalDigit(char) && isDecimalDigit(char)) { index += 1; value += char; } } while (index < length) { char = this.peek(index); if (isLegacy && isDecimalDigit(char)) { bad = true; } else if (!isAllowedDigit(char)) { break; } value += char; index += 1; } if (isAllowedDigit !== isDecimalDigit) { if (!isLegacy && value.length <= 2) { // 0x return { type: Token.NumericLiteral, value: value, isMalformed: true }; } if (index < length) { char = this.peek(index); if (isIdentifierStart(char)) { return null; } } return { type: Token.NumericLiteral, value: value, base: base, isLegacy: isLegacy, isMalformed: false }; } } if (char === ".") { value += char; index += 1; while (index < length) { char = this.peek(index); if (!isDecimalDigit(char)) { break; } value += char; index += 1; } } if (char === "e" || char === "E") { value += char; index += 1; char = this.peek(index); if (char === "+" || char === "-") { value += this.peek(index); index += 1; } char = this.peek(index); if (isDecimalDigit(char)) { value += char; index += 1; while (index < length) { char = this.peek(index); if (!isDecimalDigit(char)) { break; } value += char; index += 1; } } else { return null; } } if (index < length) { char = this.peek(index); if (isIdentifierStart(char)) { return null; } } return { type: Token.NumericLiteral, value: value, base: base, isMalformed: !isFinite(value) }; }, scanEscapeSequence: function(checks) { var allowNewLine = false; var jump = 1; this.skip(); var char = this.peek(); switch (char) { case "'": this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\'" ] }, checks, function() {return state.jsonMode; }); break; case "b": char = "\\b"; break; case "f": char = "\\f"; break; case "n": char = "\\n"; break; case "r": char = "\\r"; break; case "t": char = "\\t"; break; case "0": char = "\\0"; var n = parseInt(this.peek(1), 10); this.triggerAsync("warning", { code: "W115", line: this.line, character: this.char }, checks, function() { return n >= 0 && n <= 7 && state.isStrict(); }); break; case "u": var hexCode = this.input.substr(1, 4); var code = parseInt(hexCode, 16); if (isNaN(code)) { this.trigger("warning", { code: "W052", line: this.line, character: this.char, data: [ "u" + hexCode ] }); } char = String.fromCharCode(code); jump = 5; break; case "v": this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\v" ] }, checks, function() { return state.jsonMode; }); char = "\v"; break; case "x": var x = parseInt(this.input.substr(1, 2), 16); this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "\\x-" ] }, checks, function() { return state.jsonMode; }); char = String.fromCharCode(x); jump = 3; break; case "\\": char = "\\\\"; break; case "\"": char = "\\\""; break; case "/": break; case "": allowNewLine = true; char = ""; break; } return { char: char, jump: jump, allowNewLine: allowNewLine }; }, scanTemplateLiteral: function(checks) { var tokenType; var value = ""; var ch; var startLine = this.line; var startChar = this.char; var depth = this.templateStarts.length; if (!state.option.esnext) { return null; } else if (this.peek() === "`") { tokenType = Token.TemplateHead; this.templateStarts.push({ line: this.line, char: this.char }); depth = this.templateStarts.length; this.skip(1); this.pushContext(Context.Template); } else if (this.inContext(Context.Template) && this.peek() === "}") { tokenType = Token.TemplateMiddle; } else { return null; } while (this.peek() !== "`") { while ((ch = this.peek()) === "") { value += "\n"; if (!this.nextLine()) { var startPos = this.templateStarts.pop(); this.trigger("error", { code: "E052", line: startPos.line, character: startPos.char }); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: true, depth: depth, context: this.popContext() }; } } if (ch === '$' && this.peek(1) === '{') { value += '${'; this.skip(2); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, depth: depth, context: this.currentContext() }; } else if (ch === '\\') { var escape = this.scanEscapeSequence(checks); value += escape.char; this.skip(escape.jump); } else if (ch !== '`') { value += ch; this.skip(1); } } tokenType = tokenType === Token.TemplateHead ? Token.NoSubstTemplate : Token.TemplateTail; this.skip(1); this.templateStarts.pop(); return { type: tokenType, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, depth: depth, context: this.popContext() }; }, scanStringLiteral: function(checks) { var quote = this.peek(); if (quote !== "\"" && quote !== "'") { return null; } this.triggerAsync("warning", { code: "W108", line: this.line, character: this.char // +1? }, checks, function() { return state.jsonMode && quote !== "\""; }); var value = ""; var startLine = this.line; var startChar = this.char; var allowNewLine = false; this.skip(); while (this.peek() !== quote) { if (this.peek() === "") { // End Of Line if (!allowNewLine) { this.trigger("warning", { code: "W112", line: this.line, character: this.char }); } else { allowNewLine = false; this.triggerAsync("warning", { code: "W043", line: this.line, character: this.char }, checks, function() { return !state.option.multistr; }); this.triggerAsync("warning", { code: "W042", line: this.line, character: this.char }, checks, function() { return state.jsonMode && state.option.multistr; }); } if (!this.nextLine()) { this.trigger("error", { code: "E029", line: startLine, character: startChar }); return { type: Token.StringLiteral, value: value, startLine: startLine, startChar: startChar, isUnclosed: true, quote: quote }; } } else { // Any character other than End Of Line allowNewLine = false; var char = this.peek(); var jump = 1; // A length of a jump, after we're done if (char < " ") { this.trigger("warning", { code: "W113", line: this.line, character: this.char, data: [ "<non-printable>" ] }); } if (char === "\\") { var parsed = this.scanEscapeSequence(checks); char = parsed.char; jump = parsed.jump; allowNewLine = parsed.allowNewLine; } value += char; this.skip(jump); } } this.skip(); return { type: Token.StringLiteral, value: value, startLine: startLine, startChar: startChar, isUnclosed: false, quote: quote }; }, scanRegExp: function() { var index = 0; var length = this.input.length; var char = this.peek(); var value = char; var body = ""; var flags = []; var malformed = false; var isCharSet = false; var terminated; var scanUnexpectedChars = function() { if (char < " ") { malformed = true; this.trigger("warning", { code: "W048", line: this.line, character: this.char }); } if (char === "<") { malformed = true; this.trigger("warning", { code: "W049", line: this.line, character: this.char, data: [ char ] }); } }.bind(this); if (!this.prereg || char !== "/") { return null; } index += 1; terminated = false; while (index < length) { char = this.peek(index); value += char; body += char; if (isCharSet) { if (char === "]") { if (this.peek(index - 1) !== "\\" || this.peek(index - 2) === "\\") { isCharSet = false; } } if (char === "\\") { index += 1; char = this.peek(index); body += char; value += char; scanUnexpectedChars(); } index += 1; continue; } if (char === "\\") { index += 1; char = this.peek(index); body += char; value += char; scanUnexpectedChars(); if (char === "/") { index += 1; continue; } if (char === "[") { index += 1; continue; } } if (char === "[") { isCharSet = true; index += 1; continue; } if (char === "/") { body = body.substr(0, body.length - 1); terminated = true; index += 1; break; } index += 1; } if (!terminated) { this.trigger("error", { code: "E015", line: this.line, character: this.from }); return void this.trigger("fatal", { line: this.line, from: this.from }); } while (index < length) { char = this.peek(index); if (!/[gim]/.test(char)) { break; } flags.push(char); value += char; index += 1; } try { new RegExp(body, flags.join("")); } catch (err) { malformed = true; this.trigger("error", { code: "E016", line: this.line, character: this.char, data: [ err.message ] // Platform dependent! }); } return { type: Token.RegExp, value: value, flags: flags, isMalformed: malformed }; }, scanNonBreakingSpaces: function() { return state.option.nonbsp ? this.input.search(/(\u00A0)/) : -1; }, scanUnsafeChars: function() { return this.input.search(reg.unsafeChars); }, next: function(checks) { this.from = this.char; var start; if (/\s/.test(this.peek())) { start = this.char; while (/\s/.test(this.peek())) { this.from += 1; this.skip(); } } var match = this.scanComments() || this.scanStringLiteral(checks) || this.scanTemplateLiteral(checks); if (match) { return match; } match = this.scanRegExp() || this.scanPunctuator() || this.scanKeyword() || this.scanIdentifier() || this.scanNumericLiteral(); if (match) { this.skip(match.tokenLength || match.value.length); return match; } return null; }, nextLine: function() { var char; if (this.line >= this.getLines().length) { return false; } this.input = this.getLines()[this.line]; this.line += 1; this.char = 1; this.from = 1; var inputTrimmed = this.input.trim(); var startsWith = function() { return _.some(arguments, function(prefix) { return inputTrimmed.indexOf(prefix) === 0; }); }; var endsWith = function() { return _.some(arguments, function(suffix) { return inputTrimmed.indexOf(suffix, inputTrimmed.length - suffix.length) !== -1; }); }; if (state.ignoreLinterErrors === true) { if (!startsWith("/*", "//") && !(this.inComment && endsWith("*/"))) { this.input = ""; } } char = this.scanNonBreakingSpaces(); if (char >= 0) { this.trigger("warning", { code: "W125", line: this.line, character: char + 1 }); } this.input = this.input.replace(/\t/g, state.tab); char = this.scanUnsafeChars(); if (char >= 0) { this.trigger("warning", { code: "W100", line: this.line, character: char }); } if (state.option.maxlen && state.option.maxlen < this.input.length) { var inComment = this.inComment || startsWith.call(inputTrimmed, "//") || startsWith.call(inputTrimmed, "/*"); var shouldTriggerError = !inComment || !reg.maxlenException.test(inputTrimmed); if (shouldTriggerError) { this.trigger("warning", { code: "W101", line: this.line, character: this.input.length }); } } return true; }, start: function() { this.nextLine(); }, token: function() { var checks = asyncTrigger(); var token; function isReserved(token, isProperty) { if (!token.reserved) { return false; } var meta = token.meta; if (meta && meta.isFutureReservedWord && state.inES5()) { if (!meta.es5) { return false; } if (meta.strictOnly) { if (!state.option.strict && !state.isStrict()) { return false; } } if (isProperty) { return false; } } return true; } var create = function(type, value, isProperty, token) { var obj; if (type !== "(endline)" && type !== "(end)") { this.prereg = false; } if (type === "(punctuator)") { switch (value) { case ".": case ")": case "~": case "#": case "]": case "++": case "--": this.prereg = false; break; default: this.prereg = true; } obj = Object.create(state.syntax[value] || state.syntax["(error)"]); } if (type === "(identifier)") { if (value === "return" || value === "case" || value === "typeof") { this.prereg = true; } if (_.has(state.syntax, value)) { obj = Object.create(state.syntax[value] || state.syntax["(error)"]); if (!isReserved(obj, isProperty && type === "(identifier)")) { obj = null; } } } if (!obj) { obj = Object.create(state.syntax[type]); } obj.identifier = (type === "(identifier)"); obj.type = obj.type || type; obj.value = value; obj.line = this.line; obj.character = this.char; obj.from = this.from; if (obj.identifier && token) obj.raw_text = token.text || token.value; if (token && token.startLine && token.startLine !== this.line) { obj.startLine = token.startLine; } if (token && token.context) { obj.context = token.context; } if (token && token.depth) { obj.depth = token.depth; } if (token && token.isUnclosed) { obj.isUnclosed = token.isUnclosed; } if (isProperty && obj.identifier) { obj.isProperty = isProperty; } obj.check = checks.check; return obj; }.bind(this); for (;;) { if (!this.input.length) { if (this.nextLine()) { return create("(endline)", ""); } if (this.exhausted) { return null; } this.exhausted = true; return create("(end)", ""); } token = this.next(checks); if (!token) { if (this.input.length) { this.trigger("error", { code: "E024", line: this.line, character: this.char, data: [ this.peek() ] }); this.input = ""; } continue; } switch (token.type) { case Token.StringLiteral: this.triggerAsync("String", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value, quote: token.quote }, checks, function() { return true; }); return create("(string)", token.value, null, token); case Token.TemplateHead: this.trigger("TemplateHead", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template)", token.value, null, token); case Token.TemplateMiddle: this.trigger("TemplateMiddle", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template middle)", token.value, null, token); case Token.TemplateTail: this.trigger("TemplateTail", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(template tail)", token.value, null, token); case Token.NoSubstTemplate: this.trigger("NoSubstTemplate", { line: this.line, char: this.char, from: this.from, startLine: token.startLine, startChar: token.startChar, value: token.value }); return create("(no subst template)", token.value, null, token); case Token.Identifier: this.trigger("Identifier", { line: this.line, char: this.char, from: this.form, name: token.value, raw_name: token.text, isProperty: state.tokens.curr.id === "." }); case Token.Keyword: case Token.NullLiteral: case Token.BooleanLiteral: return create("(identifier)", token.value, state.tokens.curr.id === ".", token); case Token.NumericLiteral: if (token.isMalformed) { this.trigger("warning", { code: "W045", line: this.line, character: this.char, data: [ token.value ] }); } this.triggerAsync("warning", { code: "W114", line: this.line, character: this.char, data: [ "0x-" ] }, checks, function() { return token.base === 16 && state.jsonMode; }); this.triggerAsync("warning", { code: "W115", line: this.line, character: this.char }, checks, function() { return state.isStrict() && token.base === 8 && token.isLegacy; }); this.trigger("Number", { line: this.line, char: this.char, from: this.from, value: token.value, base: token.base, isMalformed: token.malformed }); return create("(number)", token.value); case Token.RegExp: return create("(regexp)", token.value); case Token.Comment: state.tokens.curr.comment = true; if (token.isSpecial) { return { id: '(comment)', value: token.value, body: token.body, type: token.commentType, isSpecial: token.isSpecial, line: this.line, character: this.char, from: this.from }; } break; case "": break; default: return create("(punctuator)", token.value); } } } }; exports.Lexer = Lexer; exports.Context = Context; },{"../data/ascii-identifier-data.js":"/node_modules/jshint/data/ascii-identifier-data.js","./reg.js":"/node_modules/jshint/src/reg.js","./state.js":"/node_modules/jshint/src/state.js","events":"/node_modules/browserify/node_modules/events/events.js","underscore":"/node_modules/jshint/node_modules/underscore/underscore.js"}],"/node_modules/jshint/src/messages.js":[function(_dereq_,module,exports){ "use strict"; var _ = _dereq_("underscore"); var errors = { E001: "Bad option: '{a}'.", E002: "Bad option value.", E003: "Expected a JSON value.", E004: "Input is neither a string nor an array of strings.", E005: "Input is empty.", E006: "Unexpected early end of program.", E007: "Missing \"use strict\" statement.", E008: "Strict violation.", E009: "Option 'validthis' can't be used in a global scope.", E010: "'with' is not allowed in strict mode.", E011: "const '{a}' has already been declared.", E012: "const '{a}' is initialized to 'undefined'.", E013: "Attempting to override '{a}' which is a constant.", E014: "A regular expression literal can be confused with '/='.", E015: "Unclosed regular expression.", E016: "Invalid regular expression.", E017: "Unclosed comment.", E018: "Unbegun comment.", E019: "Unmatched '{a}'.", E020: "Expected '{a}' to match '{b}' from line {c} and instead saw '{d}'.", E021: "Expected '{a}' and instead saw '{b}'.", E022: "Line breaking error '{a}'.", E023: "Missing '{a}'.", E024: "Unexpected '{a}'.", E025: "Missing ':' on a case clause.", E026: "Missing '}' to match '{' from line {a}.", E027: "Missing ']' to match '[' from line {a}.", E028: "Illegal comma.", E029: "Unclosed string.", E030: "Expected an identifier and instead saw '{a}'.", E031: "Bad assignment.", // FIXME: Rephrase E032: "Expected a small integer or 'false' and instead saw '{a}'.", E033: "Expected an operator and instead saw '{a}'.", E034: "get/set are ES5 features.", E035: "Missing property name.", E036: "Expected to see a statement and instead saw a block.", E037: null, E038: null, E039: "Function declarations are not invocable. Wrap the whole function invocation in parens.", E040: "Each value should have its own case label.", E041: "Unrecoverable syntax error.", E042: "Stopping.", E043: "Too many errors.", E044: null, E045: "Invalid for each loop.", E046: "A yield statement shall be within a generator function (with syntax: `function*`)", E047: null, // Vacant E048: "{a} declaration not directly within block.", E049: "A {a} cannot be named '{b}'.", E050: "Mozilla requires the yield expression to be parenthesized here.", E051: "Regular parameters cannot come after default parameters.", E052: "Unclosed template literal.", E053: "Export declaration must be in global scope.", E054: "Class properties must be methods. Expected '(' but instead saw '{a}'.", E055: "The '{a}' option cannot be set after any executable code." }; var warnings = { W001: "'hasOwnProperty' is a really bad name.", W002: "Value of '{a}' may be overwritten in IE 8 and earlier.", W003: "'{a}' was used before it was defined.", W004: "'{a}' is already defined.", W005: "A dot following a number can be confused with a decimal point.", W006: "Confusing minuses.", W007: "Confusing plusses.", W008: "A leading decimal point can be confused with a dot: '{a}'.", W009: "The array literal notation [] is preferable.", W010: "The object literal notation {} is preferable.", W011: null, W012: null, W013: null, W014: "Bad line breaking before '{a}'.", W015: null, W016: "Unexpected use of '{a}'.", W017: "Bad operand.", W018: "Confusing use of '{a}'.", W019: "Use the isNaN function to compare with NaN.", W020: "Read only.", W021: "'{a}' is a function.", W022: "Do not assign to the exception parameter.", W023: "Expected an identifier in an assignment and instead saw a function invocation.", W024: "Expected an identifier and instead saw '{a}' (a reserved word).", W025: "Missing name in function declaration.", W026: "Inner functions should be listed at the top of the outer function.", W027: "Unreachable '{a}' after '{b}'.", W028: "Label '{a}' on {b} statement.", W030: "Expected an assignment or function call and instead saw an expression.", W031: "Do not use 'new' for side effects.", W032: "Unnecessary semicolon.", W033: "Missing semicolon.", W034: "Unnecessary directive \"{a}\".", W035: "Empty block.", W036: "Unexpected /*member '{a}'.", W037: "'{a}' is a statement label.", W038: "'{a}' used out of scope.", W039: "'{a}' is not allowed.", W040: "Possible strict violation.", W041: "Use '{a}' to compare with '{b}'.", W042: "Avoid EOL escaping.", W043: "Bad escaping of EOL. Use option multistr if needed.", W044: "Bad or unnecessary escaping.", /* TODO(caitp): remove W044 */ W045: "Bad number '{a}'.", W046: "Don't use extra leading zeros '{a}'.", W047: "A trailing decimal point can be confused with a dot: '{a}'.", W048: "Unexpected control character in regular expression.", W049: "Unexpected escaped character '{a}' in regular expression.", W050: "JavaScript URL.", W051: "Variables should not be deleted.", W052: "Unexpected '{a}'.", W053: "Do not use {a} as a constructor.", W054: "The Function constructor is a form of eval.", W055: "A constructor name should start with an uppercase letter.", W056: "Bad constructor.", W057: "Weird construction. Is 'new' necessary?", W058: "Missing '()' invoking a constructor.", W059: "Avoid arguments.{a}.", W060: "document.write can be a form of eval.", W061: "eval can be harmful.", W062: "Wrap an immediate function invocation in parens " + "to assist the reader in understanding that the expression " + "is the result of a function, and not the function itself.", W063: "Math is not a function.", W064: "Missing 'new' prefix when invoking a constructor.", W065: "Missing radix parameter.", W066: "Implied eval. Consider passing a function instead of a string.", W067: "Bad invocation.", W068: "Wrapping non-IIFE function literals in parens is unnecessary.", W069: "['{a}'] is better written in dot notation.", W070: "Extra comma. (it breaks older versions of IE)", W071: "This function has too many statements. ({a})", W072: "This function has too many parameters. ({a})", W073: "Blocks are nested too deeply. ({a})", W074: "This function's cyclomatic complexity is too high. ({a})", W075: "Duplicate {a} '{b}'.", W076: "Unexpected parameter '{a}' in get {b} function.", W077: "Expected a single parameter in set {a} function.", W078: "Setter is defined without getter.", W079: "Redefinition of '{a}'.", W080: "It's not necessary to initialize '{a}' to 'undefined'.", W081: null, W082: "Function declarations should not be placed in blocks. " + "Use a function expression or move the statement to the top of " + "the outer function.", W083: "Don't make functions within a loop.", W084: "Assignment in conditional expression", W085: "Don't use 'with'.", W086: "Expected a 'break' statement before '{a}'.", W087: "Forgotten 'debugger' statement?", W088: "Creating global 'for' variable. Should be 'for (var {a} ...'.", W089: "The body of a for in should be wrapped in an if statement to filter " + "unwanted properties from the prototype.", W090: "'{a}' is not a statement label.", W091: "'{a}' is out of scope.", W093: "Did you mean to return a conditional instead of an assignment?", W094: "Unexpected comma.", W095: "Expected a string and instead saw {a}.", W096: "The '{a}' key may produce unexpected results.", W097: "Use the function form of \"use strict\".", W098: "'{a}' is defined but never used.", W099: null, W100: "This character may get silently deleted by one or more browsers.", W101: "Line is too long.", W102: null, W103: "The '{a}' property is deprecated.", W104: "'{a}' is available in ES6 (use esnext option) or Mozilla JS extensions (use moz).", W105: "Unexpected {a} in '{b}'.", W106: "Identifier '{a}' is not in camel case.", W107: "Script URL.", W108: "Strings must use doublequote.", W109: "Strings must use singlequote.", W110: "Mixed double and single quotes.", W112: "Unclosed string.", W113: "Control character in string: {a}.", W114: "Avoid {a}.", W115: "Octal literals are not allowed in strict mode.", W116: "Expected '{a}' and instead saw '{b}'.", W117: "'{a}' is not defined.", W118: "'{a}' is only available in Mozilla JavaScript extensions (use moz option).", W119: "'{a}' is only available in ES6 (use esnext option).", W120: "You might be leaking a variable ({a}) here.", W121: "Extending prototype of native object: '{a}'.", W122: "Invalid typeof value '{a}'", W123: "'{a}' is already defined in outer scope.", W124: "A generator function shall contain a yield statement.", W125: "This line contains non-breaking spaces: http://jshint.com/doc/options/#nonbsp", W126: "Unnecessary grouping operator.", W127: "Unexpected use of a comma operator.", W128: "Empty array elements require elision=true.", W129: "'{a}' is defined in a future version of JavaScript. Use a " + "different variable name to avoid migration issues.", W130: "Invalid element after rest element.", W131: "Invalid parameter after rest parameter.", W132: "`var` declarations are forbidden. Use `let` or `const` instead.", W133: "Invalid for-{a} loop left-hand-side: {b}.", W134: "The '{a}' option is only available when linting ECMAScript {b} code." }; var info = { I001: "Comma warnings can be turned off with 'laxcomma'.", I002: null, I003: "ES5 option is now set per default" }; exports.errors = {}; exports.warnings = {}; exports.info = {}; _.each(errors, function(desc, code) { exports.errors[code] = { code: code, desc: desc }; }); _.each(warnings, function(desc, code) { exports.warnings[code] = { code: code, desc: desc }; }); _.each(info, function(desc, code) { exports.info[code] = { code: code, desc: desc }; }); },{"underscore":"/node_modules/jshint/node_modules/underscore/underscore.js"}],"/node_modules/jshint/src/name-stack.js":[function(_dereq_,module,exports){ "use strict"; function NameStack() { this._stack = []; } Object.defineProperty(NameStack.prototype, "length", { get: function() { return this._stack.length; } }); NameStack.prototype.push = function() { this._stack.push(null); }; NameStack.prototype.pop = function() { this._stack.pop(); }; NameStack.prototype.set = function(token) { this._stack[this.length - 1] = token; }; NameStack.prototype.infer = function() { var nameToken = this._stack[this.length - 1]; var prefix = ""; var type; if (!nameToken || nameToken.type === "class") { nameToken = this._stack[this.length - 2]; } if (!nameToken) { return "(empty)"; } type = nameToken.type; if (type !== "(string)" && type !== "(number)" && type !== "(identifier)" && type !== "default") { return "(expression)"; } if (nameToken.accessorType) { prefix = nameToken.accessorType + " "; } return prefix + nameToken.value; }; module.exports = NameStack; },{}],"/node_modules/jshint/src/options.js":[function(_dereq_,module,exports){ "use strict"; exports.bool = { enforcing: { bitwise : true, freeze : true, camelcase : true, curly : true, eqeqeq : true, futurehostile: true, notypeof : true, es3 : true, es5 : true, forin : true, funcscope : true, immed : true, iterator : true, newcap : true, noarg : true, nocomma : true, noempty : true, nonbsp : true, nonew : true, undef : true, singleGroups: false, strict : true, varstmt: false, enforceall : false }, relaxing: { asi : true, multistr : true, debug : true, boss : true, evil : true, globalstrict: true, plusplus : true, proto : true, scripturl : true, sub : true, supernew : true, laxbreak : true, laxcomma : true, validthis : true, withstmt : true, moz : true, noyield : true, eqnull : true, lastsemic : true, loopfunc : true, expr : true, esnext : true, elision : true, }, environments: { mootools : true, couch : true, jasmine : true, jquery : true, node : true, qunit : true, rhino : true, shelljs : true, prototypejs : true, yui : true, mocha : true, module : true, wsh : true, worker : true, nonstandard : true, browser : true, browserify : true, devel : true, dojo : true, typed : true, phantom : true }, obsolete: { onecase : true, // if one case switch statements should be allowed regexp : true, // if the . should not be allowed in regexp literals regexdash : true // if unescaped first/last dash (-) inside brackets } }; exports.val = { maxlen : false, indent : false, maxerr : false, predef : false, // predef is deprecated and being replaced by globals globals : false, quotmark : false, scope : false, maxstatements: false, maxdepth : false, maxparams : false, maxcomplexity: false, shadow : false, unused : true, latedef : false, ignore : false, // start/end ignoring lines of code, bypassing the lexer ignoreDelimiters: false // array of start/end delimiters used to ignore }; exports.inverted = { bitwise : true, forin : true, newcap : true, plusplus: true, regexp : true, undef : true, eqeqeq : true, strict : true }; exports.validNames = Object.keys(exports.val) .concat(Object.keys(exports.bool.relaxing)) .concat(Object.keys(exports.bool.enforcing)) .concat(Object.keys(exports.bool.obsolete)) .concat(Object.keys(exports.bool.environments)); exports.renamed = { eqeq : "eqeqeq", windows: "wsh", sloppy : "strict" }; exports.removed = { nomen: true, onevar: true, passfail: true, white: true, gcl: true, smarttabs: true, trailing: true }; exports.noenforceall = { varstmt: true, strict: true }; },{}],"/node_modules/jshint/src/reg.js":[function(_dereq_,module,exports){ "use strict"; exports.unsafeString = /@cc|<\/?|script|\]\s*\]|<\s*!|&lt/i; exports.unsafeChars = /[\u0000-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; exports.needEsc = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/; exports.needEscGlobal = /[\u0000-\u001f&<"\/\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g; exports.starSlash = /\*\//; exports.identifier = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/; exports.javascriptURL = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\s*:/i; exports.fallsThrough = /^\s*\/\*\s*falls?\sthrough\s*\*\/\s*$/; exports.maxlenException = /^(?:(?:\/\/|\/\*|\*) ?)?[^ ]+$/; },{}],"/node_modules/jshint/src/state.js":[function(_dereq_,module,exports){ "use strict"; var NameStack = _dereq_("./name-stack.js"); var state = { syntax: {}, isStrict: function() { return this.directive["use strict"] || this.inClassBody || this.option.module; }, inMoz: function() { return this.option.moz; }, inESNext: function() { return this.option.moz || this.option.esnext; }, inES5: function() { return !this.option.es3; }, inES3: function() { return this.option.es3; }, reset: function() { this.tokens = { prev: null, next: null, curr: null }; this.option = {}; this.funct = null; this.ignored = {}; this.directive = {}; this.jsonMode = false; this.jsonWarnings = []; this.lines = []; this.tab = ""; this.cache = {}; // Node.JS doesn't have Map. Sniff. this.ignoredLines = {}; this.forinifcheckneeded = false; this.nameStack = new NameStack(); this.inClassBody = false; this.ignoreLinterErrors = false; } }; exports.state = state; },{"./name-stack.js":"/node_modules/jshint/src/name-stack.js"}],"/node_modules/jshint/src/style.js":[function(_dereq_,module,exports){ "use strict"; exports.register = function(linter) { linter.on("Identifier", function style_scanProto(data) { if (linter.getOption("proto")) { return; } if (data.name === "__proto__") { linter.warn("W103", { line: data.line, char: data.char, data: [ data.name ] }); } }); linter.on("Identifier", function style_scanIterator(data) { if (linter.getOption("iterator")) { return; } if (data.name === "__iterator__") { linter.warn("W104", { line: data.line, char: data.char, data: [ data.name ] }); } }); linter.on("Identifier", function style_scanCamelCase(data) { if (!linter.getOption("camelcase")) { return; } if (data.name.replace(/^_+|_+$/g, "").indexOf("_") > -1 && !data.name.match(/^[A-Z0-9_]*$/)) { linter.warn("W106", { line: data.line, char: data.from, data: [ data.name ] }); } }); linter.on("String", function style_scanQuotes(data) { var quotmark = linter.getOption("quotmark"); var code; if (!quotmark) { return; } if (quotmark === "single" && data.quote !== "'") { code = "W109"; } if (quotmark === "double" && data.quote !== "\"") { code = "W108"; } if (quotmark === true) { if (!linter.getCache("quotmark")) { linter.setCache("quotmark", data.quote); } if (linter.getCache("quotmark") !== data.quote) { code = "W110"; } } if (code) { linter.warn(code, { line: data.line, char: data.char, }); } }); linter.on("Number", function style_scanNumbers(data) { if (data.value.charAt(0) === ".") { linter.warn("W008", { line: data.line, char: data.char, data: [ data.value ] }); } if (data.value.substr(data.value.length - 1) === ".") { linter.warn("W047", { line: data.line, char: data.char, data: [ data.value ] }); } if (/^00+/.test(data.value)) { linter.warn("W046", { line: data.line, char: data.char, data: [ data.value ] }); } }); linter.on("String", function style_scanJavaScriptURLs(data) { var re = /^(?:javascript|jscript|ecmascript|vbscript|livescript)\s*:/i; if (linter.getOption("scripturl")) { return; } if (re.test(data.value)) { linter.warn("W107", { line: data.line, char: data.char }); } }); }; },{}],"/node_modules/jshint/src/vars.js":[function(_dereq_,module,exports){ "use strict"; exports.reservedVars = { arguments : false, NaN : false }; exports.ecmaIdentifiers = { 3: { Array : false, Boolean : false, Date : false, decodeURI : false, decodeURIComponent : false, encodeURI : false, encodeURIComponent : false, Error : false, "eval" : false, EvalError : false, Function : false, hasOwnProperty : false, isFinite : false, isNaN : false, Math : false, Number : false, Object : false, parseInt : false, parseFloat : false, RangeError : false, ReferenceError : false, RegExp : false, String : false, SyntaxError : false, TypeError : false, URIError : false }, 5: { JSON : false }, 6: { Map : false, Promise : false, Proxy : false, Reflect : false, Set : false, Symbol : false, WeakMap : false, WeakSet : false } }; exports.browser = { Audio : false, Blob : false, addEventListener : false, applicationCache : false, atob : false, blur : false, btoa : false, cancelAnimationFrame : false, CanvasGradient : false, CanvasPattern : false, CanvasRenderingContext2D: false, CSS : false, clearInterval : false, clearTimeout : false, close : false, closed : false, Comment : false, CustomEvent : false, DOMParser : false, defaultStatus : false, Document : false, document : false, DocumentFragment : false, Element : false, ElementTimeControl : false, Event : false, event : false, fetch : false, FileReader : false, FormData : false, focus : false, frames : false, getComputedStyle : false, HTMLElement : false, HTMLAnchorElement : false, HTMLBaseElement : false, HTMLBlockquoteElement: false, HTMLBodyElement : false, HTMLBRElement : false, HTMLButtonElement : false, HTMLCanvasElement : false, HTMLCollection : false, HTMLDirectoryElement : false, HTMLDivElement : false, HTMLDListElement : false, HTMLFieldSetElement : false, HTMLFontElement : false, HTMLFormElement : false, HTMLFrameElement : false, HTMLFrameSetElement : false, HTMLHeadElement : false, HTMLHeadingElement : false, HTMLHRElement : false, HTMLHtmlElement : false, HTMLIFrameElement : false, HTMLImageElement : false, HTMLInputElement : false, HTMLIsIndexElement : false, HTMLLabelElement : false, HTMLLayerElement : false, HTMLLegendElement : false, HTMLLIElement : false, HTMLLinkElement : false, HTMLMapElement : false, HTMLMenuElement : false, HTMLMetaElement : false, HTMLModElement : false, HTMLObjectElement : false, HTMLOListElement : false, HTMLOptGroupElement : false, HTMLOptionElement : false, HTMLParagraphElement : false, HTMLParamElement : false, HTMLPreElement : false, HTMLQuoteElement : false, HTMLScriptElement : false, HTMLSelectElement : false, HTMLStyleElement : false, HTMLTableCaptionElement: false, HTMLTableCellElement : false, HTMLTableColElement : false, HTMLTableElement : false, HTMLTableRowElement : false, HTMLTableSectionElement: false, HTMLTemplateElement : false, HTMLTextAreaElement : false, HTMLTitleElement : false, HTMLUListElement : false, HTMLVideoElement : false, history : false, Image : false, Intl : false, length : false, localStorage : false, location : false, matchMedia : false, MessageChannel : false, MessageEvent : false, MessagePort : false, MouseEvent : false, moveBy : false, moveTo : false, MutationObserver : false, name : false, Node : false, NodeFilter : false, NodeList : false, Notification : false, navigator : false, onbeforeunload : true, onblur : true, onerror : true, onfocus : true, onload : true, onresize : true, onunload : true, open : false, openDatabase : false, opener : false, Option : false, parent : false, performance : false, print : false, Range : false, requestAnimationFrame : false, removeEventListener : false, resizeBy : false, resizeTo : false, screen : false, scroll : false, scrollBy : false, scrollTo : false, sessionStorage : false, setInterval : false, setTimeout : false, SharedWorker : false, status : false, SVGAElement : false, SVGAltGlyphDefElement: false, SVGAltGlyphElement : false, SVGAltGlyphItemElement: false, SVGAngle : false, SVGAnimateColorElement: false, SVGAnimateElement : false, SVGAnimateMotionElement: false, SVGAnimateTransformElement: false, SVGAnimatedAngle : false, SVGAnimatedBoolean : false, SVGAnimatedEnumeration: false, SVGAnimatedInteger : false, SVGAnimatedLength : false, SVGAnimatedLengthList: false, SVGAnimatedNumber : false, SVGAnimatedNumberList: false, SVGAnimatedPathData : false, SVGAnimatedPoints : false, SVGAnimatedPreserveAspectRatio: false, SVGAnimatedRect : false, SVGAnimatedString : false, SVGAnimatedTransformList: false, SVGAnimationElement : false, SVGCSSRule : false, SVGCircleElement : false, SVGClipPathElement : false, SVGColor : false, SVGColorProfileElement: false, SVGColorProfileRule : false, SVGComponentTransferFunctionElement: false, SVGCursorElement : false, SVGDefsElement : false, SVGDescElement : false, SVGDocument : false, SVGElement : false, SVGElementInstance : false, SVGElementInstanceList: false, SVGEllipseElement : false, SVGExternalResourcesRequired: false, SVGFEBlendElement : false, SVGFEColorMatrixElement: false, SVGFEComponentTransferElement: false, SVGFECompositeElement: false, SVGFEConvolveMatrixElement: false, SVGFEDiffuseLightingElement: false, SVGFEDisplacementMapElement: false, SVGFEDistantLightElement: false, SVGFEFloodElement : false, SVGFEFuncAElement : false, SVGFEFuncBElement : false, SVGFEFuncGElement : false, SVGFEFuncRElement : false, SVGFEGaussianBlurElement: false, SVGFEImageElement : false, SVGFEMergeElement : false, SVGFEMergeNodeElement: false, SVGFEMorphologyElement: false, SVGFEOffsetElement : false, SVGFEPointLightElement: false, SVGFESpecularLightingElement: false, SVGFESpotLightElement: false, SVGFETileElement : false, SVGFETurbulenceElement: false, SVGFilterElement : false, SVGFilterPrimitiveStandardAttributes: false, SVGFitToViewBox : false, SVGFontElement : false, SVGFontFaceElement : false, SVGFontFaceFormatElement: false, SVGFontFaceNameElement: false, SVGFontFaceSrcElement: false, SVGFontFaceUriElement: false, SVGForeignObjectElement: false, SVGGElement : false, SVGGlyphElement : false, SVGGlyphRefElement : false, SVGGradientElement : false, SVGHKernElement : false, SVGICCColor : false, SVGImageElement : false, SVGLangSpace : false, SVGLength : false, SVGLengthList : false, SVGLineElement : false, SVGLinearGradientElement: false, SVGLocatable : false, SVGMPathElement : false, SVGMarkerElement : false, SVGMaskElement : false, SVGMatrix : false, SVGMetadataElement : false, SVGMissingGlyphElement: false, SVGNumber : false, SVGNumberList : false, SVGPaint : false, SVGPathElement : false, SVGPathSeg : false, SVGPathSegArcAbs : false, SVGPathSegArcRel : false, SVGPathSegClosePath : false, SVGPathSegCurvetoCubicAbs: false, SVGPathSegCurvetoCubicRel: false, SVGPathSegCurvetoCubicSmoothAbs: false, SVGPathSegCurvetoCubicSmoothRel: false, SVGPathSegCurvetoQuadraticAbs: false, SVGPathSegCurvetoQuadraticRel: false, SVGPathSegCurvetoQuadraticSmoothAbs: false, SVGPathSegCurvetoQuadraticSmoothRel: false, SVGPathSegLinetoAbs : false, SVGPathSegLinetoHorizontalAbs: false, SVGPathSegLinetoHorizontalRel: false, SVGPathSegLinetoRel : false, SVGPathSegLinetoVerticalAbs: false, SVGPathSegLinetoVerticalRel: false, SVGPathSegList : false, SVGPathSegMovetoAbs : false, SVGPathSegMovetoRel : false, SVGPatternElement : false, SVGPoint : false, SVGPointList : false, SVGPolygonElement : false, SVGPolylineElement : false, SVGPreserveAspectRatio: false, SVGRadialGradientElement: false, SVGRect : false, SVGRectElement : false, SVGRenderingIntent : false, SVGSVGElement : false, SVGScriptElement : false, SVGSetElement : false, SVGStopElement : false, SVGStringList : false, SVGStylable : false, SVGStyleElement : false, SVGSwitchElement : false, SVGSymbolElement : false, SVGTRefElement : false, SVGTSpanElement : false, SVGTests : false, SVGTextContentElement: false, SVGTextElement : false, SVGTextPathElement : false, SVGTextPositioningElement: false, SVGTitleElement : false, SVGTransform : false, SVGTransformList : false, SVGTransformable : false, SVGURIReference : false, SVGUnitTypes : false, SVGUseElement : false, SVGVKernElement : false, SVGViewElement : false, SVGViewSpec : false, SVGZoomAndPan : false, Text : false, TextDecoder : false, TextEncoder : false, TimeEvent : false, top : false, URL : false, WebGLActiveInfo : false, WebGLBuffer : false, WebGLContextEvent : false, WebGLFramebuffer : false, WebGLProgram : false, WebGLRenderbuffer : false, WebGLRenderingContext: false, WebGLShader : false, WebGLShaderPrecisionFormat: false, WebGLTexture : false, WebGLUniformLocation : false, WebSocket : false, window : false, Worker : false, XDomainRequest : false, XMLHttpRequest : false, XMLSerializer : false, XPathEvaluator : false, XPathException : false, XPathExpression : false, XPathNamespace : false, XPathNSResolver : false, XPathResult : false }; exports.devel = { alert : false, confirm: false, console: false, Debug : false, opera : false, prompt : false }; exports.worker = { importScripts : true, postMessage : true, self : true, FileReaderSync : true }; exports.nonstandard = { escape : false, unescape: false }; exports.couch = { "require" : false, respond : false, getRow : false, emit : false, send : false, start : false, sum : false, log : false, exports : false, module : false, provides : false }; exports.node = { __filename : false, __dirname : false, GLOBAL : false, global : false, module : false, require : false, Buffer : true, console : true, exports : true, process : true, setTimeout : true, clearTimeout : true, setInterval : true, clearInterval : true, setImmediate : true, // v0.9.1+ clearImmediate: true // v0.9.1+ }; exports.browserify = { __filename : false, __dirname : false, global : false, module : false, require : false, Buffer : true, exports : true, process : true }; exports.phantom = { phantom : true, require : true, WebPage : true, console : true, // in examples, but undocumented exports : true // v1.7+ }; exports.qunit = { asyncTest : false, deepEqual : false, equal : false, expect : false, module : false, notDeepEqual : false, notEqual : false, notPropEqual : false, notStrictEqual : false, ok : false, propEqual : false, QUnit : false, raises : false, start : false, stop : false, strictEqual : false, test : false, "throws" : false }; exports.rhino = { defineClass : false, deserialize : false, gc : false, help : false, importClass : false, importPackage: false, "java" : false, load : false, loadClass : false, Packages : false, print : false, quit : false, readFile : false, readUrl : false, runCommand : false, seal : false, serialize : false, spawn : false, sync : false, toint32 : false, version : false }; exports.shelljs = { target : false, echo : false, exit : false, cd : false, pwd : false, ls : false, find : false, cp : false, rm : false, mv : false, mkdir : false, test : false, cat : false, sed : false, grep : false, which : false, dirs : false, pushd : false, popd : false, env : false, exec : false, chmod : false, config : false, error : false, tempdir : false }; exports.typed = { ArrayBuffer : false, ArrayBufferView : false, DataView : false, Float32Array : false, Float64Array : false, Int16Array : false, Int32Array : false, Int8Array : false, Uint16Array : false, Uint32Array : false, Uint8Array : false, Uint8ClampedArray : false }; exports.wsh = { ActiveXObject : true, Enumerator : true, GetObject : true, ScriptEngine : true, ScriptEngineBuildVersion : true, ScriptEngineMajorVersion : true, ScriptEngineMinorVersion : true, VBArray : true, WSH : true, WScript : true, XDomainRequest : true }; exports.dojo = { dojo : false, dijit : false, dojox : false, define : false, "require": false }; exports.jquery = { "$" : false, jQuery : false }; exports.mootools = { "$" : false, "$$" : false, Asset : false, Browser : false, Chain : false, Class : false, Color : false, Cookie : false, Core : false, Document : false, DomReady : false, DOMEvent : false, DOMReady : false, Drag : false, Element : false, Elements : false, Event : false, Events : false, Fx : false, Group : false, Hash : false, HtmlTable : false, IFrame : false, IframeShim : false, InputValidator: false, instanceOf : false, Keyboard : false, Locale : false, Mask : false, MooTools : false, Native : false, Options : false, OverText : false, Request : false, Scroller : false, Slick : false, Slider : false, Sortables : false, Spinner : false, Swiff : false, Tips : false, Type : false, typeOf : false, URI : false, Window : false }; exports.prototypejs = { "$" : false, "$$" : false, "$A" : false, "$F" : false, "$H" : false, "$R" : false, "$break" : false, "$continue" : false, "$w" : false, Abstract : false, Ajax : false, Class : false, Enumerable : false, Element : false, Event : false, Field : false, Form : false, Hash : false, Insertion : false, ObjectRange : false, PeriodicalExecuter: false, Position : false, Prototype : false, Selector : false, Template : false, Toggle : false, Try : false, Autocompleter : false, Builder : false, Control : false, Draggable : false, Draggables : false, Droppables : false, Effect : false, Sortable : false, SortableObserver : false, Sound : false, Scriptaculous : false }; exports.yui = { YUI : false, Y : false, YUI_config: false }; exports.mocha = { mocha : false, describe : false, xdescribe : false, it : false, xit : false, context : false, xcontext : false, before : false, after : false, beforeEach : false, afterEach : false, suite : false, test : false, setup : false, teardown : false, suiteSetup : false, suiteTeardown : false }; exports.jasmine = { jasmine : false, describe : false, xdescribe : false, it : false, xit : false, beforeEach : false, afterEach : false, setFixtures : false, loadFixtures: false, spyOn : false, expect : false, runs : false, waitsFor : false, waits : false, beforeAll : false, afterAll : false, fail : false, fdescribe : false, fit : false }; },{}]},{},["/node_modules/jshint/src/jshint.js"]); }); ace.define("ace/mode/javascript_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/javascript/jshint"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var lint = require("./javascript/jshint").JSHINT; function startRegex(arr) { return RegExp("^(" + arr.join("|") + ")"); } var disabledWarningsRe = startRegex([ "Bad for in variable '(.+)'.", 'Missing "use strict"' ]); var errorsRe = startRegex([ "Unexpected", "Expected ", "Confusing (plus|minus)", "\\{a\\} unterminated regular expression", "Unclosed ", "Unmatched ", "Unbegun comment", "Bad invocation", "Missing space after", "Missing operator at" ]); var infoRe = startRegex([ "Expected an assignment", "Bad escapement of EOL", "Unexpected comma", "Unexpected space", "Missing radix parameter.", "A leading decimal point can", "\\['{a}'\\] is better written in dot notation.", "'{a}' used out of scope" ]); var JavaScriptWorker = exports.JavaScriptWorker = function(sender) { Mirror.call(this, sender); this.setTimeout(500); this.setOptions(); }; oop.inherits(JavaScriptWorker, Mirror); (function() { this.setOptions = function(options) { this.options = options || { esnext: true, moz: true, devel: true, browser: true, node: true, laxcomma: true, laxbreak: true, lastsemic: true, onevar: false, passfail: false, maxerr: 100, expr: true, multistr: true, globalstrict: true }; this.doc.getValue() && this.deferredUpdate.schedule(100); }; this.changeOptions = function(newOptions) { oop.mixin(this.options, newOptions); this.doc.getValue() && this.deferredUpdate.schedule(100); }; this.isValidJS = function(str) { try { eval("throw 0;" + str); } catch(e) { if (e === 0) return true; } return false }; this.onUpdate = function() { var value = this.doc.getValue(); value = value.replace(/^#!.*\n/, "\n"); if (!value) return this.sender.emit("annotate", []); var errors = []; var maxErrorLevel = this.isValidJS(value) ? "warning" : "error"; lint(value, this.options); var results = lint.errors; var errorAdded = false for (var i = 0; i < results.length; i++) { var error = results[i]; if (!error) continue; var raw = error.raw; var type = "warning"; if (raw == "Missing semicolon.") { var str = error.evidence.substr(error.character); str = str.charAt(str.search(/\S/)); if (maxErrorLevel == "error" && str && /[\w\d{(['"]/.test(str)) { error.reason = 'Missing ";" before statement'; type = "error"; } else { type = "info"; } } else if (disabledWarningsRe.test(raw)) { continue; } else if (infoRe.test(raw)) { type = "info" } else if (errorsRe.test(raw)) { errorAdded = true; type = maxErrorLevel; } else if (raw == "'{a}' is not defined.") { type = "warning"; } else if (raw == "'{a}' is defined but never used.") { type = "info"; } errors.push({ row: error.line-1, column: error.character-1, text: error.reason, type: type, raw: raw }); if (errorAdded) { } } this.sender.emit("annotate", errors); }; }).call(JavaScriptWorker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/mode-html_elixir.js
3,005
ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|async|await|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode "[0-2][0-7]{0,2}|" + // oct "3[0-7][0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ DocCommentHighlightRules.getStartRule("doc-start"), comments("no_regex"), { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "punctuation.operator", regex : /[.](?![.])/, next : "property" }, { token : "keyword.operator", regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], property: [{ token : "text", regex : "\\s+" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", next: "function_arguments" }, { token : "punctuation.operator", regex : /[.](?![.])/ }, { token : "support.function", regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : "support.function.dom", regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : "support.constant", regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : "identifier", regex : identifierRe }, { regex: "", token: "empty", next: "no_regex" } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("start"), { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); } else if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); if (!options || options.jsx != false) JSX.call(this); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); function JSX() { var tagRegex = identifierRe.replace("\\d", "\\d\\-"); var jsxTag = { onMatch : function(val, state, stack) { var offset = val.charAt(1) == "/" ? 2 : 1; if (offset == 1) { if (state != this.nextState) stack.unshift(this.next, this.nextState, 0); else stack.unshift(this.next); stack[2]++; } else if (offset == 2) { if (state == this.nextState) { stack[1]--; if (!stack[1] || stack[1] < 0) { stack.shift(); stack.shift(); } } } return [{ type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", value: val.slice(0, offset) }, { type: "meta.tag.tag-name.xml", value: val.substr(offset) }]; }, regex : "</?" + tagRegex + "", next: "jsxAttributes", nextState: "jsx" }; this.$rules.start.unshift(jsxTag); var jsxJsRule = { regex: "{", token: "paren.quasi.start", push: "start" }; this.$rules.jsx = [ jsxJsRule, jsxTag, {include : "reference"}, {defaultToken: "string"} ]; this.$rules.jsxAttributes = [{ token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", onMatch : function(value, currentState, stack) { if (currentState == stack[0]) stack.shift(); if (value.length == 2) { if (stack[0] == this.nextState) stack[1]--; if (!stack[1] || stack[1] < 0) { stack.splice(0, 2); } } this.next = stack[0] || "start"; return [{type: this.token, value: value}]; }, nextState: "jsx" }, jsxJsRule, comments("jsxAttributes"), { token : "entity.other.attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { token : "text.tag-whitespace.xml", regex : "\\s+" }, { token : "string.attribute-value.xml", regex : "'", stateName : "jsx_attr_q", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', stateName : "jsx_attr_qq", push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, jsxTag ]; this.$rules.reference = [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }]; } function comments(next) { return [ { token : "comment", // multi line comment regex : /\/\*/, next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] }, { token : "comment", regex : "\\/\\/", next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] } ]; } exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/elixir_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var ElixirHighlightRules = function() { this.$rules = { start: [ { token: [ 'meta.module.elixir', 'keyword.control.module.elixir', 'meta.module.elixir', 'entity.name.type.module.elixir' ], regex: '^(\\s*)(defmodule)(\\s+)((?:[A-Z]\\w*\\s*\\.\\s*)*[A-Z]\\w*)' }, { token: 'comment.documentation.heredoc', regex: '@(?:module|type)?doc (?:~[a-z])?"""', push: [ { token: 'comment.documentation.heredoc', regex: '\\s*"""', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'comment.documentation.heredoc' } ], comment: '@doc with heredocs is treated as documentation' }, { token: 'comment.documentation.heredoc', regex: '@(?:module|type)?doc ~[A-Z]"""', push: [ { token: 'comment.documentation.heredoc', regex: '\\s*"""', next: 'pop' }, { defaultToken: 'comment.documentation.heredoc' } ], comment: '@doc with heredocs is treated as documentation' }, { token: 'comment.documentation.heredoc', regex: '@(?:module|type)?doc (?:~[a-z])?\'\'\'', push: [ { token: 'comment.documentation.heredoc', regex: '\\s*\'\'\'', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'comment.documentation.heredoc' } ], comment: '@doc with heredocs is treated as documentation' }, { token: 'comment.documentation.heredoc', regex: '@(?:module|type)?doc ~[A-Z]\'\'\'', push: [ { token: 'comment.documentation.heredoc', regex: '\\s*\'\'\'', next: 'pop' }, { defaultToken: 'comment.documentation.heredoc' } ], comment: '@doc with heredocs is treated as documentation' }, { token: 'comment.documentation.false', regex: '@(?:module|type)?doc false', comment: '@doc false is treated as documentation' }, { token: 'comment.documentation.string', regex: '@(?:module|type)?doc "', push: [ { token: 'comment.documentation.string', regex: '"', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'comment.documentation.string' } ], comment: '@doc with string is treated as documentation' }, { token: 'keyword.control.elixir', regex: '\\b(?:do|end|case|bc|lc|for|if|cond|unless|try|receive|fn|defmodule|defp?|defprotocol|defimpl|defrecord|defstruct|defmacrop?|defdelegate|defcallback|defmacrocallback|defexception|defoverridable|exit|after|rescue|catch|else|raise|throw|import|require|alias|use|quote|unquote|super)\\b(?![?!])', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<!\\.)\\b(do|end|case|bc|lc|for|if|cond|unless|try|receive|fn|defmodule|defp?|defprotocol|defimpl|defrecord|defstruct|defmacrop?|defdelegate|defcallback|defmacrocallback|defexception|defoverridable|exit|after|rescue|catch|else|raise|throw|import|require|alias|use|quote|unquote|super)\\b(?![?!])' }, { token: 'keyword.operator.elixir', regex: '\\b(?:and|not|or|when|xor|in|inlist|inbits)\\b', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<!\\.)\\b(and|not|or|when|xor|in|inlist|inbits)\\b', comment: ' as above, just doesn\'t need a \'end\' and does a logic operation' }, { token: 'constant.language.elixir', regex: '\\b(?:nil|true|false)\\b(?![?!])' }, { token: 'variable.language.elixir', regex: '\\b__(?:CALLER|ENV|MODULE|DIR)__\\b(?![?!])' }, { token: [ 'punctuation.definition.variable.elixir', 'variable.other.readwrite.module.elixir' ], regex: '(@)([a-zA-Z_]\\w*)' }, { token: [ 'punctuation.definition.variable.elixir', 'variable.other.anonymous.elixir' ], regex: '(&)(\\d*)' }, { token: 'variable.other.constant.elixir', regex: '\\b[A-Z]\\w*\\b' }, { token: 'constant.numeric.elixir', regex: '\\b(?:0x[\\da-fA-F](?:_?[\\da-fA-F])*|\\d(?:_?\\d)*(?:\\.(?![^[:space:][:digit:]])(?:_?\\d)*)?(?:[eE][-+]?\\d(?:_?\\d)*)?|0b[01]+|0o[0-7]+)\\b', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '\\b(0x\\h(?>_?\\h)*|\\d(?>_?\\d)*(\\.(?![^[:space:][:digit:]])(?>_?\\d)*)?([eE][-+]?\\d(?>_?\\d)*)?|0b[01]+|0o[0-7]+)\\b' }, { token: 'punctuation.definition.constant.elixir', regex: ':\'', push: [ { token: 'punctuation.definition.constant.elixir', regex: '\'', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'constant.other.symbol.single-quoted.elixir' } ] }, { token: 'punctuation.definition.constant.elixir', regex: ':"', push: [ { token: 'punctuation.definition.constant.elixir', regex: '"', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'constant.other.symbol.double-quoted.elixir' } ] }, { token: 'punctuation.definition.string.begin.elixir', regex: '(?:\'\'\')', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?>\'\'\')', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '^\\s*\'\'\'', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'support.function.variable.quoted.single.heredoc.elixir' } ], comment: 'Single-quoted heredocs' }, { token: 'punctuation.definition.string.begin.elixir', regex: '\'', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\'', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'support.function.variable.quoted.single.elixir' } ], comment: 'single quoted string (allows for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '(?:""")', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?>""")', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '^\\s*"""', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.quoted.double.heredoc.elixir' } ], comment: 'Double-quoted heredocs' }, { token: 'punctuation.definition.string.begin.elixir', regex: '"', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '"', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.quoted.double.elixir' } ], comment: 'double quoted string (allows for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z](?:""")', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '~[a-z](?>""")', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '^\\s*"""', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.quoted.double.heredoc.elixir' } ], comment: 'Double-quoted heredocs sigils' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z]\\{', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\}[a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z]\\[', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\][a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z]\\<', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\>[a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z]\\(', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\)[a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[a-z][^\\w]', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '[^\\w][a-z]*', next: 'pop' }, { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { include: '#escaped_char' }, { defaultToken: 'string.interpolated.elixir' } ], comment: 'sigil (allow for interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z](?:""")', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '~[A-Z](?>""")', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '^\\s*"""', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'Double-quoted heredocs sigils' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z]\\{', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\}[a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z]\\[', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\][a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z]\\<', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\>[a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z]\\(', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '\\)[a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: 'punctuation.definition.string.begin.elixir', regex: '~[A-Z][^\\w]', push: [ { token: 'punctuation.definition.string.end.elixir', regex: '[^\\w][a-z]*', next: 'pop' }, { defaultToken: 'string.quoted.other.literal.upper.elixir' } ], comment: 'sigil (without interpolation)' }, { token: ['punctuation.definition.constant.elixir', 'constant.other.symbol.elixir'], regex: '(:)([a-zA-Z_][\\w@]*(?:[?!]|=(?![>=]))?|\\<\\>|===?|!==?|<<>>|<<<|>>>|~~~|::|<\\-|\\|>|=>|~|~=|=|/|\\\\\\\\|\\*\\*?|\\.\\.?\\.?|>=?|<=?|&&?&?|\\+\\+?|\\-\\-?|\\|\\|?\\|?|\\!|@|\\%?\\{\\}|%|\\[\\]|\\^(?:\\^\\^)?)', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<!:)(:)(?>[a-zA-Z_][\\w@]*(?>[?!]|=(?![>=]))?|\\<\\>|===?|!==?|<<>>|<<<|>>>|~~~|::|<\\-|\\|>|=>|~|~=|=|/|\\\\\\\\|\\*\\*?|\\.\\.?\\.?|>=?|<=?|&&?&?|\\+\\+?|\\-\\-?|\\|\\|?\\|?|\\!|@|\\%?\\{\\}|%|\\[\\]|\\^(\\^\\^)?)', comment: 'symbols' }, { token: 'punctuation.definition.constant.elixir', regex: '(?:[a-zA-Z_][\\w@]*(?:[?!])?):(?!:)', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?>[a-zA-Z_][\\w@]*(?>[?!])?)(:)(?!:)', comment: 'symbols' }, { token: [ 'punctuation.definition.comment.elixir', 'comment.line.number-sign.elixir' ], regex: '(#)(.*)' }, { token: 'constant.numeric.elixir', regex: '\\?(?:\\\\(?:x[\\da-fA-F]{1,2}(?![\\da-fA-F])\\b|[^xMC])|[^\\s\\\\])', TODO: 'FIXME: regexp doesn\'t have js equivalent', originalRegex: '(?<!\\w)\\?(\\\\(x\\h{1,2}(?!\\h)\\b|[^xMC])|[^\\s\\\\])', comment: '\n\t\t\tmatches questionmark-letters.\n\n\t\t\texamples (1st alternation = hex):\n\t\t\t?\\x1 ?\\x61\n\n\t\t\texamples (2rd alternation = escaped):\n\t\t\t?\\n ?\\b\n\n\t\t\texamples (3rd alternation = normal):\n\t\t\t?a ?A ?0 \n\t\t\t?* ?" ?( \n\t\t\t?. ?#\n\t\t\t\n\t\t\tthe negative lookbehind prevents against matching\n\t\t\tp(42.tainted?)\n\t\t\t' }, { token: 'keyword.operator.assignment.augmented.elixir', regex: '\\+=|\\-=|\\|\\|=|~=|&&=' }, { token: 'keyword.operator.comparison.elixir', regex: '===?|!==?|<=?|>=?' }, { token: 'keyword.operator.bitwise.elixir', regex: '\\|{3}|&{3}|\\^{3}|<{3}|>{3}|~{3}' }, { token: 'keyword.operator.logical.elixir', regex: '!+|\\bnot\\b|&&|\\band\\b|\\|\\||\\bor\\b|\\bxor\\b', originalRegex: '(?<=[ \\t])!+|\\bnot\\b|&&|\\band\\b|\\|\\||\\bor\\b|\\bxor\\b' }, { token: 'keyword.operator.arithmetic.elixir', regex: '\\*|\\+|\\-|/' }, { token: 'keyword.operator.other.elixir', regex: '\\||\\+\\+|\\-\\-|\\*\\*|\\\\\\\\|\\<\\-|\\<\\>|\\<\\<|\\>\\>|\\:\\:|\\.\\.|\\|>|~|=>' }, { token: 'keyword.operator.assignment.elixir', regex: '=' }, { token: 'punctuation.separator.other.elixir', regex: ':' }, { token: 'punctuation.separator.statement.elixir', regex: '\\;' }, { token: 'punctuation.separator.object.elixir', regex: ',' }, { token: 'punctuation.separator.method.elixir', regex: '\\.' }, { token: 'punctuation.section.scope.elixir', regex: '\\{|\\}' }, { token: 'punctuation.section.array.elixir', regex: '\\[|\\]' }, { token: 'punctuation.section.function.elixir', regex: '\\(|\\)' } ], '#escaped_char': [ { token: 'constant.character.escape.elixir', regex: '\\\\(?:x[\\da-fA-F]{1,2}|.)' } ], '#interpolated_elixir': [ { token: [ 'source.elixir.embedded.source', 'source.elixir.embedded.source.empty' ], regex: '(#\\{)(\\})' }, { todo: { token: 'punctuation.section.embedded.elixir', regex: '#\\{', push: [ { token: 'punctuation.section.embedded.elixir', regex: '\\}', next: 'pop' }, { include: '#nest_curly_and_self' }, { include: '$self' }, { defaultToken: 'source.elixir.embedded.source' } ] } } ], '#nest_curly_and_self': [ { token: 'punctuation.section.scope.elixir', regex: '\\{', push: [ { token: 'punctuation.section.scope.elixir', regex: '\\}', next: 'pop' }, { include: '#nest_curly_and_self' } ] }, { include: '$self' } ], '#regex_sub': [ { include: '#interpolated_elixir' }, { include: '#escaped_char' }, { token: [ 'punctuation.definition.arbitrary-repitition.elixir', 'string.regexp.arbitrary-repitition.elixir', 'string.regexp.arbitrary-repitition.elixir', 'punctuation.definition.arbitrary-repitition.elixir' ], regex: '(\\{)(\\d+)((?:,\\d+)?)(\\})' }, { token: 'punctuation.definition.character-class.elixir', regex: '\\[(?:\\^?\\])?', push: [ { token: 'punctuation.definition.character-class.elixir', regex: '\\]', next: 'pop' }, { include: '#escaped_char' }, { defaultToken: 'string.regexp.character-class.elixir' } ] }, { token: 'punctuation.definition.group.elixir', regex: '\\(', push: [ { token: 'punctuation.definition.group.elixir', regex: '\\)', next: 'pop' }, { include: '#regex_sub' }, { defaultToken: 'string.regexp.group.elixir' } ] }, { token: [ 'punctuation.definition.comment.elixir', 'comment.line.number-sign.elixir' ], regex: '(?:^|\\s)(#)(\\s[[a-zA-Z0-9,. \\t?!-][^\\x00-\\x7F]]*$)', originalRegex: '(?<=^|\\s)(#)\\s[[a-zA-Z0-9,. \\t?!-][^\\x{00}-\\x{7F}]]*$', comment: 'We are restrictive in what we allow to go after the comment character to avoid false positives, since the availability of comments depend on regexp flags.' } ] } this.normalizeRules(); }; ElixirHighlightRules.metaData = { comment: 'Textmate bundle for Elixir Programming Language.', fileTypes: [ 'ex', 'exs' ], firstLineMatch: '^#!/.*\\belixir', foldingStartMarker: '(after|else|catch|rescue|\\-\\>|\\{|\\[|do)\\s*$', foldingStopMarker: '^\\s*((\\}|\\]|after|else|catch|rescue)\\s*$|end\\b)', keyEquivalent: '^~E', name: 'Elixir', scopeName: 'source.elixir' } oop.inherits(ElixirHighlightRules, TextHighlightRules); exports.ElixirHighlightRules = ElixirHighlightRules; }); ace.define("ace/mode/html_elixir_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/html_highlight_rules","ace/mode/elixir_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var ElixirHighlightRules = require("./elixir_highlight_rules").ElixirHighlightRules; var HtmlElixirHighlightRules = function() { HtmlHighlightRules.call(this); var startRules = [ { regex: "<%%|%%>", token: "constant.language.escape" }, { token : "comment.start.eex", regex : "<%#", push : [{ token : "comment.end.eex", regex: "%>", next: "pop", defaultToken:"comment" }] }, { token : "support.elixir_tag", regex : "<%+(?!>)[-=]?", push : "elixir-start" } ]; var endRules = [ { token : "support.elixir_tag", regex : "%>", next : "pop" }, { token: "comment", regex: "#(?:[^%]|%[^>])*" } ]; for (var key in this.$rules) this.$rules[key].unshift.apply(this.$rules[key], startRules); this.embedRules(ElixirHighlightRules, "elixir-", endRules, ["start"]); this.normalizeRules(); }; oop.inherits(HtmlElixirHighlightRules, HtmlHighlightRules); exports.HtmlElixirHighlightRules = HtmlElixirHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_completions",["require","exports","module"], function(require, exports, module) { "use strict"; var propertyMap = { "background": {"#$0": 1}, "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, "background-image": {"url('/$0')": 1}, "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, "background-attachment": {"scroll": 1, "fixed": 1}, "background-size": {"cover": 1, "contain": 1}, "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, "border-color": {"#$0": 1}, "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, "border-collapse": {"collapse": 1, "separate": 1}, "bottom": {"px": 1, "em": 1, "%": 1}, "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, "empty-cells": {"show": 1, "hide": 1}, "float": {"left": 1, "right": 1, "none": 1}, "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, "font-size": {"px": 1, "em": 1, "%": 1}, "font-weight": {"bold": 1, "normal": 1}, "font-style": {"italic": 1, "normal": 1}, "font-variant": {"normal": 1, "small-caps": 1}, "height": {"px": 1, "em": 1, "%": 1}, "left": {"px": 1, "em": 1, "%": 1}, "letter-spacing": {"normal": 1}, "line-height": {"normal": 1}, "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, "margin": {"px": 1, "em": 1, "%": 1}, "margin-right": {"px": 1, "em": 1, "%": 1}, "margin-left": {"px": 1, "em": 1, "%": 1}, "margin-top": {"px": 1, "em": 1, "%": 1}, "margin-bottom": {"px": 1, "em": 1, "%": 1}, "max-height": {"px": 1, "em": 1, "%": 1}, "max-width": {"px": 1, "em": 1, "%": 1}, "min-height": {"px": 1, "em": 1, "%": 1}, "min-width": {"px": 1, "em": 1, "%": 1}, "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "padding": {"px": 1, "em": 1, "%": 1}, "padding-top": {"px": 1, "em": 1, "%": 1}, "padding-right": {"px": 1, "em": 1, "%": 1}, "padding-bottom": {"px": 1, "em": 1, "%": 1}, "padding-left": {"px": 1, "em": 1, "%": 1}, "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, "right": {"px": 1, "em": 1, "%": 1}, "table-layout": {"fixed": 1, "auto": 1}, "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, "top": {"px": 1, "em": 1, "%": 1}, "vertical-align": {"top": 1, "bottom": 1}, "visibility": {"hidden": 1, "visible": 1}, "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, "width": {"px": 1, "em": 1, "%": 1}, "word-spacing": {"normal": 1}, "filter": {"alpha(opacity=$0100)": 1}, "text-shadow": {"$02px 2px 2px #777": 1}, "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, "-moz-border-radius": 1, "-moz-border-radius-topright": 1, "-moz-border-radius-bottomright": 1, "-moz-border-radius-topleft": 1, "-moz-border-radius-bottomleft": 1, "-webkit-border-radius": 1, "-webkit-border-top-right-radius": 1, "-webkit-border-top-left-radius": 1, "-webkit-border-bottom-right-radius": 1, "-webkit-border-bottom-left-radius": 1, "-moz-box-shadow": 1, "-webkit-box-shadow": 1, "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } }; var CssCompletions = function() { }; (function() { this.completionsDefined = false; this.defineCompletions = function() { if (document) { var style = document.createElement('c').style; for (var i in style) { if (typeof style[i] !== 'string') continue; var name = i.replace(/[A-Z]/g, function(x) { return '-' + x.toLowerCase(); }); if (!propertyMap.hasOwnProperty(name)) propertyMap[name] = 1; } } this.completionsDefined = true; } this.getCompletions = function(state, session, pos, prefix) { if (!this.completionsDefined) { this.defineCompletions(); } var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (state==='ruleset'){ var line = session.getLine(pos.row).substr(0, pos.column); if (/:[^;]+$/.test(line)) { /([\w\-]+):[^:]*$/.test(line); return this.getPropertyValueCompletions(state, session, pos, prefix); } else { return this.getPropertyCompletions(state, session, pos, prefix); } } return []; }; this.getPropertyCompletions = function(state, session, pos, prefix) { var properties = Object.keys(propertyMap); return properties.map(function(property){ return { caption: property, snippet: property + ': $0', meta: "property", score: Number.MAX_VALUE }; }); }; this.getPropertyValueCompletions = function(state, session, pos, prefix) { var line = session.getLine(pos.row).substr(0, pos.column); var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; if (!property) return []; var values = []; if (property in propertyMap && typeof propertyMap[property] === "object") { values = Object.keys(propertyMap[property]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "property value", score: Number.MAX_VALUE }; }); }; }).call(CssCompletions.prototype); exports.CssCompletions = CssCompletions; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssCompletions = require("./css_completions").CssCompletions; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.$completer = new CssCompletions(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": {"manifest": 1}, "head": {}, "title": {}, "base": {"href": 1, "target": 1}, "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, "noscript": {"href": 1}, "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, "section": {}, "nav": {}, "article": {"pubdate": 1}, "aside": {}, "h1": {}, "h2": {}, "h3": {}, "h4": {}, "h5": {}, "h6": {}, "header": {}, "footer": {}, "address": {}, "main": {}, "p": {}, "hr": {}, "pre": {}, "blockquote": {"cite": 1}, "ol": {"start": 1, "reversed": 1}, "ul": {}, "li": {"value": 1}, "dl": {}, "dt": {}, "dd": {}, "figure": {}, "figcaption": {}, "div": {}, "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, "em": {}, "strong": {}, "small": {}, "s": {}, "cite": {}, "q": {"cite": 1}, "dfn": {}, "abbr": {}, "data": {}, "time": {"datetime": 1}, "code": {}, "var": {}, "samp": {}, "kbd": {}, "sub": {}, "sup": {}, "i": {}, "b": {}, "u": {}, "mark": {}, "ruby": {}, "rt": {}, "rp": {}, "bdi": {}, "bdo": {}, "span": {}, "br": {}, "wbr": {}, "ins": {"cite": 1, "datetime": 1}, "del": {"cite": 1, "datetime": 1}, "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, "param": {"name": 1, "value": 1}, "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, "source": {"src": 1, "type": 1, "media": 1}, "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, "canvas": {"width": 1, "height": 1}, "map": {"name": 1}, "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, "svg": {}, "math": {}, "table": {"summary": 1}, "caption": {}, "colgroup": {"span": 1}, "col": {"span": 1}, "tbody": {}, "thead": {}, "tfoot": {}, "tr": {}, "td": {"headers": 1, "rowspan": 1, "colspan": 1}, "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, "fieldset": {"disabled": 1, "form": 1, "name": 1}, "legend": {}, "label": {"form": 1, "for": 1}, "input": { "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, "datalist": {}, "optgroup": {"disabled": 1, "label": 1}, "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, "output": {"for": 1, "form": 1, "name": 1}, "progress": {"value": 1, "max": 1}, "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, "details": {"open": 1}, "summary": {}, "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, "menu": {"type": 1, "label": 1}, "dialog": {"open": 1} }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } function findAttributeName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "attribute-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompletions(state, session, pos, prefix); if (is(token, "attribute-value")) return this.getAttributeValueCompletions(state, session, pos, prefix); var line = session.getLine(pos.row).substr(0, pos.column); if (/&[A-z]*$/i.test(line)) return this.getHTMLEntityCompletions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(Object.keys(attributeMap[tagName])); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; this.getAttributeValueCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); var attributeName = findAttributeName(session, pos); if (!tagName) return []; var values = []; if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { values = Object.keys(attributeMap[tagName][attributeName]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "attribute value", score: Number.MAX_VALUE }; }); }; this.getHTMLEntityCompletions = function(state, session, pos, prefix) { var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; return values.map(function(value){ return { caption: value, snippet: value, meta: "html entity", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != "#") return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != "#") break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent!= -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start"; else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start"; else return ""; }; }).call(FoldMode.prototype); }); ace.define("ace/mode/elixir",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/elixir_highlight_rules","ace/mode/folding/coffee"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var ElixirHighlightRules = require("./elixir_highlight_rules").ElixirHighlightRules; var FoldMode = require("./folding/coffee").FoldMode; var Mode = function() { this.HighlightRules = ElixirHighlightRules; this.foldingRules = new FoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.$id = "ace/mode/elixir" }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/html_elixir",["require","exports","module","ace/lib/oop","ace/mode/html_elixir_highlight_rules","ace/mode/html","ace/mode/javascript","ace/mode/css","ace/mode/elixir"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlElixirHighlightRules = require("./html_elixir_highlight_rules").HtmlElixirHighlightRules; var HtmlMode = require("./html").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var ElixirMode = require("./elixir").Mode; var Mode = function() { HtmlMode.call(this); this.HighlightRules = HtmlElixirHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode, "elixir-": ElixirMode }); }; oop.inherits(Mode, HtmlMode); (function() { this.$id = "ace/mode/html_elixir"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace/mode-luapage.js
2,935
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ { token : "comment", regex : "\\/\\/", next : "line_comment" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "keyword.operator", regex : /--|\+\+|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/", next : "line_comment_regex_allowed" }, { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); return "paren"; } if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var getWrapped = function(selection, selected, opening, closing) { var rowDiff = selection.end.row - selection.start.row; return { text: opening + selected + closing, selection: [ 0, selection.start.column + 1, rowDiff, selection.end.column + (rowDiff ? 0 : 1) ] }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '{', '}'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '(', ')'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '[', ']'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, quote, quote); } else if (!selected) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); var rightChar = line.substring(cursor.column, cursor.column + 1); var token = session.getTokenAt(cursor.row, cursor.column); var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); if (leftChar == "\\" && token && /escape/.test(token.type)) return null; var stringBefore = token && /string|escape/.test(token.type); var stringAfter = !rightToken || /string|escape/.test(rightToken.type); var pair; if (rightChar == quote) { pair = stringBefore !== stringAfter; } else { if (stringBefore && !stringAfter) return null; // wrap string with different quote if (stringBefore && stringAfter) return null; // do not pair quotes inside strings var wordRe = session.$mode.tokenRe; wordRe.lastIndex = 0; var isWordBefore = wordRe.test(leftChar); wordRe.lastIndex = 0; var isWordAfter = wordRe.test(leftChar); if (isWordBefore || isWordAfter) return null; // before or after alphanumeric if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) return null; // there is rightChar and it isn't closing pair = true; } return { text: pair ? quote + quote : "", selection: [1,1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction", }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ], }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(JavaScriptHighlightRules, "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getCursorPosition(); var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": ["manifest"], "head": [], "title": [], "base": ["href", "target"], "link": ["href", "hreflang", "rel", "media", "type", "sizes"], "meta": ["http-equiv", "name", "content", "charset"], "style": ["type", "media", "scoped"], "script": ["charset", "type", "src", "defer", "async"], "noscript": ["href"], "body": ["onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onmessage", "onoffline", "onpopstate", "onredo", "onresize", "onstorage", "onundo", "onunload"], "section": [], "nav": [], "article": ["pubdate"], "aside": [], "h1": [], "h2": [], "h3": [], "h4": [], "h5": [], "h6": [], "header": [], "footer": [], "address": [], "main": [], "p": [], "hr": [], "pre": [], "blockquote": ["cite"], "ol": ["start", "reversed"], "ul": [], "li": ["value"], "dl": [], "dt": [], "dd": [], "figure": [], "figcaption": [], "div": [], "a": ["href", "target", "ping", "rel", "media", "hreflang", "type"], "em": [], "strong": [], "small": [], "s": [], "cite": [], "q": ["cite"], "dfn": [], "abbr": [], "data": [], "time": ["datetime"], "code": [], "var": [], "samp": [], "kbd": [], "sub": [], "sup": [], "i": [], "b": [], "u": [], "mark": [], "ruby": [], "rt": [], "rp": [], "bdi": [], "bdo": [], "span": [], "br": [], "wbr": [], "ins": ["cite", "datetime"], "del": ["cite", "datetime"], "img": ["alt", "src", "height", "width", "usemap", "ismap"], "iframe": ["name", "src", "height", "width", "sandbox", "seamless"], "embed": ["src", "height", "width", "type"], "object": ["param", "data", "type", "height" , "width", "usemap", "name", "form", "classid"], "param": ["name", "value"], "video": ["src", "autobuffer", "autoplay", "loop", "controls", "width", "height", "poster"], "audio": ["src", "autobuffer", "autoplay", "loop", "controls"], "source": ["src", "type", "media"], "track": ["kind", "src", "srclang", "label", "default"], "canvas": ["width", "height"], "map": ["name"], "area": ["shape", "coords", "href", "hreflang", "alt", "target", "media", "rel", "ping", "type"], "svg": [], "math": [], "table": ["summary"], "caption": [], "colgroup": ["span"], "col": ["span"], "tbody": [], "thead": [], "tfoot": [], "tr": [], "td": ["headers", "rowspan", "colspan"], "th": ["headers", "rowspan", "colspan", "scope"], "form": ["accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target"], "fieldset": ["disabled", "form", "name"], "legend": [], "label": ["form", "for"], "input": ["type", "accept", "alt", "autocomplete", "checked", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "list", "max", "maxlength", "min", "multiple", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "width", "files", "value"], "button": ["autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "value", "type"], "select": ["autofocus", "disabled", "form", "multiple", "name", "size"], "datalist": [], "optgroup": ["disabled", "label"], "option": ["disabled", "selected", "label", "value"], "textarea": ["autofocus", "disabled", "form", "maxlength", "name", "placeholder", "readonly", "required", "rows", "cols", "wrap"], "keygen": ["autofocus", "challenge", "disabled", "form", "keytype", "name"], "output": ["for", "form", "name"], "progress": ["value", "max"], "meter": ["value", "min", "max", "low", "high", "optimum"], "details": ["open"], "summary": [], "command": ["type", "label", "icon", "disabled", "checked", "radiogroup", "command"], "menu": ["type", "label"], "dialog": ["open"] }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompetions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompetions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(attributeMap[tagName]); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/lua_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var LuaHighlightRules = function() { var keywords = ( "break|do|else|elseif|end|for|function|if|in|local|repeat|"+ "return|then|until|while|or|and|not" ); var builtinConstants = ("true|false|nil|_G|_VERSION"); var functions = ( "string|xpcall|package|tostring|print|os|unpack|require|"+ "getfenv|setmetatable|next|assert|tonumber|io|rawequal|"+ "collectgarbage|getmetatable|module|rawset|math|debug|"+ "pcall|table|newproxy|type|coroutine|_G|select|gcinfo|"+ "pairs|rawget|loadstring|ipairs|_VERSION|dofile|setfenv|"+ "load|error|loadfile|"+ "sub|upper|len|gfind|rep|find|match|char|dump|gmatch|"+ "reverse|byte|format|gsub|lower|preload|loadlib|loaded|"+ "loaders|cpath|config|path|seeall|exit|setlocale|date|"+ "getenv|difftime|remove|time|clock|tmpname|rename|execute|"+ "lines|write|close|flush|open|output|type|read|stderr|"+ "stdin|input|stdout|popen|tmpfile|log|max|acos|huge|"+ "ldexp|pi|cos|tanh|pow|deg|tan|cosh|sinh|random|randomseed|"+ "frexp|ceil|floor|rad|abs|sqrt|modf|asin|min|mod|fmod|log10|"+ "atan2|exp|sin|atan|getupvalue|debug|sethook|getmetatable|"+ "gethook|setmetatable|setlocal|traceback|setfenv|getinfo|"+ "setupvalue|getlocal|getregistry|getfenv|setn|insert|getn|"+ "foreachi|maxn|foreach|concat|sort|remove|resume|yield|"+ "status|wrap|create|running|"+ "__add|__sub|__mod|__unm|__concat|__lt|__index|__call|__gc|__metatable|"+ "__mul|__div|__pow|__len|__eq|__le|__newindex|__tostring|__mode|__tonumber" ); var stdLibaries = ("string|package|os|io|math|debug|table|coroutine"); var futureReserved = ""; var deprecatedIn5152 = ("setn|foreach|foreachi|gcinfo|log10|maxn"); var keywordMapper = this.createKeywordMapper({ "keyword": keywords, "support.function": functions, "invalid.deprecated": deprecatedIn5152, "constant.library": stdLibaries, "constant.language": builtinConstants, "invalid.illegal": futureReserved, "variable.language": "self" }, "identifier"); var decimalInteger = "(?:(?:[1-9]\\d*)|(?:0))"; var hexInteger = "(?:0[xX][\\dA-Fa-f]+)"; var integer = "(?:" + decimalInteger + "|" + hexInteger + ")"; var fraction = "(?:\\.\\d+)"; var intPart = "(?:\\d+)"; var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))"; var floatNumber = "(?:" + pointFloat + ")"; this.$rules = { "start" : [{ stateName: "bracketedComment", onMatch : function(value, currentState, stack){ stack.unshift(this.next, value.length - 2, currentState); return "comment"; }, regex : /\-\-\[=*\[/, next : [ { onMatch : function(value, currentState, stack) { if (value.length == stack[1]) { stack.shift(); stack.shift(); this.next = stack.shift(); } else { this.next = ""; } return "comment"; }, regex : /\]=*\]/, next : "start" }, { defaultToken : "comment" } ] }, { token : "comment", regex : "\\-\\-.*$" }, { stateName: "bracketedString", onMatch : function(value, currentState, stack){ stack.unshift(this.next, value.length, currentState); return "comment"; }, regex : /\[=*\[/, next : [ { onMatch : function(value, currentState, stack) { if (value.length == stack[1]) { stack.shift(); stack.shift(); this.next = stack.shift(); } else { this.next = ""; } return "comment"; }, regex : /\]=*\]/, next : "start" }, { defaultToken : "comment" } ] }, { token : "string", // " string regex : '"(?:[^\\\\]|\\\\.)*?"' }, { token : "string", // ' string regex : "'(?:[^\\\\]|\\\\.)*?'" }, { token : "constant.numeric", // float regex : floatNumber }, { token : "constant.numeric", // integer regex : integer + "\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "keyword.operator", regex : "\\+|\\-|\\*|\\/|%|\\#|\\^|~|<|>|<=|=>|==|~=|=|\\:|\\.\\.\\.|\\.\\." }, { token : "paren.lparen", regex : "[\\[\\(\\{]" }, { token : "paren.rparen", regex : "[\\]\\)\\}]" }, { token : "text", regex : "\\s+|\\w+" } ] }; this.normalizeRules(); } oop.inherits(LuaHighlightRules, TextHighlightRules); exports.LuaHighlightRules = LuaHighlightRules; }); ace.define("ace/mode/folding/lua",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /\b(function|then|do|repeat)\b|{\s*$|(\[=*\[)/; this.foldingStopMarker = /\bend\b|^\s*}|\]=*\]/; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var isStart = this.foldingStartMarker.test(line); var isEnd = this.foldingStopMarker.test(line); if (isStart && !isEnd) { var match = line.match(this.foldingStartMarker); if (match[1] == "then" && /\belseif\b/.test(line)) return; if (match[1]) { if (session.getTokenAt(row, match.index + 1).type === "keyword") return "start"; } else if (match[2]) { var type = session.bgTokenizer.getState(row) || ""; if (type[0] == "bracketedComment" || type[0] == "bracketedString") return "start"; } else { return "start"; } } if (foldStyle != "markbeginend" || !isEnd || isStart && isEnd) return ""; var match = line.match(this.foldingStopMarker); if (match[0] === "end") { if (session.getTokenAt(row, match.index + 1).type === "keyword") return "end"; } else if (match[0][0] === "]") { var type = session.bgTokenizer.getState(row - 1) || ""; if (type[0] == "bracketedComment" || type[0] == "bracketedString") return "end"; } else return "end"; }; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.doc.getLine(row); var match = this.foldingStartMarker.exec(line); if (match) { if (match[1]) return this.luaBlock(session, row, match.index + 1); if (match[2]) return session.getCommentFoldRange(row, match.index + 1); return this.openingBracketBlock(session, "{", row, match.index); } var match = this.foldingStopMarker.exec(line); if (match) { if (match[0] === "end") { if (session.getTokenAt(row, match.index + 1).type === "keyword") return this.luaBlock(session, row, match.index + 1); } if (match[0][0] === "]") return session.getCommentFoldRange(row, match.index + 1); return this.closingBracketBlock(session, "}", row, match.index + match[0].length); } }; this.luaBlock = function(session, row, column) { var stream = new TokenIterator(session, row, column); var indentKeywords = { "function": 1, "do": 1, "then": 1, "elseif": -1, "end": -1, "repeat": 1, "until": -1 }; var token = stream.getCurrentToken(); if (!token || token.type != "keyword") return; var val = token.value; var stack = [val]; var dir = indentKeywords[val]; if (!dir) return; var startColumn = dir === -1 ? stream.getCurrentTokenColumn() : session.getLine(row).length; var startRow = row; stream.step = dir === -1 ? stream.stepBackward : stream.stepForward; while(token = stream.step()) { if (token.type !== "keyword") continue; var level = dir * indentKeywords[token.value]; if (level > 0) { stack.unshift(token.value); } else if (level <= 0) { stack.shift(); if (!stack.length && token.value != "elseif") break; if (level === 0) stack.unshift(token.value); } } var row = stream.getCurrentTokenRow(); if (dir === -1) return new Range(row, session.getLine(row).length, startRow, startColumn); else return new Range(startRow, startColumn, row, stream.getCurrentTokenColumn()); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/lua",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/lua_highlight_rules","ace/mode/folding/lua","ace/range","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules; var LuaFoldMode = require("./folding/lua").FoldMode; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.HighlightRules = LuaHighlightRules; this.foldingRules = new LuaFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "--"; this.blockComment = {start: "--[", end: "]--"}; var indentKeywords = { "function": 1, "then": 1, "do": 1, "else": 1, "elseif": 1, "repeat": 1, "end": -1, "until": -1 }; var outdentKeywords = [ "else", "elseif", "end", "until" ]; function getNetIndentLevel(tokens) { var level = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (token.type == "keyword") { if (token.value in indentKeywords) { level += indentKeywords[token.value]; } } else if (token.type == "paren.lparen") { level += token.value.length; } else if (token.type == "paren.rparen") { level -= token.value.length; } } if (level < 0) { return -1; } else if (level > 0) { return 1; } else { return 0; } } this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var level = 0; var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (state == "start") { level = getNetIndentLevel(tokens); } if (level > 0) { return indent + tab; } else if (level < 0 && indent.substr(indent.length - tab.length) == tab) { if (!this.checkOutdent(state, line, "\n")) { return indent.substr(0, indent.length - tab.length); } } return indent; }; this.checkOutdent = function(state, line, input) { if (input != "\n" && input != "\r" && input != "\r\n") return false; if (line.match(/^\s*[\)\}\]]$/)) return true; var tokens = this.getTokenizer().getLineTokens(line.trim(), state).tokens; if (!tokens || !tokens.length) return false; return (tokens[0].type == "keyword" && outdentKeywords.indexOf(tokens[0].value) != -1); }; this.autoOutdent = function(state, session, row) { var prevLine = session.getLine(row - 1); var prevIndent = this.$getIndent(prevLine).length; var prevTokens = this.getTokenizer().getLineTokens(prevLine, "start").tokens; var tabLength = session.getTabString().length; var expectedIndent = prevIndent + tabLength * getNetIndentLevel(prevTokens); var curIndent = this.$getIndent(session.getLine(row)).length; if (curIndent < expectedIndent) { return; } session.outdentRows(new Range(row, 0, row + 2, 0)); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/lua_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/lua"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/luapage_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/html_highlight_rules","ace/mode/lua_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var LuaHighlightRules = require("./lua_highlight_rules").LuaHighlightRules; var LuaPageHighlightRules = function() { HtmlHighlightRules.call(this); var startRules = [ { token: "keyword", regex: "<\\%\\=?", push: "lua-start" }, { token: "keyword", regex: "<\\?lua\\=?", push: "lua-start" } ]; var endRules = [ { token: "keyword", regex: "\\%>", next: "pop" }, { token: "keyword", regex: "\\?>", next: "pop" } ]; this.embedRules(LuaHighlightRules, "lua-", endRules, ["start"]); for (var key in this.$rules) this.$rules[key].unshift.apply(this.$rules[key], startRules); this.normalizeRules(); }; oop.inherits(LuaPageHighlightRules, HtmlHighlightRules); exports.LuaPageHighlightRules = LuaPageHighlightRules; }); ace.define("ace/mode/luapage",["require","exports","module","ace/lib/oop","ace/mode/html","ace/mode/lua","ace/mode/luapage_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlMode = require("./html").Mode; var LuaMode = require("./lua").Mode; var LuaPageHighlightRules = require("./luapage_highlight_rules").LuaPageHighlightRules; var Mode = function() { HtmlMode.call(this); this.HighlightRules = LuaPageHighlightRules; this.createModeDelegates({ "lua-": LuaMode }); }; oop.inherits(Mode, HtmlMode); (function() { this.$id = "ace/mode/luapage"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/mode-markdown.js
2,812
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|async|await|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode "[0-2][0-7]{0,2}|" + // oct "3[0-7][0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ DocCommentHighlightRules.getStartRule("doc-start"), comments("no_regex"), { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "punctuation.operator", regex : /[.](?![.])/, next : "property" }, { token : "keyword.operator", regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], property: [{ token : "text", regex : "\\s+" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", next: "function_arguments" }, { token : "punctuation.operator", regex : /[.](?![.])/ }, { token : "support.function", regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : "support.function.dom", regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : "support.constant", regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : "identifier", regex : identifierRe }, { regex: "", token: "empty", next: "no_regex" } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("start"), { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); } else if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); if (!options || options.jsx != false) JSX.call(this); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); function JSX() { var tagRegex = identifierRe.replace("\\d", "\\d\\-"); var jsxTag = { onMatch : function(val, state, stack) { var offset = val.charAt(1) == "/" ? 2 : 1; if (offset == 1) { if (state != this.nextState) stack.unshift(this.next, this.nextState, 0); else stack.unshift(this.next); stack[2]++; } else if (offset == 2) { if (state == this.nextState) { stack[1]--; if (!stack[1] || stack[1] < 0) { stack.shift(); stack.shift(); } } } return [{ type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", value: val.slice(0, offset) }, { type: "meta.tag.tag-name.xml", value: val.substr(offset) }]; }, regex : "</?" + tagRegex + "", next: "jsxAttributes", nextState: "jsx" }; this.$rules.start.unshift(jsxTag); var jsxJsRule = { regex: "{", token: "paren.quasi.start", push: "start" }; this.$rules.jsx = [ jsxJsRule, jsxTag, {include : "reference"}, {defaultToken: "string"} ]; this.$rules.jsxAttributes = [{ token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", onMatch : function(value, currentState, stack) { if (currentState == stack[0]) stack.shift(); if (value.length == 2) { if (stack[0] == this.nextState) stack[1]--; if (!stack[1] || stack[1] < 0) { stack.splice(0, 2); } } this.next = stack[0] || "start"; return [{type: this.token, value: value}]; }, nextState: "jsx" }, jsxJsRule, comments("jsxAttributes"), { token : "entity.other.attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { token : "text.tag-whitespace.xml", regex : "\\s+" }, { token : "string.attribute-value.xml", regex : "'", stateName : "jsx_attr_q", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', stateName : "jsx_attr_qq", push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, jsxTag ]; this.$rules.reference = [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }]; } function comments(next) { return [ { token : "comment", // multi line comment regex : /\/\*/, next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] }, { token : "comment", regex : "\\/\\/", next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] } ]; } exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/xml_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/xml","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var XmlFoldMode = require("./folding/xml").FoldMode; var WorkerClient = require("../worker/worker_client").WorkerClient; var Mode = function() { this.HighlightRules = XmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.foldingRules = new XmlFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.voidElements = lang.arrayToMap([]); this.blockComment = {start: "<!--", end: "-->"}; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/xml_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/xml"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/css_completions",["require","exports","module"], function(require, exports, module) { "use strict"; var propertyMap = { "background": {"#$0": 1}, "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, "background-image": {"url('/$0')": 1}, "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, "background-attachment": {"scroll": 1, "fixed": 1}, "background-size": {"cover": 1, "contain": 1}, "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, "border-color": {"#$0": 1}, "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, "border-collapse": {"collapse": 1, "separate": 1}, "bottom": {"px": 1, "em": 1, "%": 1}, "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, "empty-cells": {"show": 1, "hide": 1}, "float": {"left": 1, "right": 1, "none": 1}, "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, "font-size": {"px": 1, "em": 1, "%": 1}, "font-weight": {"bold": 1, "normal": 1}, "font-style": {"italic": 1, "normal": 1}, "font-variant": {"normal": 1, "small-caps": 1}, "height": {"px": 1, "em": 1, "%": 1}, "left": {"px": 1, "em": 1, "%": 1}, "letter-spacing": {"normal": 1}, "line-height": {"normal": 1}, "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, "margin": {"px": 1, "em": 1, "%": 1}, "margin-right": {"px": 1, "em": 1, "%": 1}, "margin-left": {"px": 1, "em": 1, "%": 1}, "margin-top": {"px": 1, "em": 1, "%": 1}, "margin-bottom": {"px": 1, "em": 1, "%": 1}, "max-height": {"px": 1, "em": 1, "%": 1}, "max-width": {"px": 1, "em": 1, "%": 1}, "min-height": {"px": 1, "em": 1, "%": 1}, "min-width": {"px": 1, "em": 1, "%": 1}, "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "padding": {"px": 1, "em": 1, "%": 1}, "padding-top": {"px": 1, "em": 1, "%": 1}, "padding-right": {"px": 1, "em": 1, "%": 1}, "padding-bottom": {"px": 1, "em": 1, "%": 1}, "padding-left": {"px": 1, "em": 1, "%": 1}, "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, "right": {"px": 1, "em": 1, "%": 1}, "table-layout": {"fixed": 1, "auto": 1}, "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, "top": {"px": 1, "em": 1, "%": 1}, "vertical-align": {"top": 1, "bottom": 1}, "visibility": {"hidden": 1, "visible": 1}, "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, "width": {"px": 1, "em": 1, "%": 1}, "word-spacing": {"normal": 1}, "filter": {"alpha(opacity=$0100)": 1}, "text-shadow": {"$02px 2px 2px #777": 1}, "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, "-moz-border-radius": 1, "-moz-border-radius-topright": 1, "-moz-border-radius-bottomright": 1, "-moz-border-radius-topleft": 1, "-moz-border-radius-bottomleft": 1, "-webkit-border-radius": 1, "-webkit-border-top-right-radius": 1, "-webkit-border-top-left-radius": 1, "-webkit-border-bottom-right-radius": 1, "-webkit-border-bottom-left-radius": 1, "-moz-box-shadow": 1, "-webkit-box-shadow": 1, "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } }; var CssCompletions = function() { }; (function() { this.completionsDefined = false; this.defineCompletions = function() { if (document) { var style = document.createElement('c').style; for (var i in style) { if (typeof style[i] !== 'string') continue; var name = i.replace(/[A-Z]/g, function(x) { return '-' + x.toLowerCase(); }); if (!propertyMap.hasOwnProperty(name)) propertyMap[name] = 1; } } this.completionsDefined = true; } this.getCompletions = function(state, session, pos, prefix) { if (!this.completionsDefined) { this.defineCompletions(); } var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (state==='ruleset'){ var line = session.getLine(pos.row).substr(0, pos.column); if (/:[^;]+$/.test(line)) { /([\w\-]+):[^:]*$/.test(line); return this.getPropertyValueCompletions(state, session, pos, prefix); } else { return this.getPropertyCompletions(state, session, pos, prefix); } } return []; }; this.getPropertyCompletions = function(state, session, pos, prefix) { var properties = Object.keys(propertyMap); return properties.map(function(property){ return { caption: property, snippet: property + ': $0', meta: "property", score: Number.MAX_VALUE }; }); }; this.getPropertyValueCompletions = function(state, session, pos, prefix) { var line = session.getLine(pos.row).substr(0, pos.column); var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; if (!property) return []; var values = []; if (property in propertyMap && typeof propertyMap[property] === "object") { values = Object.keys(propertyMap[property]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "property value", score: Number.MAX_VALUE }; }); }; }).call(CssCompletions.prototype); exports.CssCompletions = CssCompletions; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssCompletions = require("./css_completions").CssCompletions; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.$completer = new CssCompletions(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": {"manifest": 1}, "head": {}, "title": {}, "base": {"href": 1, "target": 1}, "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, "noscript": {"href": 1}, "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, "section": {}, "nav": {}, "article": {"pubdate": 1}, "aside": {}, "h1": {}, "h2": {}, "h3": {}, "h4": {}, "h5": {}, "h6": {}, "header": {}, "footer": {}, "address": {}, "main": {}, "p": {}, "hr": {}, "pre": {}, "blockquote": {"cite": 1}, "ol": {"start": 1, "reversed": 1}, "ul": {}, "li": {"value": 1}, "dl": {}, "dt": {}, "dd": {}, "figure": {}, "figcaption": {}, "div": {}, "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, "em": {}, "strong": {}, "small": {}, "s": {}, "cite": {}, "q": {"cite": 1}, "dfn": {}, "abbr": {}, "data": {}, "time": {"datetime": 1}, "code": {}, "var": {}, "samp": {}, "kbd": {}, "sub": {}, "sup": {}, "i": {}, "b": {}, "u": {}, "mark": {}, "ruby": {}, "rt": {}, "rp": {}, "bdi": {}, "bdo": {}, "span": {}, "br": {}, "wbr": {}, "ins": {"cite": 1, "datetime": 1}, "del": {"cite": 1, "datetime": 1}, "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, "param": {"name": 1, "value": 1}, "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, "source": {"src": 1, "type": 1, "media": 1}, "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, "canvas": {"width": 1, "height": 1}, "map": {"name": 1}, "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, "svg": {}, "math": {}, "table": {"summary": 1}, "caption": {}, "colgroup": {"span": 1}, "col": {"span": 1}, "tbody": {}, "thead": {}, "tfoot": {}, "tr": {}, "td": {"headers": 1, "rowspan": 1, "colspan": 1}, "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, "fieldset": {"disabled": 1, "form": 1, "name": 1}, "legend": {}, "label": {"form": 1, "for": 1}, "input": { "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, "datalist": {}, "optgroup": {"disabled": 1, "label": 1}, "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, "output": {"for": 1, "form": 1, "name": 1}, "progress": {"value": 1, "max": 1}, "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, "details": {"open": 1}, "summary": {}, "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, "menu": {"type": 1, "label": 1}, "dialog": {"open": 1} }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } function findAttributeName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "attribute-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompletions(state, session, pos, prefix); if (is(token, "attribute-value")) return this.getAttributeValueCompletions(state, session, pos, prefix); var line = session.getLine(pos.row).substr(0, pos.column); if (/&[A-z]*$/i.test(line)) return this.getHTMLEntityCompletions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(Object.keys(attributeMap[tagName])); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; this.getAttributeValueCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); var attributeName = findAttributeName(session, pos); if (!tagName) return []; var values = []; if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { values = Object.keys(attributeMap[tagName][attributeName]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "attribute value", score: Number.MAX_VALUE }; }); }; this.getHTMLEntityCompletions = function(state, session, pos, prefix) { var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; return values.map(function(value){ return { caption: value, snippet: value, meta: "html entity", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/markdown_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules","ace/mode/html_highlight_rules","ace/mode/css_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var escaped = function(ch) { return "(?:[^" + lang.escapeRegExp(ch) + "\\\\]|\\\\.)*"; } function github_embed(tag, prefix) { return { // Github style block token : "support.function", regex : "^\\s*```" + tag + "\\s*$", push : prefix + "start" }; } var MarkdownHighlightRules = function() { HtmlHighlightRules.call(this); this.$rules["start"].unshift({ token : "empty_line", regex : '^$', next: "allowBlock" }, { // h1 token: "markup.heading.1", regex: "^=+(?=\\s*$)" }, { // h2 token: "markup.heading.2", regex: "^\\-+(?=\\s*$)" }, { token : function(value) { return "markup.heading." + value.length; }, regex : /^#{1,6}(?=\s*[^ #]|\s+#.)/, next : "header" }, github_embed("(?:javascript|js)", "jscode-"), github_embed("xml", "xmlcode-"), github_embed("html", "htmlcode-"), github_embed("css", "csscode-"), { // Github style block token : "support.function", regex : "^\\s*```\\s*\\S*(?:{.*?\\})?\\s*$", next : "githubblock" }, { // block quote token : "string.blockquote", regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+", next : "blockquote" }, { // HR * - _ token : "constant", regex : "^ {0,2}(?:(?: ?\\* ?){3,}|(?: ?\\- ?){3,}|(?: ?\\_ ?){3,})\\s*$", next: "allowBlock" }, { // list token : "markup.list", regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+", next : "listblock-start" }, { include : "basic" }); this.addRules({ "basic" : [{ token : "constant.language.escape", regex : /\\[\\`*_{}\[\]()#+\-.!]/ }, { // code span ` token : "support.function", regex : "(`+)(.*?[^`])(\\1)" }, { // reference token : ["text", "constant", "text", "url", "string", "text"], regex : "^([ ]{0,3}\\[)([^\\]]+)(\\]:\\s*)([^ ]+)(\\s*(?:[\"][^\"]+[\"])?(\\s*))$" }, { // link by reference token : ["text", "string", "text", "constant", "text"], regex : "(\\[)(" + escaped("]") + ")(\\]\\s*\\[)("+ escaped("]") + ")(\\])" }, { // link by url token : ["text", "string", "text", "markup.underline", "string", "text"], regex : "(\\[)(" + // [ escaped("]") + // link text ")(\\]\\()"+ // ]( '((?:[^\\)\\s\\\\]|\\\\.|\\s(?=[^"]))*)' + // href '(\\s*"' + escaped('"') + '"\\s*)?' + // "title" "(\\))" // ) }, { // strong ** __ token : "string.strong", regex : "([*]{2}|[_]{2}(?=\\S))(.*?\\S[*_]*)(\\1)" }, { // emphasis * _ token : "string.emphasis", regex : "([*]|[_](?=\\S))(.*?\\S[*_]*)(\\1)" }, { // token : ["text", "url", "text"], regex : "(<)("+ "(?:https?|ftp|dict):[^'\">\\s]+"+ "|"+ "(?:mailto:)?[-.\\w]+\\@[-a-z0-9]+(?:\\.[-a-z0-9]+)*\\.[a-z]+"+ ")(>)" }], "allowBlock": [ {token : "support.function", regex : "^ {4}.+", next : "allowBlock"}, {token : "empty_line", regex : '^$', next: "allowBlock"}, {token : "empty", regex : "", next : "start"} ], "header" : [{ regex: "$", next : "start" }, { include: "basic" }, { defaultToken : "heading" } ], "listblock-start" : [{ token : "support.variable", regex : /(?:\[[ x]\])?/, next : "listblock" }], "listblock" : [ { // Lists only escape on completely blank lines. token : "empty_line", regex : "^$", next : "start" }, { // list token : "markup.list", regex : "^\\s{0,3}(?:[*+-]|\\d+\\.)\\s+", next : "listblock-start" }, { include : "basic", noEscape: true }, { // Github style block token : "support.function", regex : "^\\s*```\\s*[a-zA-Z]*(?:{.*?\\})?\\s*$", next : "githubblock" }, { defaultToken : "list" //do not use markup.list to allow stling leading `*` differntly } ], "blockquote" : [ { // Blockquotes only escape on blank lines. token : "empty_line", regex : "^\\s*$", next : "start" }, { // block quote token : "string.blockquote", regex : "^\\s*>\\s*(?:[*+-]|\\d+\\.)?\\s+", next : "blockquote" }, { include : "basic", noEscape: true }, { defaultToken : "string.blockquote" } ], "githubblock" : [ { token : "support.function", regex : "^\\s*```", next : "start" }, { token : "support.function", regex : ".+" } ] }); this.embedRules(JavaScriptHighlightRules, "jscode-", [{ token : "support.function", regex : "^\\s*```", next : "pop" }]); this.embedRules(HtmlHighlightRules, "htmlcode-", [{ token : "support.function", regex : "^\\s*```", next : "pop" }]); this.embedRules(CssHighlightRules, "csscode-", [{ token : "support.function", regex : "^\\s*```", next : "pop" }]); this.embedRules(XmlHighlightRules, "xmlcode-", [{ token : "support.function", regex : "^\\s*```", next : "pop" }]); this.normalizeRules(); }; oop.inherits(MarkdownHighlightRules, TextHighlightRules); exports.MarkdownHighlightRules = MarkdownHighlightRules; }); ace.define("ace/mode/folding/markdown",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /^(?:[=-]+\s*$|#{1,6} |`{3})/; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (!this.foldingStartMarker.test(line)) return ""; if (line[0] == "`") { if (session.bgTokenizer.getState(row) == "start") return "end"; return "start"; } return "start"; }; this.getFoldWidgetRange = function(session, foldStyle, row) { var line = session.getLine(row); var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; if (!line.match(this.foldingStartMarker)) return; if (line[0] == "`") { if (session.bgTokenizer.getState(row) !== "start") { while (++row < maxRow) { line = session.getLine(row); if (line[0] == "`" & line.substring(0, 3) == "```") break; } return new Range(startRow, startColumn, row, 0); } else { while (row -- > 0) { line = session.getLine(row); if (line[0] == "`" & line.substring(0, 3) == "```") break; } return new Range(row, line.length, startRow, 0); } } var token; function isHeading(row) { token = session.getTokens(row)[0]; return token && token.type.lastIndexOf(heading, 0) === 0; } var heading = "markup.heading"; function getLevel() { var ch = token.value[0]; if (ch == "=") return 6; if (ch == "-") return 5; return 7 - token.value.search(/[^#]/); } if (isHeading(row)) { var startHeadingLevel = getLevel(); while (++row < maxRow) { if (!isHeading(row)) continue; var level = getLevel(); if (level >= startHeadingLevel) break; } endRow = row - (!token || ["=", "-"].indexOf(token.value[0]) == -1 ? 1 : 2); if (endRow > startRow) { while (endRow > startRow && /^\s*$/.test(session.getLine(endRow))) endRow--; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/markdown",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript","ace/mode/xml","ace/mode/html","ace/mode/markdown_highlight_rules","ace/mode/folding/markdown"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var XmlMode = require("./xml").Mode; var HtmlMode = require("./html").Mode; var MarkdownHighlightRules = require("./markdown_highlight_rules").MarkdownHighlightRules; var MarkdownFoldMode = require("./folding/markdown").FoldMode; var Mode = function() { this.HighlightRules = MarkdownHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode, "xml-": XmlMode, "html-": HtmlMode }); this.foldingRules = new MarkdownFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.type = "text"; this.blockComment = {start: "<!--", end: "-->"}; this.getNextLineIndent = function(state, line, tab) { if (state == "listblock") { var match = /^(\s*)(?:([-+*])|(\d+)\.)(\s+)/.exec(line); if (!match) return ""; var marker = match[2]; if (!marker) marker = parseInt(match[3], 10) + 1 + "."; return match[1] + marker + match[4]; } else { return this.$getIndent(line); } }; this.$id = "ace/mode/markdown"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/mode-php.js
12,803
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|async|await|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode "[0-2][0-7]{0,2}|" + // oct "3[0-7][0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ DocCommentHighlightRules.getStartRule("doc-start"), comments("no_regex"), { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "punctuation.operator", regex : /[.](?![.])/, next : "property" }, { token : "keyword.operator", regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], property: [{ token : "text", regex : "\\s+" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", next: "function_arguments" }, { token : "punctuation.operator", regex : /[.](?![.])/ }, { token : "support.function", regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : "support.function.dom", regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : "support.constant", regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : "identifier", regex : identifierRe }, { regex: "", token: "empty", next: "no_regex" } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("start"), { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); } else if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); if (!options || options.jsx != false) JSX.call(this); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); function JSX() { var tagRegex = identifierRe.replace("\\d", "\\d\\-"); var jsxTag = { onMatch : function(val, state, stack) { var offset = val.charAt(1) == "/" ? 2 : 1; if (offset == 1) { if (state != this.nextState) stack.unshift(this.next, this.nextState, 0); else stack.unshift(this.next); stack[2]++; } else if (offset == 2) { if (state == this.nextState) { stack[1]--; if (!stack[1] || stack[1] < 0) { stack.shift(); stack.shift(); } } } return [{ type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", value: val.slice(0, offset) }, { type: "meta.tag.tag-name.xml", value: val.substr(offset) }]; }, regex : "</?" + tagRegex + "", next: "jsxAttributes", nextState: "jsx" }; this.$rules.start.unshift(jsxTag); var jsxJsRule = { regex: "{", token: "paren.quasi.start", push: "start" }; this.$rules.jsx = [ jsxJsRule, jsxTag, {include : "reference"}, {defaultToken: "string"} ]; this.$rules.jsxAttributes = [{ token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", onMatch : function(value, currentState, stack) { if (currentState == stack[0]) stack.shift(); if (value.length == 2) { if (stack[0] == this.nextState) stack[1]--; if (!stack[1] || stack[1] < 0) { stack.splice(0, 2); } } this.next = stack[0] || "start"; return [{type: this.token, value: value}]; }, nextState: "jsx" }, jsxJsRule, comments("jsxAttributes"), { token : "entity.other.attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { token : "text.tag-whitespace.xml", regex : "\\s+" }, { token : "string.attribute-value.xml", regex : "'", stateName : "jsx_attr_q", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', stateName : "jsx_attr_qq", push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, jsxTag ]; this.$rules.reference = [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }]; } function comments(next) { return [ { token : "comment", // multi line comment regex : /\/\*/, next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] }, { token : "comment", regex : "\\/\\/", next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] } ]; } exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/php_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules","ace/mode/html_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var PhpLangHighlightRules = function() { var docComment = DocCommentHighlightRules; var builtinFunctions = lang.arrayToMap( ('abs|acos|acosh|addcslashes|addslashes|aggregate|aggregate_info|aggregate_methods|aggregate_methods_by_list|aggregate_methods_by_regexp|' + 'aggregate_properties|aggregate_properties_by_list|aggregate_properties_by_regexp|aggregation_info|amqpconnection|amqpexchange|amqpqueue|' + 'apache_child_terminate|apache_get_modules|apache_get_version|apache_getenv|apache_lookup_uri|apache_note|apache_request_headers|' + 'apache_reset_timeout|apache_response_headers|apache_setenv|apc_add|apc_bin_dump|apc_bin_dumpfile|apc_bin_load|apc_bin_loadfile|' + 'apc_cache_info|apc_cas|apc_clear_cache|apc_compile_file|apc_dec|apc_define_constants|apc_delete|apc_delete_file|apc_exists|apc_fetch|' + 'apc_inc|apc_load_constants|apc_sma_info|apc_store|apciterator|apd_breakpoint|apd_callstack|apd_clunk|apd_continue|apd_croak|' + 'apd_dump_function_table|apd_dump_persistent_resources|apd_dump_regular_resources|apd_echo|apd_get_active_symbols|apd_set_pprof_trace|' + 'apd_set_session|apd_set_session_trace|apd_set_session_trace_socket|appenditerator|array|array_change_key_case|array_chunk|array_combine|' + 'array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_fill_keys|array_filter|' + 'array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|' + 'array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|' + 'array_reduce|array_replace|array_replace_recursive|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|' + 'array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|' + 'array_values|array_walk|array_walk_recursive|arrayaccess|arrayiterator|arrayobject|arsort|asin|asinh|asort|assert|assert_options|atan|' + 'atan2|atanh|audioproperties|badfunctioncallexception|badmethodcallexception|base64_decode|base64_encode|base_convert|basename|' + 'bbcode_add_element|bbcode_add_smiley|bbcode_create|bbcode_destroy|bbcode_parse|bbcode_set_arg_parser|bbcode_set_flags|bcadd|bccomp|bcdiv|' + 'bcmod|bcmul|bcompiler_load|bcompiler_load_exe|bcompiler_parse_class|bcompiler_read|bcompiler_write_class|bcompiler_write_constant|' + 'bcompiler_write_exe_footer|bcompiler_write_file|bcompiler_write_footer|bcompiler_write_function|bcompiler_write_functions_from_file|' + 'bcompiler_write_header|bcompiler_write_included_filename|bcpow|bcpowmod|bcscale|bcsqrt|bcsub|bin2hex|bind_textdomain_codeset|bindec|' + 'bindtextdomain|bson_decode|bson_encode|bumpValue|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|' + 'cachingiterator|cairo|cairo_create|cairo_font_face_get_type|cairo_font_face_status|cairo_font_options_create|cairo_font_options_equal|' + 'cairo_font_options_get_antialias|cairo_font_options_get_hint_metrics|cairo_font_options_get_hint_style|' + 'cairo_font_options_get_subpixel_order|cairo_font_options_hash|cairo_font_options_merge|cairo_font_options_set_antialias|' + 'cairo_font_options_set_hint_metrics|cairo_font_options_set_hint_style|cairo_font_options_set_subpixel_order|cairo_font_options_status|' + 'cairo_format_stride_for_width|cairo_image_surface_create|cairo_image_surface_create_for_data|cairo_image_surface_create_from_png|' + 'cairo_image_surface_get_data|cairo_image_surface_get_format|cairo_image_surface_get_height|cairo_image_surface_get_stride|' + 'cairo_image_surface_get_width|cairo_matrix_create_scale|cairo_matrix_create_translate|cairo_matrix_invert|cairo_matrix_multiply|' + 'cairo_matrix_rotate|cairo_matrix_transform_distance|cairo_matrix_transform_point|cairo_matrix_translate|cairo_pattern_add_color_stop_rgb|' + 'cairo_pattern_add_color_stop_rgba|cairo_pattern_create_for_surface|cairo_pattern_create_linear|cairo_pattern_create_radial|' + 'cairo_pattern_create_rgb|cairo_pattern_create_rgba|cairo_pattern_get_color_stop_count|cairo_pattern_get_color_stop_rgba|' + 'cairo_pattern_get_extend|cairo_pattern_get_filter|cairo_pattern_get_linear_points|cairo_pattern_get_matrix|' + 'cairo_pattern_get_radial_circles|cairo_pattern_get_rgba|cairo_pattern_get_surface|cairo_pattern_get_type|cairo_pattern_set_extend|' + 'cairo_pattern_set_filter|cairo_pattern_set_matrix|cairo_pattern_status|cairo_pdf_surface_create|cairo_pdf_surface_set_size|' + 'cairo_ps_get_levels|cairo_ps_level_to_string|cairo_ps_surface_create|cairo_ps_surface_dsc_begin_page_setup|' + 'cairo_ps_surface_dsc_begin_setup|cairo_ps_surface_dsc_comment|cairo_ps_surface_get_eps|cairo_ps_surface_restrict_to_level|' + 'cairo_ps_surface_set_eps|cairo_ps_surface_set_size|cairo_scaled_font_create|cairo_scaled_font_extents|cairo_scaled_font_get_ctm|' + 'cairo_scaled_font_get_font_face|cairo_scaled_font_get_font_matrix|cairo_scaled_font_get_font_options|cairo_scaled_font_get_scale_matrix|' + 'cairo_scaled_font_get_type|cairo_scaled_font_glyph_extents|cairo_scaled_font_status|cairo_scaled_font_text_extents|' + 'cairo_surface_copy_page|cairo_surface_create_similar|cairo_surface_finish|cairo_surface_flush|cairo_surface_get_content|' + 'cairo_surface_get_device_offset|cairo_surface_get_font_options|cairo_surface_get_type|cairo_surface_mark_dirty|' + 'cairo_surface_mark_dirty_rectangle|cairo_surface_set_device_offset|cairo_surface_set_fallback_resolution|cairo_surface_show_page|' + 'cairo_surface_status|cairo_surface_write_to_png|cairo_svg_surface_create|cairo_svg_surface_restrict_to_version|' + 'cairo_svg_version_to_string|cairoantialias|cairocontent|cairocontext|cairoexception|cairoextend|cairofillrule|cairofilter|cairofontface|' + 'cairofontoptions|cairofontslant|cairofonttype|cairofontweight|cairoformat|cairogradientpattern|cairohintmetrics|cairohintstyle|' + 'cairoimagesurface|cairolineargradient|cairolinecap|cairolinejoin|cairomatrix|cairooperator|cairopath|cairopattern|cairopatterntype|' + 'cairopdfsurface|cairopslevel|cairopssurface|cairoradialgradient|cairoscaledfont|cairosolidpattern|cairostatus|cairosubpixelorder|' + 'cairosurface|cairosurfacepattern|cairosurfacetype|cairosvgsurface|cairosvgversion|cairotoyfontface|cal_days_in_month|cal_from_jd|cal_info|' + 'cal_to_jd|calcul_hmac|calculhmac|call_user_func|call_user_func_array|call_user_method|call_user_method_array|callbackfilteriterator|ceil|' + 'chdb|chdb_create|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_alias|class_exists|class_implements|' + 'class_parents|class_uses|classkit_import|classkit_method_add|classkit_method_copy|classkit_method_redefine|classkit_method_remove|' + 'classkit_method_rename|clearstatcache|clone|closedir|closelog|collator|com|com_addref|com_create_guid|com_event_sink|com_get|' + 'com_get_active_object|com_invoke|com_isenum|com_load|com_load_typelib|com_message_pump|com_print_typeinfo|com_propget|com_propput|' + 'com_propset|com_release|com_set|compact|connection_aborted|connection_status|connection_timeout|constant|construct|construct|construct|' + 'convert_cyr_string|convert_uudecode|convert_uuencode|copy|cos|cosh|count|count_chars|countable|counter_bump|counter_bump_value|' + 'counter_create|counter_get|counter_get_meta|counter_get_named|counter_get_value|counter_reset|counter_reset_value|crack_check|' + 'crack_closedict|crack_getlastmessage|crack_opendict|crc32|create_function|crypt|ctype_alnum|ctype_alpha|ctype_cntrl|ctype_digit|' + 'ctype_graph|ctype_lower|ctype_print|ctype_punct|ctype_space|ctype_upper|ctype_xdigit|cubrid_affected_rows|cubrid_bind|' + 'cubrid_client_encoding|cubrid_close|cubrid_close_prepare|cubrid_close_request|cubrid_col_get|cubrid_col_size|cubrid_column_names|' + 'cubrid_column_types|cubrid_commit|cubrid_connect|cubrid_connect_with_url|cubrid_current_oid|cubrid_data_seek|cubrid_db_name|' + 'cubrid_disconnect|cubrid_drop|cubrid_errno|cubrid_error|cubrid_error_code|cubrid_error_code_facility|cubrid_error_msg|cubrid_execute|' + 'cubrid_fetch|cubrid_fetch_array|cubrid_fetch_assoc|cubrid_fetch_field|cubrid_fetch_lengths|cubrid_fetch_object|cubrid_fetch_row|' + 'cubrid_field_flags|cubrid_field_len|cubrid_field_name|cubrid_field_seek|cubrid_field_table|cubrid_field_type|cubrid_free_result|' + 'cubrid_get|cubrid_get_autocommit|cubrid_get_charset|cubrid_get_class_name|cubrid_get_client_info|cubrid_get_db_parameter|' + 'cubrid_get_server_info|cubrid_insert_id|cubrid_is_instance|cubrid_list_dbs|cubrid_load_from_glo|cubrid_lob_close|cubrid_lob_export|' + 'cubrid_lob_get|cubrid_lob_send|cubrid_lob_size|cubrid_lock_read|cubrid_lock_write|cubrid_move_cursor|cubrid_new_glo|cubrid_next_result|' + 'cubrid_num_cols|cubrid_num_fields|cubrid_num_rows|cubrid_ping|cubrid_prepare|cubrid_put|cubrid_query|cubrid_real_escape_string|' + 'cubrid_result|cubrid_rollback|cubrid_save_to_glo|cubrid_schema|cubrid_send_glo|cubrid_seq_drop|cubrid_seq_insert|cubrid_seq_put|' + 'cubrid_set_add|cubrid_set_autocommit|cubrid_set_db_parameter|cubrid_set_drop|cubrid_unbuffered_query|cubrid_version|curl_close|' + 'curl_copy_handle|curl_errno|curl_error|curl_exec|curl_getinfo|curl_init|curl_multi_add_handle|curl_multi_close|curl_multi_exec|' + 'curl_multi_getcontent|curl_multi_info_read|curl_multi_init|curl_multi_remove_handle|curl_multi_select|curl_setopt|curl_setopt_array|' + 'curl_version|current|cyrus_authenticate|cyrus_bind|cyrus_close|cyrus_connect|cyrus_query|cyrus_unbind|date|date_add|date_create|' + 'date_create_from_format|date_date_set|date_default_timezone_get|date_default_timezone_set|date_diff|date_format|date_get_last_errors|' + 'date_interval_create_from_date_string|date_interval_format|date_isodate_set|date_modify|date_offset_get|date_parse|date_parse_from_format|' + 'date_sub|date_sun_info|date_sunrise|date_sunset|date_time_set|date_timestamp_get|date_timestamp_set|date_timezone_get|date_timezone_set|' + 'dateinterval|dateperiod|datetime|datetimezone|db2_autocommit|db2_bind_param|db2_client_info|db2_close|db2_column_privileges|db2_columns|' + 'db2_commit|db2_conn_error|db2_conn_errormsg|db2_connect|db2_cursor_type|db2_escape_string|db2_exec|db2_execute|db2_fetch_array|' + 'db2_fetch_assoc|db2_fetch_both|db2_fetch_object|db2_fetch_row|db2_field_display_size|db2_field_name|db2_field_num|db2_field_precision|' + 'db2_field_scale|db2_field_type|db2_field_width|db2_foreign_keys|db2_free_result|db2_free_stmt|db2_get_option|db2_last_insert_id|' + 'db2_lob_read|db2_next_result|db2_num_fields|db2_num_rows|db2_pclose|db2_pconnect|db2_prepare|db2_primary_keys|db2_procedure_columns|' + 'db2_procedures|db2_result|db2_rollback|db2_server_info|db2_set_option|db2_special_columns|db2_statistics|db2_stmt_error|db2_stmt_errormsg|' + 'db2_table_privileges|db2_tables|dba_close|dba_delete|dba_exists|dba_fetch|dba_firstkey|dba_handlers|dba_insert|dba_key_split|dba_list|' + 'dba_nextkey|dba_open|dba_optimize|dba_popen|dba_replace|dba_sync|dbase_add_record|dbase_close|dbase_create|dbase_delete_record|' + 'dbase_get_header_info|dbase_get_record|dbase_get_record_with_names|dbase_numfields|dbase_numrecords|dbase_open|dbase_pack|' + 'dbase_replace_record|dbplus_add|dbplus_aql|dbplus_chdir|dbplus_close|dbplus_curr|dbplus_errcode|dbplus_errno|dbplus_find|dbplus_first|' + 'dbplus_flush|dbplus_freealllocks|dbplus_freelock|dbplus_freerlocks|dbplus_getlock|dbplus_getunique|dbplus_info|dbplus_last|dbplus_lockrel|' + 'dbplus_next|dbplus_open|dbplus_prev|dbplus_rchperm|dbplus_rcreate|dbplus_rcrtexact|dbplus_rcrtlike|dbplus_resolve|dbplus_restorepos|' + 'dbplus_rkeys|dbplus_ropen|dbplus_rquery|dbplus_rrename|dbplus_rsecindex|dbplus_runlink|dbplus_rzap|dbplus_savepos|dbplus_setindex|' + 'dbplus_setindexbynumber|dbplus_sql|dbplus_tcl|dbplus_tremove|dbplus_undo|dbplus_undoprepare|dbplus_unlockrel|dbplus_unselect|' + 'dbplus_update|dbplus_xlockrel|dbplus_xunlockrel|dbx_close|dbx_compare|dbx_connect|dbx_error|dbx_escape_string|dbx_fetch_row|dbx_query|' + 'dbx_sort|dcgettext|dcngettext|deaggregate|debug_backtrace|debug_print_backtrace|debug_zval_dump|decbin|dechex|decoct|define|' + 'define_syslog_variables|defined|deg2rad|delete|dgettext|die|dio_close|dio_fcntl|dio_open|dio_read|dio_seek|dio_stat|dio_tcsetattr|' + 'dio_truncate|dio_write|dir|directoryiterator|dirname|disk_free_space|disk_total_space|diskfreespace|dl|dngettext|dns_check_record|' + 'dns_get_mx|dns_get_record|dom_import_simplexml|domainexception|domattr|domattribute_name|domattribute_set_value|domattribute_specified|' + 'domattribute_value|domcharacterdata|domcomment|domdocument|domdocument_add_root|domdocument_create_attribute|' + 'domdocument_create_cdata_section|domdocument_create_comment|domdocument_create_element|domdocument_create_element_ns|' + 'domdocument_create_entity_reference|domdocument_create_processing_instruction|domdocument_create_text_node|domdocument_doctype|' + 'domdocument_document_element|domdocument_dump_file|domdocument_dump_mem|domdocument_get_element_by_id|domdocument_get_elements_by_tagname|' + 'domdocument_html_dump_mem|domdocument_xinclude|domdocumentfragment|domdocumenttype|domdocumenttype_entities|' + 'domdocumenttype_internal_subset|domdocumenttype_name|domdocumenttype_notations|domdocumenttype_public_id|domdocumenttype_system_id|' + 'domelement|domelement_get_attribute|domelement_get_attribute_node|domelement_get_elements_by_tagname|domelement_has_attribute|' + 'domelement_remove_attribute|domelement_set_attribute|domelement_set_attribute_node|domelement_tagname|domentity|domentityreference|' + 'domexception|domimplementation|domnamednodemap|domnode|domnode_add_namespace|domnode_append_child|domnode_append_sibling|' + 'domnode_attributes|domnode_child_nodes|domnode_clone_node|domnode_dump_node|domnode_first_child|domnode_get_content|' + 'domnode_has_attributes|domnode_has_child_nodes|domnode_insert_before|domnode_is_blank_node|domnode_last_child|domnode_next_sibling|' + 'domnode_node_name|domnode_node_type|domnode_node_value|domnode_owner_document|domnode_parent_node|domnode_prefix|domnode_previous_sibling|' + 'domnode_remove_child|domnode_replace_child|domnode_replace_node|domnode_set_content|domnode_set_name|domnode_set_namespace|' + 'domnode_unlink_node|domnodelist|domnotation|domprocessinginstruction|domprocessinginstruction_data|domprocessinginstruction_target|' + 'domtext|domxml_new_doc|domxml_open_file|domxml_open_mem|domxml_version|domxml_xmltree|domxml_xslt_stylesheet|domxml_xslt_stylesheet_doc|' + 'domxml_xslt_stylesheet_file|domxml_xslt_version|domxpath|domxsltstylesheet_process|domxsltstylesheet_result_dump_file|' + 'domxsltstylesheet_result_dump_mem|dotnet|dotnet_load|doubleval|each|easter_date|easter_days|echo|empty|emptyiterator|' + 'enchant_broker_describe|enchant_broker_dict_exists|enchant_broker_free|enchant_broker_free_dict|enchant_broker_get_error|' + 'enchant_broker_init|enchant_broker_list_dicts|enchant_broker_request_dict|enchant_broker_request_pwl_dict|enchant_broker_set_ordering|' + 'enchant_dict_add_to_personal|enchant_dict_add_to_session|enchant_dict_check|enchant_dict_describe|enchant_dict_get_error|' + 'enchant_dict_is_in_session|enchant_dict_quick_check|enchant_dict_store_replacement|enchant_dict_suggest|end|ereg|ereg_replace|eregi|' + 'eregi_replace|error_get_last|error_log|error_reporting|errorexception|escapeshellarg|escapeshellcmd|eval|event_add|event_base_free|' + 'event_base_loop|event_base_loopbreak|event_base_loopexit|event_base_new|event_base_priority_init|event_base_set|event_buffer_base_set|' + 'event_buffer_disable|event_buffer_enable|event_buffer_fd_set|event_buffer_free|event_buffer_new|event_buffer_priority_set|' + 'event_buffer_read|event_buffer_set_callback|event_buffer_timeout_set|event_buffer_watermark_set|event_buffer_write|event_del|event_free|' + 'event_new|event_set|exception|exec|exif_imagetype|exif_read_data|exif_tagname|exif_thumbnail|exit|exp|expect_expectl|expect_popen|explode|' + 'expm1|export|export|extension_loaded|extract|ezmlm_hash|fam_cancel_monitor|fam_close|fam_monitor_collection|fam_monitor_directory|' + 'fam_monitor_file|fam_next_event|fam_open|fam_pending|fam_resume_monitor|fam_suspend_monitor|fbsql_affected_rows|fbsql_autocommit|' + 'fbsql_blob_size|fbsql_change_user|fbsql_clob_size|fbsql_close|fbsql_commit|fbsql_connect|fbsql_create_blob|fbsql_create_clob|' + 'fbsql_create_db|fbsql_data_seek|fbsql_database|fbsql_database_password|fbsql_db_query|fbsql_db_status|fbsql_drop_db|fbsql_errno|' + 'fbsql_error|fbsql_fetch_array|fbsql_fetch_assoc|fbsql_fetch_field|fbsql_fetch_lengths|fbsql_fetch_object|fbsql_fetch_row|' + 'fbsql_field_flags|fbsql_field_len|fbsql_field_name|fbsql_field_seek|fbsql_field_table|fbsql_field_type|fbsql_free_result|' + 'fbsql_get_autostart_info|fbsql_hostname|fbsql_insert_id|fbsql_list_dbs|fbsql_list_fields|fbsql_list_tables|fbsql_next_result|' + 'fbsql_num_fields|fbsql_num_rows|fbsql_password|fbsql_pconnect|fbsql_query|fbsql_read_blob|fbsql_read_clob|fbsql_result|fbsql_rollback|' + 'fbsql_rows_fetched|fbsql_select_db|fbsql_set_characterset|fbsql_set_lob_mode|fbsql_set_password|fbsql_set_transaction|fbsql_start_db|' + 'fbsql_stop_db|fbsql_table_name|fbsql_tablename|fbsql_username|fbsql_warnings|fclose|fdf_add_doc_javascript|fdf_add_template|fdf_close|' + 'fdf_create|fdf_enum_values|fdf_errno|fdf_error|fdf_get_ap|fdf_get_attachment|fdf_get_encoding|fdf_get_file|fdf_get_flags|fdf_get_opt|' + 'fdf_get_status|fdf_get_value|fdf_get_version|fdf_header|fdf_next_field_name|fdf_open|fdf_open_string|fdf_remove_item|fdf_save|' + 'fdf_save_string|fdf_set_ap|fdf_set_encoding|fdf_set_file|fdf_set_flags|fdf_set_javascript_action|fdf_set_on_import_javascript|fdf_set_opt|' + 'fdf_set_status|fdf_set_submit_form_action|fdf_set_target_frame|fdf_set_value|fdf_set_version|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file|' + 'file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filepro|' + 'filepro_fieldcount|filepro_fieldname|filepro_fieldtype|filepro_fieldwidth|filepro_retrieve|filepro_rowcount|filesize|filesystemiterator|' + 'filetype|filter_has_var|filter_id|filter_input|filter_input_array|filter_list|filter_var|filter_var_array|filteriterator|finfo_buffer|' + 'finfo_close|finfo_file|finfo_open|finfo_set_flags|floatval|flock|floor|flush|fmod|fnmatch|fopen|forward_static_call|' + 'forward_static_call_array|fpassthru|fprintf|fputcsv|fputs|fread|frenchtojd|fribidi_log2vis|fscanf|fseek|fsockopen|fstat|ftell|ftok|' + 'ftp_alloc|ftp_cdup|ftp_chdir|ftp_chmod|ftp_close|ftp_connect|ftp_delete|ftp_exec|ftp_fget|ftp_fput|ftp_get|ftp_get_option|ftp_login|' + 'ftp_mdtm|ftp_mkdir|ftp_nb_continue|ftp_nb_fget|ftp_nb_fput|ftp_nb_get|ftp_nb_put|ftp_nlist|ftp_pasv|ftp_put|ftp_pwd|ftp_quit|ftp_raw|' + 'ftp_rawlist|ftp_rename|ftp_rmdir|ftp_set_option|ftp_site|ftp_size|ftp_ssl_connect|ftp_systype|ftruncate|func_get_arg|func_get_args|' + 'func_num_args|function_exists|fwrite|gc_collect_cycles|gc_disable|gc_enable|gc_enabled|gd_info|gearmanclient|gearmanjob|gearmantask|' + 'gearmanworker|geoip_continent_code_by_name|geoip_country_code3_by_name|geoip_country_code_by_name|geoip_country_name_by_name|' + 'geoip_database_info|geoip_db_avail|geoip_db_filename|geoip_db_get_all_info|geoip_id_by_name|geoip_isp_by_name|geoip_org_by_name|' + 'geoip_record_by_name|geoip_region_by_name|geoip_region_name_by_code|geoip_time_zone_by_country_and_region|getMeta|getNamed|getValue|' + 'get_browser|get_called_class|get_cfg_var|get_class|get_class_methods|get_class_vars|get_current_user|get_declared_classes|' + 'get_declared_interfaces|get_declared_traits|get_defined_constants|get_defined_functions|get_defined_vars|get_extension_funcs|get_headers|' + 'get_html_translation_table|get_include_path|get_included_files|get_loaded_extensions|get_magic_quotes_gpc|get_magic_quotes_runtime|' + 'get_meta_tags|get_object_vars|get_parent_class|get_required_files|get_resource_type|getallheaders|getconstant|getconstants|getconstructor|' + 'getcwd|getdate|getdefaultproperties|getdoccomment|getendline|getenv|getextension|getextensionname|getfilename|gethostbyaddr|gethostbyname|' + 'gethostbynamel|gethostname|getimagesize|getinterfacenames|getinterfaces|getlastmod|getmethod|getmethods|getmodifiers|getmxrr|getmygid|' + 'getmyinode|getmypid|getmyuid|getname|getnamespacename|getopt|getparentclass|getproperties|getproperty|getprotobyname|getprotobynumber|' + 'getrandmax|getrusage|getservbyname|getservbyport|getshortname|getstartline|getstaticproperties|getstaticpropertyvalue|gettext|' + 'gettimeofday|gettype|glob|globiterator|gmagick|gmagickdraw|gmagickpixel|gmdate|gmmktime|gmp_abs|gmp_add|gmp_and|gmp_clrbit|gmp_cmp|' + 'gmp_com|gmp_div|gmp_div_q|gmp_div_qr|gmp_div_r|gmp_divexact|gmp_fact|gmp_gcd|gmp_gcdext|gmp_hamdist|gmp_init|gmp_intval|gmp_invert|' + 'gmp_jacobi|gmp_legendre|gmp_mod|gmp_mul|gmp_neg|gmp_nextprime|gmp_or|gmp_perfect_square|gmp_popcount|gmp_pow|gmp_powm|gmp_prob_prime|' + 'gmp_random|gmp_scan0|gmp_scan1|gmp_setbit|gmp_sign|gmp_sqrt|gmp_sqrtrem|gmp_strval|gmp_sub|gmp_testbit|gmp_xor|gmstrftime|' + 'gnupg_adddecryptkey|gnupg_addencryptkey|gnupg_addsignkey|gnupg_cleardecryptkeys|gnupg_clearencryptkeys|gnupg_clearsignkeys|gnupg_decrypt|' + 'gnupg_decryptverify|gnupg_encrypt|gnupg_encryptsign|gnupg_export|gnupg_geterror|gnupg_getprotocol|gnupg_import|gnupg_init|gnupg_keyinfo|' + 'gnupg_setarmor|gnupg_seterrormode|gnupg_setsignmode|gnupg_sign|gnupg_verify|gopher_parsedir|grapheme_extract|grapheme_stripos|' + 'grapheme_stristr|grapheme_strlen|grapheme_strpos|grapheme_strripos|grapheme_strrpos|grapheme_strstr|grapheme_substr|gregoriantojd|' + 'gupnp_context_get_host_ip|gupnp_context_get_port|gupnp_context_get_subscription_timeout|gupnp_context_host_path|gupnp_context_new|' + 'gupnp_context_set_subscription_timeout|gupnp_context_timeout_add|gupnp_context_unhost_path|gupnp_control_point_browse_start|' + 'gupnp_control_point_browse_stop|gupnp_control_point_callback_set|gupnp_control_point_new|gupnp_device_action_callback_set|' + 'gupnp_device_info_get|gupnp_device_info_get_service|gupnp_root_device_get_available|gupnp_root_device_get_relative_location|' + 'gupnp_root_device_new|gupnp_root_device_set_available|gupnp_root_device_start|gupnp_root_device_stop|gupnp_service_action_get|' + 'gupnp_service_action_return|gupnp_service_action_return_error|gupnp_service_action_set|gupnp_service_freeze_notify|gupnp_service_info_get|' + 'gupnp_service_info_get_introspection|gupnp_service_introspection_get_state_variable|gupnp_service_notify|gupnp_service_proxy_action_get|' + 'gupnp_service_proxy_action_set|gupnp_service_proxy_add_notify|gupnp_service_proxy_callback_set|gupnp_service_proxy_get_subscribed|' + 'gupnp_service_proxy_remove_notify|gupnp_service_proxy_set_subscribed|gupnp_service_thaw_notify|gzclose|gzcompress|gzdecode|gzdeflate|' + 'gzencode|gzeof|gzfile|gzgetc|gzgets|gzgetss|gzinflate|gzopen|gzpassthru|gzputs|gzread|gzrewind|gzseek|gztell|gzuncompress|gzwrite|' + 'halt_compiler|haruannotation|haruannotation_setborderstyle|haruannotation_sethighlightmode|haruannotation_seticon|' + 'haruannotation_setopened|harudestination|harudestination_setfit|harudestination_setfitb|harudestination_setfitbh|harudestination_setfitbv|' + 'harudestination_setfith|harudestination_setfitr|harudestination_setfitv|harudestination_setxyz|harudoc|harudoc_addpage|' + 'harudoc_addpagelabel|harudoc_construct|harudoc_createoutline|harudoc_getcurrentencoder|harudoc_getcurrentpage|harudoc_getencoder|' + 'harudoc_getfont|harudoc_getinfoattr|harudoc_getpagelayout|harudoc_getpagemode|harudoc_getstreamsize|harudoc_insertpage|harudoc_loadjpeg|' + 'harudoc_loadpng|harudoc_loadraw|harudoc_loadttc|harudoc_loadttf|harudoc_loadtype1|harudoc_output|harudoc_readfromstream|' + 'harudoc_reseterror|harudoc_resetstream|harudoc_save|harudoc_savetostream|harudoc_setcompressionmode|harudoc_setcurrentencoder|' + 'harudoc_setencryptionmode|harudoc_setinfoattr|harudoc_setinfodateattr|harudoc_setopenaction|harudoc_setpagelayout|harudoc_setpagemode|' + 'harudoc_setpagesconfiguration|harudoc_setpassword|harudoc_setpermission|harudoc_usecnsencodings|harudoc_usecnsfonts|' + 'harudoc_usecntencodings|harudoc_usecntfonts|harudoc_usejpencodings|harudoc_usejpfonts|harudoc_usekrencodings|harudoc_usekrfonts|' + 'haruencoder|haruencoder_getbytetype|haruencoder_gettype|haruencoder_getunicode|haruencoder_getwritingmode|haruexception|harufont|' + 'harufont_getascent|harufont_getcapheight|harufont_getdescent|harufont_getencodingname|harufont_getfontname|harufont_gettextwidth|' + 'harufont_getunicodewidth|harufont_getxheight|harufont_measuretext|haruimage|haruimage_getbitspercomponent|haruimage_getcolorspace|' + 'haruimage_getheight|haruimage_getsize|haruimage_getwidth|haruimage_setcolormask|haruimage_setmaskimage|haruoutline|' + 'haruoutline_setdestination|haruoutline_setopened|harupage|harupage_arc|harupage_begintext|harupage_circle|harupage_closepath|' + 'harupage_concat|harupage_createdestination|harupage_createlinkannotation|harupage_createtextannotation|harupage_createurlannotation|' + 'harupage_curveto|harupage_curveto2|harupage_curveto3|harupage_drawimage|harupage_ellipse|harupage_endpath|harupage_endtext|' + 'harupage_eofill|harupage_eofillstroke|harupage_fill|harupage_fillstroke|harupage_getcharspace|harupage_getcmykfill|harupage_getcmykstroke|' + 'harupage_getcurrentfont|harupage_getcurrentfontsize|harupage_getcurrentpos|harupage_getcurrenttextpos|harupage_getdash|' + 'harupage_getfillingcolorspace|harupage_getflatness|harupage_getgmode|harupage_getgrayfill|harupage_getgraystroke|harupage_getheight|' + 'harupage_gethorizontalscaling|harupage_getlinecap|harupage_getlinejoin|harupage_getlinewidth|harupage_getmiterlimit|harupage_getrgbfill|' + 'harupage_getrgbstroke|harupage_getstrokingcolorspace|harupage_gettextleading|harupage_gettextmatrix|harupage_gettextrenderingmode|' + 'harupage_gettextrise|harupage_gettextwidth|harupage_gettransmatrix|harupage_getwidth|harupage_getwordspace|harupage_lineto|' + 'harupage_measuretext|harupage_movetextpos|harupage_moveto|harupage_movetonextline|harupage_rectangle|harupage_setcharspace|' + 'harupage_setcmykfill|harupage_setcmykstroke|harupage_setdash|harupage_setflatness|harupage_setfontandsize|harupage_setgrayfill|' + 'harupage_setgraystroke|harupage_setheight|harupage_sethorizontalscaling|harupage_setlinecap|harupage_setlinejoin|harupage_setlinewidth|' + 'harupage_setmiterlimit|harupage_setrgbfill|harupage_setrgbstroke|harupage_setrotate|harupage_setsize|harupage_setslideshow|' + 'harupage_settextleading|harupage_settextmatrix|harupage_settextrenderingmode|harupage_settextrise|harupage_setwidth|harupage_setwordspace|' + 'harupage_showtext|harupage_showtextnextline|harupage_stroke|harupage_textout|harupage_textrect|hasconstant|hash|hash_algos|hash_copy|' + 'hash_file|hash_final|hash_hmac|hash_hmac_file|hash_init|hash_update|hash_update_file|hash_update_stream|hasmethod|hasproperty|header|' + 'header_register_callback|header_remove|headers_list|headers_sent|hebrev|hebrevc|hex2bin|hexdec|highlight_file|highlight_string|' + 'html_entity_decode|htmlentities|htmlspecialchars|htmlspecialchars_decode|http_build_cookie|http_build_query|http_build_str|http_build_url|' + 'http_cache_etag|http_cache_last_modified|http_chunked_decode|http_date|http_deflate|http_get|http_get_request_body|' + 'http_get_request_body_stream|http_get_request_headers|http_head|http_inflate|http_match_etag|http_match_modified|' + 'http_match_request_header|http_negotiate_charset|http_negotiate_content_type|http_negotiate_language|http_parse_cookie|http_parse_headers|' + 'http_parse_message|http_parse_params|http_persistent_handles_clean|http_persistent_handles_count|http_persistent_handles_ident|' + 'http_post_data|http_post_fields|http_put_data|http_put_file|http_put_stream|http_redirect|http_request|http_request_body_encode|' + 'http_request_method_exists|http_request_method_name|http_request_method_register|http_request_method_unregister|http_response_code|' + 'http_send_content_disposition|http_send_content_type|http_send_data|http_send_file|http_send_last_modified|http_send_status|' + 'http_send_stream|http_support|http_throttle|httpdeflatestream|httpdeflatestream_construct|httpdeflatestream_factory|' + 'httpdeflatestream_finish|httpdeflatestream_flush|httpdeflatestream_update|httpinflatestream|httpinflatestream_construct|' + 'httpinflatestream_factory|httpinflatestream_finish|httpinflatestream_flush|httpinflatestream_update|httpmessage|httpmessage_addheaders|' + 'httpmessage_construct|httpmessage_detach|httpmessage_factory|httpmessage_fromenv|httpmessage_fromstring|httpmessage_getbody|' + 'httpmessage_getheader|httpmessage_getheaders|httpmessage_gethttpversion|httpmessage_getparentmessage|httpmessage_getrequestmethod|' + 'httpmessage_getrequesturl|httpmessage_getresponsecode|httpmessage_getresponsestatus|httpmessage_gettype|httpmessage_guesscontenttype|' + 'httpmessage_prepend|httpmessage_reverse|httpmessage_send|httpmessage_setbody|httpmessage_setheaders|httpmessage_sethttpversion|' + 'httpmessage_setrequestmethod|httpmessage_setrequesturl|httpmessage_setresponsecode|httpmessage_setresponsestatus|httpmessage_settype|' + 'httpmessage_tomessagetypeobject|httpmessage_tostring|httpquerystring|httpquerystring_construct|httpquerystring_get|httpquerystring_mod|' + 'httpquerystring_set|httpquerystring_singleton|httpquerystring_toarray|httpquerystring_tostring|httpquerystring_xlate|httprequest|' + 'httprequest_addcookies|httprequest_addheaders|httprequest_addpostfields|httprequest_addpostfile|httprequest_addputdata|' + 'httprequest_addquerydata|httprequest_addrawpostdata|httprequest_addssloptions|httprequest_clearhistory|httprequest_construct|' + 'httprequest_enablecookies|httprequest_getcontenttype|httprequest_getcookies|httprequest_getheaders|httprequest_gethistory|' + 'httprequest_getmethod|httprequest_getoptions|httprequest_getpostfields|httprequest_getpostfiles|httprequest_getputdata|' + 'httprequest_getputfile|httprequest_getquerydata|httprequest_getrawpostdata|httprequest_getrawrequestmessage|' + 'httprequest_getrawresponsemessage|httprequest_getrequestmessage|httprequest_getresponsebody|httprequest_getresponsecode|' + 'httprequest_getresponsecookies|httprequest_getresponsedata|httprequest_getresponseheader|httprequest_getresponseinfo|' + 'httprequest_getresponsemessage|httprequest_getresponsestatus|httprequest_getssloptions|httprequest_geturl|httprequest_resetcookies|' + 'httprequest_send|httprequest_setcontenttype|httprequest_setcookies|httprequest_setheaders|httprequest_setmethod|httprequest_setoptions|' + 'httprequest_setpostfields|httprequest_setpostfiles|httprequest_setputdata|httprequest_setputfile|httprequest_setquerydata|' + 'httprequest_setrawpostdata|httprequest_setssloptions|httprequest_seturl|httprequestpool|httprequestpool_attach|httprequestpool_construct|' + 'httprequestpool_destruct|httprequestpool_detach|httprequestpool_getattachedrequests|httprequestpool_getfinishedrequests|' + 'httprequestpool_reset|httprequestpool_send|httprequestpool_socketperform|httprequestpool_socketselect|httpresponse|httpresponse_capture|' + 'httpresponse_getbuffersize|httpresponse_getcache|httpresponse_getcachecontrol|httpresponse_getcontentdisposition|' + 'httpresponse_getcontenttype|httpresponse_getdata|httpresponse_getetag|httpresponse_getfile|httpresponse_getgzip|httpresponse_getheader|' + 'httpresponse_getlastmodified|httpresponse_getrequestbody|httpresponse_getrequestbodystream|httpresponse_getrequestheaders|' + 'httpresponse_getstream|httpresponse_getthrottledelay|httpresponse_guesscontenttype|httpresponse_redirect|httpresponse_send|' + 'httpresponse_setbuffersize|httpresponse_setcache|httpresponse_setcachecontrol|httpresponse_setcontentdisposition|' + 'httpresponse_setcontenttype|httpresponse_setdata|httpresponse_setetag|httpresponse_setfile|httpresponse_setgzip|httpresponse_setheader|' + 'httpresponse_setlastmodified|httpresponse_setstream|httpresponse_setthrottledelay|httpresponse_status|hw_array2objrec|hw_changeobject|' + 'hw_children|hw_childrenobj|hw_close|hw_connect|hw_connection_info|hw_cp|hw_deleteobject|hw_docbyanchor|hw_docbyanchorobj|' + 'hw_document_attributes|hw_document_bodytag|hw_document_content|hw_document_setcontent|hw_document_size|hw_dummy|hw_edittext|hw_error|' + 'hw_errormsg|hw_free_document|hw_getanchors|hw_getanchorsobj|hw_getandlock|hw_getchildcoll|hw_getchildcollobj|hw_getchilddoccoll|' + 'hw_getchilddoccollobj|hw_getobject|hw_getobjectbyquery|hw_getobjectbyquerycoll|hw_getobjectbyquerycollobj|hw_getobjectbyqueryobj|' + 'hw_getparents|hw_getparentsobj|hw_getrellink|hw_getremote|hw_getremotechildren|hw_getsrcbydestobj|hw_gettext|hw_getusername|hw_identify|' + 'hw_incollections|hw_info|hw_inscoll|hw_insdoc|hw_insertanchors|hw_insertdocument|hw_insertobject|hw_mapid|hw_modifyobject|hw_mv|' + 'hw_new_document|hw_objrec2array|hw_output_document|hw_pconnect|hw_pipedocument|hw_root|hw_setlinkroot|hw_stat|hw_unlock|hw_who|' + 'hwapi_attribute|hwapi_attribute_key|hwapi_attribute_langdepvalue|hwapi_attribute_value|hwapi_attribute_values|hwapi_checkin|' + 'hwapi_checkout|hwapi_children|hwapi_content|hwapi_content_mimetype|hwapi_content_read|hwapi_copy|hwapi_dbstat|hwapi_dcstat|' + 'hwapi_dstanchors|hwapi_dstofsrcanchor|hwapi_error_count|hwapi_error_reason|hwapi_find|hwapi_ftstat|hwapi_hgcsp|hwapi_hwstat|' + 'hwapi_identify|hwapi_info|hwapi_insert|hwapi_insertanchor|hwapi_insertcollection|hwapi_insertdocument|hwapi_link|hwapi_lock|hwapi_move|' + 'hwapi_new_content|hwapi_object|hwapi_object_assign|hwapi_object_attreditable|hwapi_object_count|hwapi_object_insert|hwapi_object_new|' + 'hwapi_object_remove|hwapi_object_title|hwapi_object_value|hwapi_objectbyanchor|hwapi_parents|hwapi_reason_description|hwapi_reason_type|' + 'hwapi_remove|hwapi_replace|hwapi_setcommittedversion|hwapi_srcanchors|hwapi_srcsofdst|hwapi_unlock|hwapi_user|hwapi_userlist|hypot|' + 'ibase_add_user|ibase_affected_rows|ibase_backup|ibase_blob_add|ibase_blob_cancel|ibase_blob_close|ibase_blob_create|ibase_blob_echo|' + 'ibase_blob_get|ibase_blob_import|ibase_blob_info|ibase_blob_open|ibase_close|ibase_commit|ibase_commit_ret|ibase_connect|ibase_db_info|' + 'ibase_delete_user|ibase_drop_db|ibase_errcode|ibase_errmsg|ibase_execute|ibase_fetch_assoc|ibase_fetch_object|ibase_fetch_row|' + 'ibase_field_info|ibase_free_event_handler|ibase_free_query|ibase_free_result|ibase_gen_id|ibase_maintain_db|ibase_modify_user|' + 'ibase_name_result|ibase_num_fields|ibase_num_params|ibase_param_info|ibase_pconnect|ibase_prepare|ibase_query|ibase_restore|' + 'ibase_rollback|ibase_rollback_ret|ibase_server_info|ibase_service_attach|ibase_service_detach|ibase_set_event_handler|ibase_timefmt|' + 'ibase_trans|ibase_wait_event|iconv|iconv_get_encoding|iconv_mime_decode|iconv_mime_decode_headers|iconv_mime_encode|iconv_set_encoding|' + 'iconv_strlen|iconv_strpos|iconv_strrpos|iconv_substr|id3_get_frame_long_name|id3_get_frame_short_name|id3_get_genre_id|id3_get_genre_list|' + 'id3_get_genre_name|id3_get_tag|id3_get_version|id3_remove_tag|id3_set_tag|id3v2attachedpictureframe|id3v2frame|id3v2tag|idate|' + 'idn_to_ascii|idn_to_unicode|idn_to_utf8|ifx_affected_rows|ifx_blobinfile_mode|ifx_byteasvarchar|ifx_close|ifx_connect|ifx_copy_blob|' + 'ifx_create_blob|ifx_create_char|ifx_do|ifx_error|ifx_errormsg|ifx_fetch_row|ifx_fieldproperties|ifx_fieldtypes|ifx_free_blob|' + 'ifx_free_char|ifx_free_result|ifx_get_blob|ifx_get_char|ifx_getsqlca|ifx_htmltbl_result|ifx_nullformat|ifx_num_fields|ifx_num_rows|' + 'ifx_pconnect|ifx_prepare|ifx_query|ifx_textasvarchar|ifx_update_blob|ifx_update_char|ifxus_close_slob|ifxus_create_slob|ifxus_free_slob|' + 'ifxus_open_slob|ifxus_read_slob|ifxus_seek_slob|ifxus_tell_slob|ifxus_write_slob|ignore_user_abort|iis_add_server|iis_get_dir_security|' + 'iis_get_script_map|iis_get_server_by_comment|iis_get_server_by_path|iis_get_server_rights|iis_get_service_state|iis_remove_server|' + 'iis_set_app_settings|iis_set_dir_security|iis_set_script_map|iis_set_server_rights|iis_start_server|iis_start_service|iis_stop_server|' + 'iis_stop_service|image2wbmp|image_type_to_extension|image_type_to_mime_type|imagealphablending|imageantialias|imagearc|imagechar|' + 'imagecharup|imagecolorallocate|imagecolorallocatealpha|imagecolorat|imagecolorclosest|imagecolorclosestalpha|imagecolorclosesthwb|' + 'imagecolordeallocate|imagecolorexact|imagecolorexactalpha|imagecolormatch|imagecolorresolve|imagecolorresolvealpha|imagecolorset|' + 'imagecolorsforindex|imagecolorstotal|imagecolortransparent|imageconvolution|imagecopy|imagecopymerge|imagecopymergegray|' + 'imagecopyresampled|imagecopyresized|imagecreate|imagecreatefromgd|imagecreatefromgd2|imagecreatefromgd2part|imagecreatefromgif|' + 'imagecreatefromjpeg|imagecreatefrompng|imagecreatefromstring|imagecreatefromwbmp|imagecreatefromxbm|imagecreatefromxpm|' + 'imagecreatetruecolor|imagedashedline|imagedestroy|imageellipse|imagefill|imagefilledarc|imagefilledellipse|imagefilledpolygon|' + 'imagefilledrectangle|imagefilltoborder|imagefilter|imagefontheight|imagefontwidth|imageftbbox|imagefttext|imagegammacorrect|imagegd|' + 'imagegd2|imagegif|imagegrabscreen|imagegrabwindow|imageinterlace|imageistruecolor|imagejpeg|imagelayereffect|imageline|imageloadfont|' + 'imagepalettecopy|imagepng|imagepolygon|imagepsbbox|imagepsencodefont|imagepsextendfont|imagepsfreefont|imagepsloadfont|imagepsslantfont|' + 'imagepstext|imagerectangle|imagerotate|imagesavealpha|imagesetbrush|imagesetpixel|imagesetstyle|imagesetthickness|imagesettile|' + 'imagestring|imagestringup|imagesx|imagesy|imagetruecolortopalette|imagettfbbox|imagettftext|imagetypes|imagewbmp|imagexbm|imagick|' + 'imagick_adaptiveblurimage|imagick_adaptiveresizeimage|imagick_adaptivesharpenimage|imagick_adaptivethresholdimage|imagick_addimage|' + 'imagick_addnoiseimage|imagick_affinetransformimage|imagick_animateimages|imagick_annotateimage|imagick_appendimages|imagick_averageimages|' + 'imagick_blackthresholdimage|imagick_blurimage|imagick_borderimage|imagick_charcoalimage|imagick_chopimage|imagick_clear|imagick_clipimage|' + 'imagick_clippathimage|imagick_clone|imagick_clutimage|imagick_coalesceimages|imagick_colorfloodfillimage|imagick_colorizeimage|' + 'imagick_combineimages|imagick_commentimage|imagick_compareimagechannels|imagick_compareimagelayers|imagick_compareimages|' + 'imagick_compositeimage|imagick_construct|imagick_contrastimage|imagick_contraststretchimage|imagick_convolveimage|imagick_cropimage|' + 'imagick_cropthumbnailimage|imagick_current|imagick_cyclecolormapimage|imagick_decipherimage|imagick_deconstructimages|' + 'imagick_deleteimageartifact|imagick_despeckleimage|imagick_destroy|imagick_displayimage|imagick_displayimages|imagick_distortimage|' + 'imagick_drawimage|imagick_edgeimage|imagick_embossimage|imagick_encipherimage|imagick_enhanceimage|imagick_equalizeimage|' + 'imagick_evaluateimage|imagick_extentimage|imagick_flattenimages|imagick_flipimage|imagick_floodfillpaintimage|imagick_flopimage|' + 'imagick_frameimage|imagick_fximage|imagick_gammaimage|imagick_gaussianblurimage|imagick_getcolorspace|imagick_getcompression|' + 'imagick_getcompressionquality|imagick_getcopyright|imagick_getfilename|imagick_getfont|imagick_getformat|imagick_getgravity|' + 'imagick_gethomeurl|imagick_getimage|imagick_getimagealphachannel|imagick_getimageartifact|imagick_getimagebackgroundcolor|' + 'imagick_getimageblob|imagick_getimageblueprimary|imagick_getimagebordercolor|imagick_getimagechanneldepth|' + 'imagick_getimagechanneldistortion|imagick_getimagechanneldistortions|imagick_getimagechannelextrema|imagick_getimagechannelmean|' + 'imagick_getimagechannelrange|imagick_getimagechannelstatistics|imagick_getimageclipmask|imagick_getimagecolormapcolor|' + 'imagick_getimagecolors|imagick_getimagecolorspace|imagick_getimagecompose|imagick_getimagecompression|imagick_getimagecompressionquality|' + 'imagick_getimagedelay|imagick_getimagedepth|imagick_getimagedispose|imagick_getimagedistortion|imagick_getimageextrema|' + 'imagick_getimagefilename|imagick_getimageformat|imagick_getimagegamma|imagick_getimagegeometry|imagick_getimagegravity|' + 'imagick_getimagegreenprimary|imagick_getimageheight|imagick_getimagehistogram|imagick_getimageindex|imagick_getimageinterlacescheme|' + 'imagick_getimageinterpolatemethod|imagick_getimageiterations|imagick_getimagelength|imagick_getimagemagicklicense|imagick_getimagematte|' + 'imagick_getimagemattecolor|imagick_getimageorientation|imagick_getimagepage|imagick_getimagepixelcolor|imagick_getimageprofile|' + 'imagick_getimageprofiles|imagick_getimageproperties|imagick_getimageproperty|imagick_getimageredprimary|imagick_getimageregion|' + 'imagick_getimagerenderingintent|imagick_getimageresolution|imagick_getimagesblob|imagick_getimagescene|imagick_getimagesignature|' + 'imagick_getimagesize|imagick_getimagetickspersecond|imagick_getimagetotalinkdensity|imagick_getimagetype|imagick_getimageunits|' + 'imagick_getimagevirtualpixelmethod|imagick_getimagewhitepoint|imagick_getimagewidth|imagick_getinterlacescheme|imagick_getiteratorindex|' + 'imagick_getnumberimages|imagick_getoption|imagick_getpackagename|imagick_getpage|imagick_getpixeliterator|imagick_getpixelregioniterator|' + 'imagick_getpointsize|imagick_getquantumdepth|imagick_getquantumrange|imagick_getreleasedate|imagick_getresource|imagick_getresourcelimit|' + 'imagick_getsamplingfactors|imagick_getsize|imagick_getsizeoffset|imagick_getversion|imagick_hasnextimage|imagick_haspreviousimage|' + 'imagick_identifyimage|imagick_implodeimage|imagick_labelimage|imagick_levelimage|imagick_linearstretchimage|imagick_liquidrescaleimage|' + 'imagick_magnifyimage|imagick_mapimage|imagick_mattefloodfillimage|imagick_medianfilterimage|imagick_mergeimagelayers|imagick_minifyimage|' + 'imagick_modulateimage|imagick_montageimage|imagick_morphimages|imagick_mosaicimages|imagick_motionblurimage|imagick_negateimage|' + 'imagick_newimage|imagick_newpseudoimage|imagick_nextimage|imagick_normalizeimage|imagick_oilpaintimage|imagick_opaquepaintimage|' + 'imagick_optimizeimagelayers|imagick_orderedposterizeimage|imagick_paintfloodfillimage|imagick_paintopaqueimage|' + 'imagick_painttransparentimage|imagick_pingimage|imagick_pingimageblob|imagick_pingimagefile|imagick_polaroidimage|imagick_posterizeimage|' + 'imagick_previewimages|imagick_previousimage|imagick_profileimage|imagick_quantizeimage|imagick_quantizeimages|imagick_queryfontmetrics|' + 'imagick_queryfonts|imagick_queryformats|imagick_radialblurimage|imagick_raiseimage|imagick_randomthresholdimage|imagick_readimage|' + 'imagick_readimageblob|imagick_readimagefile|imagick_recolorimage|imagick_reducenoiseimage|imagick_removeimage|imagick_removeimageprofile|' + 'imagick_render|imagick_resampleimage|imagick_resetimagepage|imagick_resizeimage|imagick_rollimage|imagick_rotateimage|' + 'imagick_roundcorners|imagick_sampleimage|imagick_scaleimage|imagick_separateimagechannel|imagick_sepiatoneimage|' + 'imagick_setbackgroundcolor|imagick_setcolorspace|imagick_setcompression|imagick_setcompressionquality|imagick_setfilename|' + 'imagick_setfirstiterator|imagick_setfont|imagick_setformat|imagick_setgravity|imagick_setimage|imagick_setimagealphachannel|' + 'imagick_setimageartifact|imagick_setimagebackgroundcolor|imagick_setimagebias|imagick_setimageblueprimary|imagick_setimagebordercolor|' + 'imagick_setimagechanneldepth|imagick_setimageclipmask|imagick_setimagecolormapcolor|imagick_setimagecolorspace|imagick_setimagecompose|' + 'imagick_setimagecompression|imagick_setimagecompressionquality|imagick_setimagedelay|imagick_setimagedepth|imagick_setimagedispose|' + 'imagick_setimageextent|imagick_setimagefilename|imagick_setimageformat|imagick_setimagegamma|imagick_setimagegravity|' + 'imagick_setimagegreenprimary|imagick_setimageindex|imagick_setimageinterlacescheme|imagick_setimageinterpolatemethod|' + 'imagick_setimageiterations|imagick_setimagematte|imagick_setimagemattecolor|imagick_setimageopacity|imagick_setimageorientation|' + 'imagick_setimagepage|imagick_setimageprofile|imagick_setimageproperty|imagick_setimageredprimary|imagick_setimagerenderingintent|' + 'imagick_setimageresolution|imagick_setimagescene|imagick_setimagetickspersecond|imagick_setimagetype|imagick_setimageunits|' + 'imagick_setimagevirtualpixelmethod|imagick_setimagewhitepoint|imagick_setinterlacescheme|imagick_setiteratorindex|imagick_setlastiterator|' + 'imagick_setoption|imagick_setpage|imagick_setpointsize|imagick_setresolution|imagick_setresourcelimit|imagick_setsamplingfactors|' + 'imagick_setsize|imagick_setsizeoffset|imagick_settype|imagick_shadeimage|imagick_shadowimage|imagick_sharpenimage|imagick_shaveimage|' + 'imagick_shearimage|imagick_sigmoidalcontrastimage|imagick_sketchimage|imagick_solarizeimage|imagick_spliceimage|imagick_spreadimage|' + 'imagick_steganoimage|imagick_stereoimage|imagick_stripimage|imagick_swirlimage|imagick_textureimage|imagick_thresholdimage|' + 'imagick_thumbnailimage|imagick_tintimage|imagick_transformimage|imagick_transparentpaintimage|imagick_transposeimage|' + 'imagick_transverseimage|imagick_trimimage|imagick_uniqueimagecolors|imagick_unsharpmaskimage|imagick_valid|imagick_vignetteimage|' + 'imagick_waveimage|imagick_whitethresholdimage|imagick_writeimage|imagick_writeimagefile|imagick_writeimages|imagick_writeimagesfile|' + 'imagickdraw|imagickdraw_affine|imagickdraw_annotation|imagickdraw_arc|imagickdraw_bezier|imagickdraw_circle|imagickdraw_clear|' + 'imagickdraw_clone|imagickdraw_color|imagickdraw_comment|imagickdraw_composite|imagickdraw_construct|imagickdraw_destroy|' + 'imagickdraw_ellipse|imagickdraw_getclippath|imagickdraw_getcliprule|imagickdraw_getclipunits|imagickdraw_getfillcolor|' + 'imagickdraw_getfillopacity|imagickdraw_getfillrule|imagickdraw_getfont|imagickdraw_getfontfamily|imagickdraw_getfontsize|' + 'imagickdraw_getfontstyle|imagickdraw_getfontweight|imagickdraw_getgravity|imagickdraw_getstrokeantialias|imagickdraw_getstrokecolor|' + 'imagickdraw_getstrokedasharray|imagickdraw_getstrokedashoffset|imagickdraw_getstrokelinecap|imagickdraw_getstrokelinejoin|' + 'imagickdraw_getstrokemiterlimit|imagickdraw_getstrokeopacity|imagickdraw_getstrokewidth|imagickdraw_gettextalignment|' + 'imagickdraw_gettextantialias|imagickdraw_gettextdecoration|imagickdraw_gettextencoding|imagickdraw_gettextundercolor|' + 'imagickdraw_getvectorgraphics|imagickdraw_line|imagickdraw_matte|imagickdraw_pathclose|imagickdraw_pathcurvetoabsolute|' + 'imagickdraw_pathcurvetoquadraticbezierabsolute|imagickdraw_pathcurvetoquadraticbezierrelative|' + 'imagickdraw_pathcurvetoquadraticbeziersmoothabsolute|imagickdraw_pathcurvetoquadraticbeziersmoothrelative|imagickdraw_pathcurvetorelative|' + 'imagickdraw_pathcurvetosmoothabsolute|imagickdraw_pathcurvetosmoothrelative|imagickdraw_pathellipticarcabsolute|' + 'imagickdraw_pathellipticarcrelative|imagickdraw_pathfinish|imagickdraw_pathlinetoabsolute|imagickdraw_pathlinetohorizontalabsolute|' + 'imagickdraw_pathlinetohorizontalrelative|imagickdraw_pathlinetorelative|imagickdraw_pathlinetoverticalabsolute|' + 'imagickdraw_pathlinetoverticalrelative|imagickdraw_pathmovetoabsolute|imagickdraw_pathmovetorelative|imagickdraw_pathstart|' + 'imagickdraw_point|imagickdraw_polygon|imagickdraw_polyline|imagickdraw_pop|imagickdraw_popclippath|imagickdraw_popdefs|' + 'imagickdraw_poppattern|imagickdraw_push|imagickdraw_pushclippath|imagickdraw_pushdefs|imagickdraw_pushpattern|imagickdraw_rectangle|' + 'imagickdraw_render|imagickdraw_rotate|imagickdraw_roundrectangle|imagickdraw_scale|imagickdraw_setclippath|imagickdraw_setcliprule|' + 'imagickdraw_setclipunits|imagickdraw_setfillalpha|imagickdraw_setfillcolor|imagickdraw_setfillopacity|imagickdraw_setfillpatternurl|' + 'imagickdraw_setfillrule|imagickdraw_setfont|imagickdraw_setfontfamily|imagickdraw_setfontsize|imagickdraw_setfontstretch|' + 'imagickdraw_setfontstyle|imagickdraw_setfontweight|imagickdraw_setgravity|imagickdraw_setstrokealpha|imagickdraw_setstrokeantialias|' + 'imagickdraw_setstrokecolor|imagickdraw_setstrokedasharray|imagickdraw_setstrokedashoffset|imagickdraw_setstrokelinecap|' + 'imagickdraw_setstrokelinejoin|imagickdraw_setstrokemiterlimit|imagickdraw_setstrokeopacity|imagickdraw_setstrokepatternurl|' + 'imagickdraw_setstrokewidth|imagickdraw_settextalignment|imagickdraw_settextantialias|imagickdraw_settextdecoration|' + 'imagickdraw_settextencoding|imagickdraw_settextundercolor|imagickdraw_setvectorgraphics|imagickdraw_setviewbox|imagickdraw_skewx|' + 'imagickdraw_skewy|imagickdraw_translate|imagickpixel|imagickpixel_clear|imagickpixel_construct|imagickpixel_destroy|imagickpixel_getcolor|' + 'imagickpixel_getcolorasstring|imagickpixel_getcolorcount|imagickpixel_getcolorvalue|imagickpixel_gethsl|imagickpixel_issimilar|' + 'imagickpixel_setcolor|imagickpixel_setcolorvalue|imagickpixel_sethsl|imagickpixeliterator|imagickpixeliterator_clear|' + 'imagickpixeliterator_construct|imagickpixeliterator_destroy|imagickpixeliterator_getcurrentiteratorrow|' + 'imagickpixeliterator_getiteratorrow|imagickpixeliterator_getnextiteratorrow|imagickpixeliterator_getpreviousiteratorrow|' + 'imagickpixeliterator_newpixeliterator|imagickpixeliterator_newpixelregioniterator|imagickpixeliterator_resetiterator|' + 'imagickpixeliterator_setiteratorfirstrow|imagickpixeliterator_setiteratorlastrow|imagickpixeliterator_setiteratorrow|' + 'imagickpixeliterator_synciterator|imap_8bit|imap_alerts|imap_append|imap_base64|imap_binary|imap_body|imap_bodystruct|imap_check|' + 'imap_clearflag_full|imap_close|imap_create|imap_createmailbox|imap_delete|imap_deletemailbox|imap_errors|imap_expunge|imap_fetch_overview|' + 'imap_fetchbody|imap_fetchheader|imap_fetchmime|imap_fetchstructure|imap_fetchtext|imap_gc|imap_get_quota|imap_get_quotaroot|imap_getacl|' + 'imap_getmailboxes|imap_getsubscribed|imap_header|imap_headerinfo|imap_headers|imap_last_error|imap_list|imap_listmailbox|imap_listscan|' + 'imap_listsubscribed|imap_lsub|imap_mail|imap_mail_compose|imap_mail_copy|imap_mail_move|imap_mailboxmsginfo|imap_mime_header_decode|' + 'imap_msgno|imap_num_msg|imap_num_recent|imap_open|imap_ping|imap_qprint|imap_rename|imap_renamemailbox|imap_reopen|' + 'imap_rfc822_parse_adrlist|imap_rfc822_parse_headers|imap_rfc822_write_address|imap_savebody|imap_scan|imap_scanmailbox|imap_search|' + 'imap_set_quota|imap_setacl|imap_setflag_full|imap_sort|imap_status|imap_subscribe|imap_thread|imap_timeout|imap_uid|imap_undelete|' + 'imap_unsubscribe|imap_utf7_decode|imap_utf7_encode|imap_utf8|implementsinterface|implode|import_request_variables|in_array|include|' + 'include_once|inclued_get_data|inet_ntop|inet_pton|infiniteiterator|ingres_autocommit|ingres_autocommit_state|ingres_charset|ingres_close|' + 'ingres_commit|ingres_connect|ingres_cursor|ingres_errno|ingres_error|ingres_errsqlstate|ingres_escape_string|ingres_execute|' + 'ingres_fetch_array|ingres_fetch_assoc|ingres_fetch_object|ingres_fetch_proc_return|ingres_fetch_row|ingres_field_length|ingres_field_name|' + 'ingres_field_nullable|ingres_field_precision|ingres_field_scale|ingres_field_type|ingres_free_result|ingres_next_error|ingres_num_fields|' + 'ingres_num_rows|ingres_pconnect|ingres_prepare|ingres_query|ingres_result_seek|ingres_rollback|ingres_set_environment|' + 'ingres_unbuffered_query|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|innamespace|inotify_add_watch|inotify_init|inotify_queue_len|' + 'inotify_read|inotify_rm_watch|interface_exists|intl_error_name|intl_get_error_code|intl_get_error_message|intl_is_failure|' + 'intldateformatter|intval|invalidargumentexception|invoke|invokeargs|ip2long|iptcembed|iptcparse|is_a|is_array|is_bool|is_callable|is_dir|' + 'is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|' + 'is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|isabstract|' + 'iscloneable|isdisabled|isfinal|isinstance|isinstantiable|isinterface|isinternal|isiterateable|isset|issubclassof|isuserdefined|iterator|' + 'iterator_apply|iterator_count|iterator_to_array|iteratoraggregate|iteratoriterator|java_last_exception_clear|java_last_exception_get|' + 'jddayofweek|jdmonthname|jdtofrench|jdtogregorian|jdtojewish|jdtojulian|jdtounix|jewishtojd|join|jpeg2wbmp|json_decode|json_encode|' + 'json_last_error|jsonserializable|judy|judy_type|judy_version|juliantojd|kadm5_chpass_principal|kadm5_create_principal|' + 'kadm5_delete_principal|kadm5_destroy|kadm5_flush|kadm5_get_policies|kadm5_get_principal|kadm5_get_principals|kadm5_init_with_password|' + 'kadm5_modify_principal|key|krsort|ksort|lcfirst|lcg_value|lchgrp|lchown|ldap_8859_to_t61|ldap_add|ldap_bind|ldap_close|ldap_compare|' + 'ldap_connect|ldap_count_entries|ldap_delete|ldap_dn2ufn|ldap_err2str|ldap_errno|ldap_error|ldap_explode_dn|ldap_first_attribute|' + 'ldap_first_entry|ldap_first_reference|ldap_free_result|ldap_get_attributes|ldap_get_dn|ldap_get_entries|ldap_get_option|ldap_get_values|' + 'ldap_get_values_len|ldap_list|ldap_mod_add|ldap_mod_del|ldap_mod_replace|ldap_modify|ldap_next_attribute|ldap_next_entry|' + 'ldap_next_reference|ldap_parse_reference|ldap_parse_result|ldap_read|ldap_rename|ldap_sasl_bind|ldap_search|ldap_set_option|' + 'ldap_set_rebind_proc|ldap_sort|ldap_start_tls|ldap_t61_to_8859|ldap_unbind|lengthexception|levenshtein|libxml_clear_errors|' + 'libxml_disable_entity_loader|libxml_get_errors|libxml_get_last_error|libxml_set_streams_context|libxml_use_internal_errors|libxmlerror|' + 'limititerator|link|linkinfo|list|locale|localeconv|localtime|log|log10|log1p|logicexception|long2ip|lstat|ltrim|lzf_compress|' + 'lzf_decompress|lzf_optimized_for|m_checkstatus|m_completeauthorizations|m_connect|m_connectionerror|m_deletetrans|m_destroyconn|' + 'm_destroyengine|m_getcell|m_getcellbynum|m_getcommadelimited|m_getheader|m_initconn|m_initengine|m_iscommadelimited|m_maxconntimeout|' + 'm_monitor|m_numcolumns|m_numrows|m_parsecommadelimited|m_responsekeys|m_responseparam|m_returnstatus|m_setblocking|m_setdropfile|m_setip|' + 'm_setssl|m_setssl_cafile|m_setssl_files|m_settimeout|m_sslcert_gen_hash|m_transactionssent|m_transinqueue|m_transkeyval|m_transnew|' + 'm_transsend|m_uwait|m_validateidentifier|m_verifyconnection|m_verifysslcert|magic_quotes_runtime|mail|' + 'mailparse_determine_best_xfer_encoding|mailparse_msg_create|mailparse_msg_extract_part|mailparse_msg_extract_part_file|' + 'mailparse_msg_extract_whole_part_file|mailparse_msg_free|mailparse_msg_get_part|mailparse_msg_get_part_data|mailparse_msg_get_structure|' + 'mailparse_msg_parse|mailparse_msg_parse_file|mailparse_rfc822_parse_addresses|mailparse_stream_encode|mailparse_uudecode_all|main|max|' + 'maxdb_affected_rows|maxdb_autocommit|maxdb_bind_param|maxdb_bind_result|maxdb_change_user|maxdb_character_set_name|maxdb_client_encoding|' + 'maxdb_close|maxdb_close_long_data|maxdb_commit|maxdb_connect|maxdb_connect_errno|maxdb_connect_error|maxdb_data_seek|maxdb_debug|' + 'maxdb_disable_reads_from_master|maxdb_disable_rpl_parse|maxdb_dump_debug_info|maxdb_embedded_connect|maxdb_enable_reads_from_master|' + 'maxdb_enable_rpl_parse|maxdb_errno|maxdb_error|maxdb_escape_string|maxdb_execute|maxdb_fetch|maxdb_fetch_array|maxdb_fetch_assoc|' + 'maxdb_fetch_field|maxdb_fetch_field_direct|maxdb_fetch_fields|maxdb_fetch_lengths|maxdb_fetch_object|maxdb_fetch_row|maxdb_field_count|' + 'maxdb_field_seek|maxdb_field_tell|maxdb_free_result|maxdb_get_client_info|maxdb_get_client_version|maxdb_get_host_info|maxdb_get_metadata|' + 'maxdb_get_proto_info|maxdb_get_server_info|maxdb_get_server_version|maxdb_info|maxdb_init|maxdb_insert_id|maxdb_kill|maxdb_master_query|' + 'maxdb_more_results|maxdb_multi_query|maxdb_next_result|maxdb_num_fields|maxdb_num_rows|maxdb_options|maxdb_param_count|maxdb_ping|' + 'maxdb_prepare|maxdb_query|maxdb_real_connect|maxdb_real_escape_string|maxdb_real_query|maxdb_report|maxdb_rollback|' + 'maxdb_rpl_parse_enabled|maxdb_rpl_probe|maxdb_rpl_query_type|maxdb_select_db|maxdb_send_long_data|maxdb_send_query|maxdb_server_end|' + 'maxdb_server_init|maxdb_set_opt|maxdb_sqlstate|maxdb_ssl_set|maxdb_stat|maxdb_stmt_affected_rows|maxdb_stmt_bind_param|' + 'maxdb_stmt_bind_result|maxdb_stmt_close|maxdb_stmt_close_long_data|maxdb_stmt_data_seek|maxdb_stmt_errno|maxdb_stmt_error|' + 'maxdb_stmt_execute|maxdb_stmt_fetch|maxdb_stmt_free_result|maxdb_stmt_init|maxdb_stmt_num_rows|maxdb_stmt_param_count|maxdb_stmt_prepare|' + 'maxdb_stmt_reset|maxdb_stmt_result_metadata|maxdb_stmt_send_long_data|maxdb_stmt_sqlstate|maxdb_stmt_store_result|maxdb_store_result|' + 'maxdb_thread_id|maxdb_thread_safe|maxdb_use_result|maxdb_warning_count|mb_check_encoding|mb_convert_case|mb_convert_encoding|' + 'mb_convert_kana|mb_convert_variables|mb_decode_mimeheader|mb_decode_numericentity|mb_detect_encoding|mb_detect_order|mb_encode_mimeheader|' + 'mb_encode_numericentity|mb_encoding_aliases|mb_ereg|mb_ereg_match|mb_ereg_replace|mb_ereg_search|mb_ereg_search_getpos|' + 'mb_ereg_search_getregs|mb_ereg_search_init|mb_ereg_search_pos|mb_ereg_search_regs|mb_ereg_search_setpos|mb_eregi|mb_eregi_replace|' + 'mb_get_info|mb_http_input|mb_http_output|mb_internal_encoding|mb_language|mb_list_encodings|mb_output_handler|mb_parse_str|' + 'mb_preferred_mime_name|mb_regex_encoding|mb_regex_set_options|mb_send_mail|mb_split|mb_strcut|mb_strimwidth|mb_stripos|mb_stristr|' + 'mb_strlen|mb_strpos|mb_strrchr|mb_strrichr|mb_strripos|mb_strrpos|mb_strstr|mb_strtolower|mb_strtoupper|mb_strwidth|' + 'mb_substitute_character|mb_substr|mb_substr_count|mcrypt_cbc|mcrypt_cfb|mcrypt_create_iv|mcrypt_decrypt|mcrypt_ecb|' + 'mcrypt_enc_get_algorithms_name|mcrypt_enc_get_block_size|mcrypt_enc_get_iv_size|mcrypt_enc_get_key_size|mcrypt_enc_get_modes_name|' + 'mcrypt_enc_get_supported_key_sizes|mcrypt_enc_is_block_algorithm|mcrypt_enc_is_block_algorithm_mode|mcrypt_enc_is_block_mode|' + 'mcrypt_enc_self_test|mcrypt_encrypt|mcrypt_generic|mcrypt_generic_deinit|mcrypt_generic_end|mcrypt_generic_init|mcrypt_get_block_size|' + 'mcrypt_get_cipher_name|mcrypt_get_iv_size|mcrypt_get_key_size|mcrypt_list_algorithms|mcrypt_list_modes|mcrypt_module_close|' + 'mcrypt_module_get_algo_block_size|mcrypt_module_get_algo_key_size|mcrypt_module_get_supported_key_sizes|mcrypt_module_is_block_algorithm|' + 'mcrypt_module_is_block_algorithm_mode|mcrypt_module_is_block_mode|mcrypt_module_open|mcrypt_module_self_test|mcrypt_ofb|md5|md5_file|' + 'mdecrypt_generic|memcache|memcache_debug|memcached|memory_get_peak_usage|memory_get_usage|messageformatter|metaphone|method_exists|mhash|' + 'mhash_count|mhash_get_block_size|mhash_get_hash_name|mhash_keygen_s2k|microtime|mime_content_type|min|ming_keypress|' + 'ming_setcubicthreshold|ming_setscale|ming_setswfcompression|ming_useconstants|ming_useswfversion|mkdir|mktime|money_format|mongo|' + 'mongobindata|mongocode|mongocollection|mongoconnectionexception|mongocursor|mongocursorexception|mongocursortimeoutexception|mongodate|' + 'mongodb|mongodbref|mongoexception|mongogridfs|mongogridfscursor|mongogridfsexception|mongogridfsfile|mongoid|mongoint32|mongoint64|' + 'mongomaxkey|mongominkey|mongoregex|mongotimestamp|move_uploaded_file|mpegfile|mqseries_back|mqseries_begin|mqseries_close|mqseries_cmit|' + 'mqseries_conn|mqseries_connx|mqseries_disc|mqseries_get|mqseries_inq|mqseries_open|mqseries_put|mqseries_put1|mqseries_set|' + 'mqseries_strerror|msession_connect|msession_count|msession_create|msession_destroy|msession_disconnect|msession_find|msession_get|' + 'msession_get_array|msession_get_data|msession_inc|msession_list|msession_listvar|msession_lock|msession_plugin|msession_randstr|' + 'msession_set|msession_set_array|msession_set_data|msession_timeout|msession_uniq|msession_unlock|msg_get_queue|msg_queue_exists|' + 'msg_receive|msg_remove_queue|msg_send|msg_set_queue|msg_stat_queue|msql|msql_affected_rows|msql_close|msql_connect|msql_create_db|' + 'msql_createdb|msql_data_seek|msql_db_query|msql_dbname|msql_drop_db|msql_error|msql_fetch_array|msql_fetch_field|msql_fetch_object|' + 'msql_fetch_row|msql_field_flags|msql_field_len|msql_field_name|msql_field_seek|msql_field_table|msql_field_type|msql_fieldflags|' + 'msql_fieldlen|msql_fieldname|msql_fieldtable|msql_fieldtype|msql_free_result|msql_list_dbs|msql_list_fields|msql_list_tables|' + 'msql_num_fields|msql_num_rows|msql_numfields|msql_numrows|msql_pconnect|msql_query|msql_regcase|msql_result|msql_select_db|msql_tablename|' + 'mssql_bind|mssql_close|mssql_connect|mssql_data_seek|mssql_execute|mssql_fetch_array|mssql_fetch_assoc|mssql_fetch_batch|' + 'mssql_fetch_field|mssql_fetch_object|mssql_fetch_row|mssql_field_length|mssql_field_name|mssql_field_seek|mssql_field_type|' + 'mssql_free_result|mssql_free_statement|mssql_get_last_message|mssql_guid_string|mssql_init|mssql_min_error_severity|' + 'mssql_min_message_severity|mssql_next_result|mssql_num_fields|mssql_num_rows|mssql_pconnect|mssql_query|mssql_result|mssql_rows_affected|' + 'mssql_select_db|mt_getrandmax|mt_rand|mt_srand|multipleiterator|mysql_affected_rows|mysql_client_encoding|mysql_close|mysql_connect|' + 'mysql_create_db|mysql_data_seek|mysql_db_name|mysql_db_query|mysql_drop_db|mysql_errno|mysql_error|mysql_escape_string|mysql_fetch_array|' + 'mysql_fetch_assoc|mysql_fetch_field|mysql_fetch_lengths|mysql_fetch_object|mysql_fetch_row|mysql_field_flags|mysql_field_len|' + 'mysql_field_name|mysql_field_seek|mysql_field_table|mysql_field_type|mysql_free_result|mysql_get_client_info|mysql_get_host_info|' + 'mysql_get_proto_info|mysql_get_server_info|mysql_info|mysql_insert_id|mysql_list_dbs|mysql_list_fields|mysql_list_processes|' + 'mysql_list_tables|mysql_num_fields|mysql_num_rows|mysql_pconnect|mysql_ping|mysql_query|mysql_real_escape_string|mysql_result|' + 'mysql_select_db|mysql_set_charset|mysql_stat|mysql_tablename|mysql_thread_id|mysql_unbuffered_query|mysqli|mysqli_affected_rows|' + 'mysqli_autocommit|mysqli_bind_param|mysqli_bind_result|mysqli_cache_stats|mysqli_change_user|mysqli_character_set_name|' + 'mysqli_client_encoding|mysqli_close|mysqli_commit|mysqli_connect|mysqli_connect_errno|mysqli_connect_error|mysqli_data_seek|' + 'mysqli_debug|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_driver|mysqli_dump_debug_info|mysqli_embedded_server_end|' + 'mysqli_embedded_server_start|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_errno|mysqli_error|mysqli_escape_string|' + 'mysqli_execute|mysqli_fetch|mysqli_fetch_all|mysqli_fetch_array|mysqli_fetch_assoc|mysqli_fetch_field|mysqli_fetch_field_direct|' + 'mysqli_fetch_fields|mysqli_fetch_lengths|mysqli_fetch_object|mysqli_fetch_row|mysqli_field_count|mysqli_field_seek|mysqli_field_tell|' + 'mysqli_free_result|mysqli_get_charset|mysqli_get_client_info|mysqli_get_client_stats|mysqli_get_client_version|mysqli_get_connection_stats|' + 'mysqli_get_host_info|mysqli_get_metadata|mysqli_get_proto_info|mysqli_get_server_info|mysqli_get_server_version|mysqli_get_warnings|' + 'mysqli_info|mysqli_init|mysqli_insert_id|mysqli_kill|mysqli_link_construct|mysqli_master_query|mysqli_more_results|mysqli_multi_query|' + 'mysqli_next_result|mysqli_num_fields|mysqli_num_rows|mysqli_options|mysqli_param_count|mysqli_ping|mysqli_poll|mysqli_prepare|' + 'mysqli_query|mysqli_real_connect|mysqli_real_escape_string|mysqli_real_query|mysqli_reap_async_query|mysqli_refresh|mysqli_report|' + 'mysqli_result|mysqli_rollback|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|mysqli_select_db|mysqli_send_long_data|' + 'mysqli_send_query|mysqli_set_charset|mysqli_set_local_infile_default|mysqli_set_local_infile_handler|mysqli_set_opt|mysqli_slave_query|' + 'mysqli_sqlstate|mysqli_ssl_set|mysqli_stat|mysqli_stmt|mysqli_stmt_affected_rows|mysqli_stmt_attr_get|mysqli_stmt_attr_set|' + 'mysqli_stmt_bind_param|mysqli_stmt_bind_result|mysqli_stmt_close|mysqli_stmt_data_seek|mysqli_stmt_errno|mysqli_stmt_error|' + 'mysqli_stmt_execute|mysqli_stmt_fetch|mysqli_stmt_field_count|mysqli_stmt_free_result|mysqli_stmt_get_result|mysqli_stmt_get_warnings|' + 'mysqli_stmt_init|mysqli_stmt_insert_id|mysqli_stmt_next_result|mysqli_stmt_num_rows|mysqli_stmt_param_count|mysqli_stmt_prepare|' + 'mysqli_stmt_reset|mysqli_stmt_result_metadata|mysqli_stmt_send_long_data|mysqli_stmt_sqlstate|mysqli_stmt_store_result|mysqli_store_result|' + 'mysqli_thread_id|mysqli_thread_safe|mysqli_use_result|mysqli_warning|mysqli_warning_count|mysqlnd_ms_get_stats|' + 'mysqlnd_ms_query_is_select|mysqlnd_ms_set_user_pick_server|mysqlnd_qc_change_handler|mysqlnd_qc_clear_cache|mysqlnd_qc_get_cache_info|' + 'mysqlnd_qc_get_core_stats|mysqlnd_qc_get_handler|mysqlnd_qc_get_query_trace_log|mysqlnd_qc_set_user_handlers|natcasesort|natsort|' + 'ncurses_addch|ncurses_addchnstr|ncurses_addchstr|ncurses_addnstr|ncurses_addstr|ncurses_assume_default_colors|ncurses_attroff|' + 'ncurses_attron|ncurses_attrset|ncurses_baudrate|ncurses_beep|ncurses_bkgd|ncurses_bkgdset|ncurses_border|ncurses_bottom_panel|' + 'ncurses_can_change_color|ncurses_cbreak|ncurses_clear|ncurses_clrtobot|ncurses_clrtoeol|ncurses_color_content|ncurses_color_set|' + 'ncurses_curs_set|ncurses_def_prog_mode|ncurses_def_shell_mode|ncurses_define_key|ncurses_del_panel|ncurses_delay_output|ncurses_delch|' + 'ncurses_deleteln|ncurses_delwin|ncurses_doupdate|ncurses_echo|ncurses_echochar|ncurses_end|ncurses_erase|ncurses_erasechar|ncurses_filter|' + 'ncurses_flash|ncurses_flushinp|ncurses_getch|ncurses_getmaxyx|ncurses_getmouse|ncurses_getyx|ncurses_halfdelay|ncurses_has_colors|' + 'ncurses_has_ic|ncurses_has_il|ncurses_has_key|ncurses_hide_panel|ncurses_hline|ncurses_inch|ncurses_init|ncurses_init_color|' + 'ncurses_init_pair|ncurses_insch|ncurses_insdelln|ncurses_insertln|ncurses_insstr|ncurses_instr|ncurses_isendwin|ncurses_keyok|' + 'ncurses_keypad|ncurses_killchar|ncurses_longname|ncurses_meta|ncurses_mouse_trafo|ncurses_mouseinterval|ncurses_mousemask|ncurses_move|' + 'ncurses_move_panel|ncurses_mvaddch|ncurses_mvaddchnstr|ncurses_mvaddchstr|ncurses_mvaddnstr|ncurses_mvaddstr|ncurses_mvcur|' + 'ncurses_mvdelch|ncurses_mvgetch|ncurses_mvhline|ncurses_mvinch|ncurses_mvvline|ncurses_mvwaddstr|ncurses_napms|ncurses_new_panel|' + 'ncurses_newpad|ncurses_newwin|ncurses_nl|ncurses_nocbreak|ncurses_noecho|ncurses_nonl|ncurses_noqiflush|ncurses_noraw|' + 'ncurses_pair_content|ncurses_panel_above|ncurses_panel_below|ncurses_panel_window|ncurses_pnoutrefresh|ncurses_prefresh|ncurses_putp|' + 'ncurses_qiflush|ncurses_raw|ncurses_refresh|ncurses_replace_panel|ncurses_reset_prog_mode|ncurses_reset_shell_mode|ncurses_resetty|' + 'ncurses_savetty|ncurses_scr_dump|ncurses_scr_init|ncurses_scr_restore|ncurses_scr_set|ncurses_scrl|ncurses_show_panel|ncurses_slk_attr|' + 'ncurses_slk_attroff|ncurses_slk_attron|ncurses_slk_attrset|ncurses_slk_clear|ncurses_slk_color|ncurses_slk_init|ncurses_slk_noutrefresh|' + 'ncurses_slk_refresh|ncurses_slk_restore|ncurses_slk_set|ncurses_slk_touch|ncurses_standend|ncurses_standout|ncurses_start_color|' + 'ncurses_termattrs|ncurses_termname|ncurses_timeout|ncurses_top_panel|ncurses_typeahead|ncurses_ungetch|ncurses_ungetmouse|' + 'ncurses_update_panels|ncurses_use_default_colors|ncurses_use_env|ncurses_use_extended_names|ncurses_vidattr|ncurses_vline|ncurses_waddch|' + 'ncurses_waddstr|ncurses_wattroff|ncurses_wattron|ncurses_wattrset|ncurses_wborder|ncurses_wclear|ncurses_wcolor_set|ncurses_werase|' + 'ncurses_wgetch|ncurses_whline|ncurses_wmouse_trafo|ncurses_wmove|ncurses_wnoutrefresh|ncurses_wrefresh|ncurses_wstandend|' + 'ncurses_wstandout|ncurses_wvline|newinstance|newinstanceargs|newt_bell|newt_button|newt_button_bar|newt_centered_window|newt_checkbox|' + 'newt_checkbox_get_value|newt_checkbox_set_flags|newt_checkbox_set_value|newt_checkbox_tree|newt_checkbox_tree_add_item|' + 'newt_checkbox_tree_find_item|newt_checkbox_tree_get_current|newt_checkbox_tree_get_entry_value|newt_checkbox_tree_get_multi_selection|' + 'newt_checkbox_tree_get_selection|newt_checkbox_tree_multi|newt_checkbox_tree_set_current|newt_checkbox_tree_set_entry|' + 'newt_checkbox_tree_set_entry_value|newt_checkbox_tree_set_width|newt_clear_key_buffer|newt_cls|newt_compact_button|' + 'newt_component_add_callback|newt_component_takes_focus|newt_create_grid|newt_cursor_off|newt_cursor_on|newt_delay|newt_draw_form|' + 'newt_draw_root_text|newt_entry|newt_entry_get_value|newt_entry_set|newt_entry_set_filter|newt_entry_set_flags|newt_finished|newt_form|' + 'newt_form_add_component|newt_form_add_components|newt_form_add_hot_key|newt_form_destroy|newt_form_get_current|newt_form_run|' + 'newt_form_set_background|newt_form_set_height|newt_form_set_size|newt_form_set_timer|newt_form_set_width|newt_form_watch_fd|' + 'newt_get_screen_size|newt_grid_add_components_to_form|newt_grid_basic_window|newt_grid_free|newt_grid_get_size|newt_grid_h_close_stacked|' + 'newt_grid_h_stacked|newt_grid_place|newt_grid_set_field|newt_grid_simple_window|newt_grid_v_close_stacked|newt_grid_v_stacked|' + 'newt_grid_wrapped_window|newt_grid_wrapped_window_at|newt_init|newt_label|newt_label_set_text|newt_listbox|newt_listbox_append_entry|' + 'newt_listbox_clear|newt_listbox_clear_selection|newt_listbox_delete_entry|newt_listbox_get_current|newt_listbox_get_selection|' + 'newt_listbox_insert_entry|newt_listbox_item_count|newt_listbox_select_item|newt_listbox_set_current|newt_listbox_set_current_by_key|' + 'newt_listbox_set_data|newt_listbox_set_entry|newt_listbox_set_width|newt_listitem|newt_listitem_get_data|newt_listitem_set|' + 'newt_open_window|newt_pop_help_line|newt_pop_window|newt_push_help_line|newt_radio_get_current|newt_radiobutton|newt_redraw_help_line|' + 'newt_reflow_text|newt_refresh|newt_resize_screen|newt_resume|newt_run_form|newt_scale|newt_scale_set|newt_scrollbar_set|' + 'newt_set_help_callback|newt_set_suspend_callback|newt_suspend|newt_textbox|newt_textbox_get_num_lines|newt_textbox_reflowed|' + 'newt_textbox_set_height|newt_textbox_set_text|newt_vertical_scrollbar|newt_wait_for_key|newt_win_choice|newt_win_entries|newt_win_menu|' + 'newt_win_message|newt_win_messagev|newt_win_ternary|next|ngettext|nl2br|nl_langinfo|norewinditerator|normalizer|notes_body|notes_copy_db|' + 'notes_create_db|notes_create_note|notes_drop_db|notes_find_note|notes_header_info|notes_list_msgs|notes_mark_read|notes_mark_unread|' + 'notes_nav_create|notes_search|notes_unread|notes_version|nsapi_request_headers|nsapi_response_headers|nsapi_virtual|nthmac|number_format|' + 'numberformatter|oauth|oauth_get_sbs|oauth_urlencode|oauthexception|oauthprovider|ob_clean|ob_deflatehandler|ob_end_clean|ob_end_flush|' + 'ob_etaghandler|ob_flush|ob_get_clean|ob_get_contents|ob_get_flush|ob_get_length|ob_get_level|ob_get_status|ob_gzhandler|ob_iconv_handler|' + 'ob_implicit_flush|ob_inflatehandler|ob_list_handlers|ob_start|ob_tidyhandler|oci_bind_array_by_name|oci_bind_by_name|oci_cancel|' + 'oci_client_version|oci_close|oci_collection_append|oci_collection_assign|oci_collection_element_assign|oci_collection_element_get|' + 'oci_collection_free|oci_collection_max|oci_collection_size|oci_collection_trim|oci_commit|oci_connect|oci_define_by_name|oci_error|' + 'oci_execute|oci_fetch|oci_fetch_all|oci_fetch_array|oci_fetch_assoc|oci_fetch_object|oci_fetch_row|oci_field_is_null|oci_field_name|' + 'oci_field_precision|oci_field_scale|oci_field_size|oci_field_type|oci_field_type_raw|oci_free_statement|oci_internal_debug|oci_lob_append|' + 'oci_lob_close|oci_lob_copy|oci_lob_eof|oci_lob_erase|oci_lob_export|oci_lob_flush|oci_lob_free|oci_lob_getbuffering|oci_lob_import|' + 'oci_lob_is_equal|oci_lob_load|oci_lob_read|oci_lob_rewind|oci_lob_save|oci_lob_savefile|oci_lob_seek|oci_lob_setbuffering|oci_lob_size|' + 'oci_lob_tell|oci_lob_truncate|oci_lob_write|oci_lob_writetemporary|oci_lob_writetofile|oci_new_collection|oci_new_connect|oci_new_cursor|' + 'oci_new_descriptor|oci_num_fields|oci_num_rows|oci_parse|oci_password_change|oci_pconnect|oci_result|oci_rollback|oci_server_version|' + 'oci_set_action|oci_set_client_identifier|oci_set_client_info|oci_set_edition|oci_set_module_name|oci_set_prefetch|oci_statement_type|' + 'ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|' + 'ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|' + 'ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|' + 'ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|' + 'ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|' + 'octdec|odbc_autocommit|odbc_binmode|odbc_close|odbc_close_all|odbc_columnprivileges|odbc_columns|odbc_commit|odbc_connect|odbc_cursor|' + 'odbc_data_source|odbc_do|odbc_error|odbc_errormsg|odbc_exec|odbc_execute|odbc_fetch_array|odbc_fetch_into|odbc_fetch_object|' + 'odbc_fetch_row|odbc_field_len|odbc_field_name|odbc_field_num|odbc_field_precision|odbc_field_scale|odbc_field_type|odbc_foreignkeys|' + 'odbc_free_result|odbc_gettypeinfo|odbc_longreadlen|odbc_next_result|odbc_num_fields|odbc_num_rows|odbc_pconnect|odbc_prepare|' + 'odbc_primarykeys|odbc_procedurecolumns|odbc_procedures|odbc_result|odbc_result_all|odbc_rollback|odbc_setoption|odbc_specialcolumns|' + 'odbc_statistics|odbc_tableprivileges|odbc_tables|openal_buffer_create|openal_buffer_data|openal_buffer_destroy|openal_buffer_get|' + 'openal_buffer_loadwav|openal_context_create|openal_context_current|openal_context_destroy|openal_context_process|openal_context_suspend|' + 'openal_device_close|openal_device_open|openal_listener_get|openal_listener_set|openal_source_create|openal_source_destroy|' + 'openal_source_get|openal_source_pause|openal_source_play|openal_source_rewind|openal_source_set|openal_source_stop|openal_stream|opendir|' + 'openlog|openssl_cipher_iv_length|openssl_csr_export|openssl_csr_export_to_file|openssl_csr_get_public_key|openssl_csr_get_subject|' + 'openssl_csr_new|openssl_csr_sign|openssl_decrypt|openssl_dh_compute_key|openssl_digest|openssl_encrypt|openssl_error_string|' + 'openssl_free_key|openssl_get_cipher_methods|openssl_get_md_methods|openssl_get_privatekey|openssl_get_publickey|openssl_open|' + 'openssl_pkcs12_export|openssl_pkcs12_export_to_file|openssl_pkcs12_read|openssl_pkcs7_decrypt|openssl_pkcs7_encrypt|openssl_pkcs7_sign|' + 'openssl_pkcs7_verify|openssl_pkey_export|openssl_pkey_export_to_file|openssl_pkey_free|openssl_pkey_get_details|openssl_pkey_get_private|' + 'openssl_pkey_get_public|openssl_pkey_new|openssl_private_decrypt|openssl_private_encrypt|openssl_public_decrypt|openssl_public_encrypt|' + 'openssl_random_pseudo_bytes|openssl_seal|openssl_sign|openssl_verify|openssl_x509_check_private_key|openssl_x509_checkpurpose|' + 'openssl_x509_export|openssl_x509_export_to_file|openssl_x509_free|openssl_x509_parse|openssl_x509_read|ord|outeriterator|' + 'outofboundsexception|outofrangeexception|output_add_rewrite_var|output_reset_rewrite_vars|overflowexception|overload|override_function|' + 'ovrimos_close|ovrimos_commit|ovrimos_connect|ovrimos_cursor|ovrimos_exec|ovrimos_execute|ovrimos_fetch_into|ovrimos_fetch_row|' + 'ovrimos_field_len|ovrimos_field_name|ovrimos_field_num|ovrimos_field_type|ovrimos_free_result|ovrimos_longreadlen|ovrimos_num_fields|' + 'ovrimos_num_rows|ovrimos_prepare|ovrimos_result|ovrimos_result_all|ovrimos_rollback|pack|parentiterator|parse_ini_file|parse_ini_string|' + 'parse_str|parse_url|parsekit_compile_file|parsekit_compile_string|parsekit_func_arginfo|passthru|pathinfo|pclose|pcntl_alarm|pcntl_exec|' + 'pcntl_fork|pcntl_getpriority|pcntl_setpriority|pcntl_signal|pcntl_signal_dispatch|pcntl_sigprocmask|pcntl_sigtimedwait|pcntl_sigwaitinfo|' + 'pcntl_wait|pcntl_waitpid|pcntl_wexitstatus|pcntl_wifexited|pcntl_wifsignaled|pcntl_wifstopped|pcntl_wstopsig|pcntl_wtermsig|' + 'pdf_activate_item|pdf_add_annotation|pdf_add_bookmark|pdf_add_launchlink|pdf_add_locallink|pdf_add_nameddest|pdf_add_note|pdf_add_outline|' + 'pdf_add_pdflink|pdf_add_table_cell|pdf_add_textflow|pdf_add_thumbnail|pdf_add_weblink|pdf_arc|pdf_arcn|pdf_attach_file|pdf_begin_document|' + 'pdf_begin_font|pdf_begin_glyph|pdf_begin_item|pdf_begin_layer|pdf_begin_page|pdf_begin_page_ext|pdf_begin_pattern|pdf_begin_template|' + 'pdf_begin_template_ext|pdf_circle|pdf_clip|pdf_close|pdf_close_image|pdf_close_pdi|pdf_close_pdi_page|pdf_closepath|' + 'pdf_closepath_fill_stroke|pdf_closepath_stroke|pdf_concat|pdf_continue_text|pdf_create_3dview|pdf_create_action|pdf_create_annotation|' + 'pdf_create_bookmark|pdf_create_field|pdf_create_fieldgroup|pdf_create_gstate|pdf_create_pvf|pdf_create_textflow|pdf_curveto|' + 'pdf_define_layer|pdf_delete|pdf_delete_pvf|pdf_delete_table|pdf_delete_textflow|pdf_encoding_set_char|pdf_end_document|pdf_end_font|' + 'pdf_end_glyph|pdf_end_item|pdf_end_layer|pdf_end_page|pdf_end_page_ext|pdf_end_pattern|pdf_end_template|pdf_endpath|pdf_fill|' + 'pdf_fill_imageblock|pdf_fill_pdfblock|pdf_fill_stroke|pdf_fill_textblock|pdf_findfont|pdf_fit_image|pdf_fit_pdi_page|pdf_fit_table|' + 'pdf_fit_textflow|pdf_fit_textline|pdf_get_apiname|pdf_get_buffer|pdf_get_errmsg|pdf_get_errnum|pdf_get_font|pdf_get_fontname|' + 'pdf_get_fontsize|pdf_get_image_height|pdf_get_image_width|pdf_get_majorversion|pdf_get_minorversion|pdf_get_parameter|' + 'pdf_get_pdi_parameter|pdf_get_pdi_value|pdf_get_value|pdf_info_font|pdf_info_matchbox|pdf_info_table|pdf_info_textflow|pdf_info_textline|' + 'pdf_initgraphics|pdf_lineto|pdf_load_3ddata|pdf_load_font|pdf_load_iccprofile|pdf_load_image|pdf_makespotcolor|pdf_moveto|pdf_new|' + 'pdf_open_ccitt|pdf_open_file|pdf_open_gif|pdf_open_image|pdf_open_image_file|pdf_open_jpeg|pdf_open_memory_image|pdf_open_pdi|' + 'pdf_open_pdi_document|pdf_open_pdi_page|pdf_open_tiff|pdf_pcos_get_number|pdf_pcos_get_stream|pdf_pcos_get_string|pdf_place_image|' + 'pdf_place_pdi_page|pdf_process_pdi|pdf_rect|pdf_restore|pdf_resume_page|pdf_rotate|pdf_save|pdf_scale|pdf_set_border_color|' + 'pdf_set_border_dash|pdf_set_border_style|pdf_set_char_spacing|pdf_set_duration|pdf_set_gstate|pdf_set_horiz_scaling|pdf_set_info|' + 'pdf_set_info_author|pdf_set_info_creator|pdf_set_info_keywords|pdf_set_info_subject|pdf_set_info_title|pdf_set_layer_dependency|' + 'pdf_set_leading|pdf_set_parameter|pdf_set_text_matrix|pdf_set_text_pos|pdf_set_text_rendering|pdf_set_text_rise|pdf_set_value|' + 'pdf_set_word_spacing|pdf_setcolor|pdf_setdash|pdf_setdashpattern|pdf_setflat|pdf_setfont|pdf_setgray|pdf_setgray_fill|pdf_setgray_stroke|' + 'pdf_setlinecap|pdf_setlinejoin|pdf_setlinewidth|pdf_setmatrix|pdf_setmiterlimit|pdf_setpolydash|pdf_setrgbcolor|pdf_setrgbcolor_fill|' + 'pdf_setrgbcolor_stroke|pdf_shading|pdf_shading_pattern|pdf_shfill|pdf_show|pdf_show_boxed|pdf_show_xy|pdf_skew|pdf_stringwidth|pdf_stroke|' + 'pdf_suspend_page|pdf_translate|pdf_utf16_to_utf8|pdf_utf32_to_utf16|pdf_utf8_to_utf16|pdo|pdo_cubrid_schema|pdo_pgsqllobcreate|' + 'pdo_pgsqllobopen|pdo_pgsqllobunlink|pdo_sqlitecreateaggregate|pdo_sqlitecreatefunction|pdoexception|pdostatement|pfsockopen|' + 'pg_affected_rows|pg_cancel_query|pg_client_encoding|pg_close|pg_connect|pg_connection_busy|pg_connection_reset|pg_connection_status|' + 'pg_convert|pg_copy_from|pg_copy_to|pg_dbname|pg_delete|pg_end_copy|pg_escape_bytea|pg_escape_string|pg_execute|pg_fetch_all|' + 'pg_fetch_all_columns|pg_fetch_array|pg_fetch_assoc|pg_fetch_object|pg_fetch_result|pg_fetch_row|pg_field_is_null|pg_field_name|' + 'pg_field_num|pg_field_prtlen|pg_field_size|pg_field_table|pg_field_type|pg_field_type_oid|pg_free_result|pg_get_notify|pg_get_pid|' + 'pg_get_result|pg_host|pg_insert|pg_last_error|pg_last_notice|pg_last_oid|pg_lo_close|pg_lo_create|pg_lo_export|pg_lo_import|pg_lo_open|' + 'pg_lo_read|pg_lo_read_all|pg_lo_seek|pg_lo_tell|pg_lo_unlink|pg_lo_write|pg_meta_data|pg_num_fields|pg_num_rows|pg_options|' + 'pg_parameter_status|pg_pconnect|pg_ping|pg_port|pg_prepare|pg_put_line|pg_query|pg_query_params|pg_result_error|pg_result_error_field|' + 'pg_result_seek|pg_result_status|pg_select|pg_send_execute|pg_send_prepare|pg_send_query|pg_send_query_params|pg_set_client_encoding|' + 'pg_set_error_verbosity|pg_trace|pg_transaction_status|pg_tty|pg_unescape_bytea|pg_untrace|pg_update|pg_version|php_check_syntax|' + 'php_ini_loaded_file|php_ini_scanned_files|php_logo_guid|php_sapi_name|php_strip_whitespace|php_uname|phpcredits|phpinfo|phpversion|pi|' + 'png2wbmp|popen|pos|posix_access|posix_ctermid|posix_errno|posix_get_last_error|posix_getcwd|posix_getegid|posix_geteuid|posix_getgid|' + 'posix_getgrgid|posix_getgrnam|posix_getgroups|posix_getlogin|posix_getpgid|posix_getpgrp|posix_getpid|posix_getppid|posix_getpwnam|' + 'posix_getpwuid|posix_getrlimit|posix_getsid|posix_getuid|posix_initgroups|posix_isatty|posix_kill|posix_mkfifo|posix_mknod|posix_setegid|' + 'posix_seteuid|posix_setgid|posix_setpgid|posix_setsid|posix_setuid|posix_strerror|posix_times|posix_ttyname|posix_uname|pow|preg_filter|' + 'preg_grep|preg_last_error|preg_match|preg_match_all|preg_quote|preg_replace|preg_replace_callback|preg_split|prev|print|print_r|' + 'printer_abort|printer_close|printer_create_brush|printer_create_dc|printer_create_font|printer_create_pen|printer_delete_brush|' + 'printer_delete_dc|printer_delete_font|printer_delete_pen|printer_draw_bmp|printer_draw_chord|printer_draw_elipse|printer_draw_line|' + 'printer_draw_pie|printer_draw_rectangle|printer_draw_roundrect|printer_draw_text|printer_end_doc|printer_end_page|printer_get_option|' + 'printer_list|printer_logical_fontheight|printer_open|printer_select_brush|printer_select_font|printer_select_pen|printer_set_option|' + 'printer_start_doc|printer_start_page|printer_write|printf|proc_close|proc_get_status|proc_nice|proc_open|proc_terminate|property_exists|' + 'ps_add_bookmark|ps_add_launchlink|ps_add_locallink|ps_add_note|ps_add_pdflink|ps_add_weblink|ps_arc|ps_arcn|ps_begin_page|' + 'ps_begin_pattern|ps_begin_template|ps_circle|ps_clip|ps_close|ps_close_image|ps_closepath|ps_closepath_stroke|ps_continue_text|ps_curveto|' + 'ps_delete|ps_end_page|ps_end_pattern|ps_end_template|ps_fill|ps_fill_stroke|ps_findfont|ps_get_buffer|ps_get_parameter|ps_get_value|' + 'ps_hyphenate|ps_include_file|ps_lineto|ps_makespotcolor|ps_moveto|ps_new|ps_open_file|ps_open_image|ps_open_image_file|' + 'ps_open_memory_image|ps_place_image|ps_rect|ps_restore|ps_rotate|ps_save|ps_scale|ps_set_border_color|ps_set_border_dash|' + 'ps_set_border_style|ps_set_info|ps_set_parameter|ps_set_text_pos|ps_set_value|ps_setcolor|ps_setdash|ps_setflat|ps_setfont|ps_setgray|' + 'ps_setlinecap|ps_setlinejoin|ps_setlinewidth|ps_setmiterlimit|ps_setoverprintmode|ps_setpolydash|ps_shading|ps_shading_pattern|ps_shfill|' + 'ps_show|ps_show2|ps_show_boxed|ps_show_xy|ps_show_xy2|ps_string_geometry|ps_stringwidth|ps_stroke|ps_symbol|ps_symbol_name|' + 'ps_symbol_width|ps_translate|pspell_add_to_personal|pspell_add_to_session|pspell_check|pspell_clear_session|pspell_config_create|' + 'pspell_config_data_dir|pspell_config_dict_dir|pspell_config_ignore|pspell_config_mode|pspell_config_personal|pspell_config_repl|' + 'pspell_config_runtogether|pspell_config_save_repl|pspell_new|pspell_new_config|pspell_new_personal|pspell_save_wordlist|' + 'pspell_store_replacement|pspell_suggest|putenv|px_close|px_create_fp|px_date2string|px_delete|px_delete_record|px_get_field|px_get_info|' + 'px_get_parameter|px_get_record|px_get_schema|px_get_value|px_insert_record|px_new|px_numfields|px_numrecords|px_open_fp|px_put_record|' + 'px_retrieve_record|px_set_blob_file|px_set_parameter|px_set_tablename|px_set_targetencoding|px_set_value|px_timestamp2string|' + 'px_update_record|qdom_error|qdom_tree|quoted_printable_decode|quoted_printable_encode|quotemeta|rad2deg|radius_acct_open|' + 'radius_add_server|radius_auth_open|radius_close|radius_config|radius_create_request|radius_cvt_addr|radius_cvt_int|radius_cvt_string|' + 'radius_demangle|radius_demangle_mppe_key|radius_get_attr|radius_get_vendor_attr|radius_put_addr|radius_put_attr|radius_put_int|' + 'radius_put_string|radius_put_vendor_addr|radius_put_vendor_attr|radius_put_vendor_int|radius_put_vendor_string|' + 'radius_request_authenticator|radius_send_request|radius_server_secret|radius_strerror|rand|range|rangeexception|rar_wrapper_cache_stats|' + 'rararchive|rarentry|rarexception|rawurldecode|rawurlencode|read_exif_data|readdir|readfile|readgzfile|readline|readline_add_history|' + 'readline_callback_handler_install|readline_callback_handler_remove|readline_callback_read_char|readline_clear_history|' + 'readline_completion_function|readline_info|readline_list_history|readline_on_new_line|readline_read_history|readline_redisplay|' + 'readline_write_history|readlink|realpath|realpath_cache_get|realpath_cache_size|recode|recode_file|recode_string|recursivearrayiterator|' + 'recursivecachingiterator|recursivecallbackfilteriterator|recursivedirectoryiterator|recursivefilteriterator|recursiveiterator|' + 'recursiveiteratoriterator|recursiveregexiterator|recursivetreeiterator|reflection|reflectionclass|reflectionexception|reflectionextension|' + 'reflectionfunction|reflectionfunctionabstract|reflectionmethod|reflectionobject|reflectionparameter|reflectionproperty|reflector|' + 'regexiterator|register_shutdown_function|register_tick_function|rename|rename_function|require|require_once|reset|resetValue|' + 'resourcebundle|restore_error_handler|restore_exception_handler|restore_include_path|return|rewind|rewinddir|rmdir|round|rpm_close|' + 'rpm_get_tag|rpm_is_valid|rpm_open|rpm_version|rrd_create|rrd_error|rrd_fetch|rrd_first|rrd_graph|rrd_info|rrd_last|rrd_lastupdate|' + 'rrd_restore|rrd_tune|rrd_update|rrd_xport|rrdcreator|rrdgraph|rrdupdater|rsort|rtrim|runkit_class_adopt|runkit_class_emancipate|' + 'runkit_constant_add|runkit_constant_redefine|runkit_constant_remove|runkit_function_add|runkit_function_copy|runkit_function_redefine|' + 'runkit_function_remove|runkit_function_rename|runkit_import|runkit_lint|runkit_lint_file|runkit_method_add|runkit_method_copy|' + 'runkit_method_redefine|runkit_method_remove|runkit_method_rename|runkit_return_value_used|runkit_sandbox_output_handler|' + 'runkit_superglobals|runtimeexception|samconnection_commit|samconnection_connect|samconnection_constructor|samconnection_disconnect|' + 'samconnection_errno|samconnection_error|samconnection_isconnected|samconnection_peek|samconnection_peekall|samconnection_receive|' + 'samconnection_remove|samconnection_rollback|samconnection_send|samconnection_setDebug|samconnection_subscribe|samconnection_unsubscribe|' + 'sammessage_body|sammessage_constructor|sammessage_header|sca_createdataobject|sca_getservice|sca_localproxy_createdataobject|' + 'sca_soapproxy_createdataobject|scandir|sdo_das_changesummary_beginlogging|sdo_das_changesummary_endlogging|' + 'sdo_das_changesummary_getchangeddataobjects|sdo_das_changesummary_getchangetype|sdo_das_changesummary_getoldcontainer|' + 'sdo_das_changesummary_getoldvalues|sdo_das_changesummary_islogging|sdo_das_datafactory_addpropertytotype|sdo_das_datafactory_addtype|' + 'sdo_das_datafactory_getdatafactory|sdo_das_dataobject_getchangesummary|sdo_das_relational_applychanges|sdo_das_relational_construct|' + 'sdo_das_relational_createrootdataobject|sdo_das_relational_executepreparedquery|sdo_das_relational_executequery|' + 'sdo_das_setting_getlistindex|sdo_das_setting_getpropertyindex|sdo_das_setting_getpropertyname|sdo_das_setting_getvalue|' + 'sdo_das_setting_isset|sdo_das_xml_addtypes|sdo_das_xml_create|sdo_das_xml_createdataobject|sdo_das_xml_createdocument|' + 'sdo_das_xml_document_getrootdataobject|sdo_das_xml_document_getrootelementname|sdo_das_xml_document_getrootelementuri|' + 'sdo_das_xml_document_setencoding|sdo_das_xml_document_setxmldeclaration|sdo_das_xml_document_setxmlversion|sdo_das_xml_loadfile|' + 'sdo_das_xml_loadstring|sdo_das_xml_savefile|sdo_das_xml_savestring|sdo_datafactory_create|sdo_dataobject_clear|' + 'sdo_dataobject_createdataobject|sdo_dataobject_getcontainer|sdo_dataobject_getsequence|sdo_dataobject_gettypename|' + 'sdo_dataobject_gettypenamespaceuri|sdo_exception_getcause|sdo_list_insert|sdo_model_property_getcontainingtype|' + 'sdo_model_property_getdefault|sdo_model_property_getname|sdo_model_property_gettype|sdo_model_property_iscontainment|' + 'sdo_model_property_ismany|sdo_model_reflectiondataobject_construct|sdo_model_reflectiondataobject_export|' + 'sdo_model_reflectiondataobject_getcontainmentproperty|sdo_model_reflectiondataobject_getinstanceproperties|' + 'sdo_model_reflectiondataobject_gettype|sdo_model_type_getbasetype|sdo_model_type_getname|sdo_model_type_getnamespaceuri|' + 'sdo_model_type_getproperties|sdo_model_type_getproperty|sdo_model_type_isabstracttype|sdo_model_type_isdatatype|sdo_model_type_isinstance|' + 'sdo_model_type_isopentype|sdo_model_type_issequencedtype|sdo_sequence_getproperty|sdo_sequence_insert|sdo_sequence_move|seekableiterator|' + 'sem_acquire|sem_get|sem_release|sem_remove|serializable|serialize|session_cache_expire|session_cache_limiter|session_commit|' + 'session_decode|session_destroy|session_encode|session_get_cookie_params|session_id|session_is_registered|session_module_name|session_name|' + 'session_pgsql_add_error|session_pgsql_get_error|session_pgsql_get_field|session_pgsql_reset|session_pgsql_set_field|session_pgsql_status|' + 'session_regenerate_id|session_register|session_save_path|session_set_cookie_params|session_set_save_handler|session_start|' + 'session_unregister|session_unset|session_write_close|setCounterClass|set_error_handler|set_exception_handler|set_file_buffer|' + 'set_include_path|set_magic_quotes_runtime|set_socket_blocking|set_time_limit|setcookie|setlocale|setproctitle|setrawcookie|' + 'setstaticpropertyvalue|setthreadtitle|settype|sha1|sha1_file|shell_exec|shm_attach|shm_detach|shm_get_var|shm_has_var|shm_put_var|' + 'shm_remove|shm_remove_var|shmop_close|shmop_delete|shmop_open|shmop_read|shmop_size|shmop_write|show_source|shuffle|signeurlpaiement|' + 'similar_text|simplexml_import_dom|simplexml_load_file|simplexml_load_string|simplexmlelement|simplexmliterator|sin|sinh|sizeof|sleep|snmp|' + 'snmp2_get|snmp2_getnext|snmp2_real_walk|snmp2_set|snmp2_walk|snmp3_get|snmp3_getnext|snmp3_real_walk|snmp3_set|snmp3_walk|' + 'snmp_get_quick_print|snmp_get_valueretrieval|snmp_read_mib|snmp_set_enum_print|snmp_set_oid_numeric_print|snmp_set_oid_output_format|' + 'snmp_set_quick_print|snmp_set_valueretrieval|snmpget|snmpgetnext|snmprealwalk|snmpset|snmpwalk|snmpwalkoid|soapclient|soapfault|' + 'soapheader|soapparam|soapserver|soapvar|socket_accept|socket_bind|socket_clear_error|socket_close|socket_connect|socket_create|' + 'socket_create_listen|socket_create_pair|socket_get_option|socket_get_status|socket_getpeername|socket_getsockname|socket_last_error|' + 'socket_listen|socket_read|socket_recv|socket_recvfrom|socket_select|socket_send|socket_sendto|socket_set_block|socket_set_blocking|' + 'socket_set_nonblock|socket_set_option|socket_set_timeout|socket_shutdown|socket_strerror|socket_write|solr_get_version|solrclient|' + 'solrclientexception|solrdocument|solrdocumentfield|solrexception|solrgenericresponse|solrillegalargumentexception|' + 'solrillegaloperationexception|solrinputdocument|solrmodifiableparams|solrobject|solrparams|solrpingresponse|solrquery|solrqueryresponse|' + 'solrresponse|solrupdateresponse|solrutils|sort|soundex|sphinxclient|spl_autoload|spl_autoload_call|spl_autoload_extensions|' + 'spl_autoload_functions|spl_autoload_register|spl_autoload_unregister|spl_classes|spl_object_hash|splbool|spldoublylinkedlist|splenum|' + 'splfileinfo|splfileobject|splfixedarray|splfloat|splheap|splint|split|spliti|splmaxheap|splminheap|splobjectstorage|splobserver|' + 'splpriorityqueue|splqueue|splstack|splstring|splsubject|spltempfileobject|spoofchecker|sprintf|sql_regcase|sqlite3|sqlite3result|' + 'sqlite3stmt|sqlite_array_query|sqlite_busy_timeout|sqlite_changes|sqlite_close|sqlite_column|sqlite_create_aggregate|' + 'sqlite_create_function|sqlite_current|sqlite_error_string|sqlite_escape_string|sqlite_exec|sqlite_factory|sqlite_fetch_all|' + 'sqlite_fetch_array|sqlite_fetch_column_types|sqlite_fetch_object|sqlite_fetch_single|sqlite_fetch_string|sqlite_field_name|' + 'sqlite_has_more|sqlite_has_prev|sqlite_key|sqlite_last_error|sqlite_last_insert_rowid|sqlite_libencoding|sqlite_libversion|sqlite_next|' + 'sqlite_num_fields|sqlite_num_rows|sqlite_open|sqlite_popen|sqlite_prev|sqlite_query|sqlite_rewind|sqlite_seek|sqlite_single_query|' + 'sqlite_udf_decode_binary|sqlite_udf_encode_binary|sqlite_unbuffered_query|sqlite_valid|sqrt|srand|sscanf|ssdeep_fuzzy_compare|' + 'ssdeep_fuzzy_hash|ssdeep_fuzzy_hash_filename|ssh2_auth_hostbased_file|ssh2_auth_none|ssh2_auth_password|ssh2_auth_pubkey_file|' + 'ssh2_connect|ssh2_exec|ssh2_fetch_stream|ssh2_fingerprint|ssh2_methods_negotiated|ssh2_publickey_add|ssh2_publickey_init|' + 'ssh2_publickey_list|ssh2_publickey_remove|ssh2_scp_recv|ssh2_scp_send|ssh2_sftp|ssh2_sftp_lstat|ssh2_sftp_mkdir|ssh2_sftp_readlink|' + 'ssh2_sftp_realpath|ssh2_sftp_rename|ssh2_sftp_rmdir|ssh2_sftp_stat|ssh2_sftp_symlink|ssh2_sftp_unlink|ssh2_shell|ssh2_tunnel|stat|' + 'stats_absolute_deviation|stats_cdf_beta|stats_cdf_binomial|stats_cdf_cauchy|stats_cdf_chisquare|stats_cdf_exponential|stats_cdf_f|' + 'stats_cdf_gamma|stats_cdf_laplace|stats_cdf_logistic|stats_cdf_negative_binomial|stats_cdf_noncentral_chisquare|stats_cdf_noncentral_f|' + 'stats_cdf_poisson|stats_cdf_t|stats_cdf_uniform|stats_cdf_weibull|stats_covariance|stats_den_uniform|stats_dens_beta|stats_dens_cauchy|' + 'stats_dens_chisquare|stats_dens_exponential|stats_dens_f|stats_dens_gamma|stats_dens_laplace|stats_dens_logistic|' + 'stats_dens_negative_binomial|stats_dens_normal|stats_dens_pmf_binomial|stats_dens_pmf_hypergeometric|stats_dens_pmf_poisson|stats_dens_t|' + 'stats_dens_weibull|stats_harmonic_mean|stats_kurtosis|stats_rand_gen_beta|stats_rand_gen_chisquare|stats_rand_gen_exponential|' + 'stats_rand_gen_f|stats_rand_gen_funiform|stats_rand_gen_gamma|stats_rand_gen_ibinomial|stats_rand_gen_ibinomial_negative|' + 'stats_rand_gen_int|stats_rand_gen_ipoisson|stats_rand_gen_iuniform|stats_rand_gen_noncenral_chisquare|stats_rand_gen_noncentral_f|' + 'stats_rand_gen_noncentral_t|stats_rand_gen_normal|stats_rand_gen_t|stats_rand_get_seeds|stats_rand_phrase_to_seeds|stats_rand_ranf|' + 'stats_rand_setall|stats_skew|stats_standard_deviation|stats_stat_binomial_coef|stats_stat_correlation|stats_stat_gennch|' + 'stats_stat_independent_t|stats_stat_innerproduct|stats_stat_noncentral_t|stats_stat_paired_t|stats_stat_percentile|stats_stat_powersum|' + 'stats_variance|stomp|stomp_connect_error|stomp_version|stompexception|stompframe|str_getcsv|str_ireplace|str_pad|str_repeat|str_replace|' + 'str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|stream_bucket_append|stream_bucket_make_writeable|' + 'stream_bucket_new|stream_bucket_prepend|stream_context_create|stream_context_get_default|stream_context_get_options|' + 'stream_context_get_params|stream_context_set_default|stream_context_set_option|stream_context_set_params|stream_copy_to_stream|' + 'stream_encoding|stream_filter_append|stream_filter_prepend|stream_filter_register|stream_filter_remove|stream_get_contents|' + 'stream_get_filters|stream_get_line|stream_get_meta_data|stream_get_transports|stream_get_wrappers|stream_is_local|' + 'stream_notification_callback|stream_register_wrapper|stream_resolve_include_path|stream_select|stream_set_blocking|stream_set_read_buffer|' + 'stream_set_timeout|stream_set_write_buffer|stream_socket_accept|stream_socket_client|stream_socket_enable_crypto|stream_socket_get_name|' + 'stream_socket_pair|stream_socket_recvfrom|stream_socket_sendto|stream_socket_server|stream_socket_shutdown|stream_supports_lock|' + 'stream_wrapper_register|stream_wrapper_restore|stream_wrapper_unregister|streamwrapper|strftime|strip_tags|stripcslashes|stripos|' + 'stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|' + 'strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare|substr_count|substr_replace|svm|svmmodel|svn_add|' + 'svn_auth_get_parameter|svn_auth_set_parameter|svn_blame|svn_cat|svn_checkout|svn_cleanup|svn_client_version|svn_commit|svn_delete|' + 'svn_diff|svn_export|svn_fs_abort_txn|svn_fs_apply_text|svn_fs_begin_txn2|svn_fs_change_node_prop|svn_fs_check_path|' + 'svn_fs_contents_changed|svn_fs_copy|svn_fs_delete|svn_fs_dir_entries|svn_fs_file_contents|svn_fs_file_length|svn_fs_is_dir|svn_fs_is_file|' + 'svn_fs_make_dir|svn_fs_make_file|svn_fs_node_created_rev|svn_fs_node_prop|svn_fs_props_changed|svn_fs_revision_prop|svn_fs_revision_root|' + 'svn_fs_txn_root|svn_fs_youngest_rev|svn_import|svn_log|svn_ls|svn_mkdir|svn_repos_create|svn_repos_fs|svn_repos_fs_begin_txn_for_commit|' + 'svn_repos_fs_commit_txn|svn_repos_hotcopy|svn_repos_open|svn_repos_recover|svn_revert|svn_status|svn_update|swf_actiongeturl|' + 'swf_actiongotoframe|swf_actiongotolabel|swf_actionnextframe|swf_actionplay|swf_actionprevframe|swf_actionsettarget|swf_actionstop|' + 'swf_actiontogglequality|swf_actionwaitforframe|swf_addbuttonrecord|swf_addcolor|swf_closefile|swf_definebitmap|swf_definefont|' + 'swf_defineline|swf_definepoly|swf_definerect|swf_definetext|swf_endbutton|swf_enddoaction|swf_endshape|swf_endsymbol|swf_fontsize|' + 'swf_fontslant|swf_fonttracking|swf_getbitmapinfo|swf_getfontinfo|swf_getframe|swf_labelframe|swf_lookat|swf_modifyobject|swf_mulcolor|' + 'swf_nextid|swf_oncondition|swf_openfile|swf_ortho|swf_ortho2|swf_perspective|swf_placeobject|swf_polarview|swf_popmatrix|swf_posround|' + 'swf_pushmatrix|swf_removeobject|swf_rotate|swf_scale|swf_setfont|swf_setframe|swf_shapearc|swf_shapecurveto|swf_shapecurveto3|' + 'swf_shapefillbitmapclip|swf_shapefillbitmaptile|swf_shapefilloff|swf_shapefillsolid|swf_shapelinesolid|swf_shapelineto|swf_shapemoveto|' + 'swf_showframe|swf_startbutton|swf_startdoaction|swf_startshape|swf_startsymbol|swf_textwidth|swf_translate|swf_viewport|swfaction|' + 'swfbitmap|swfbutton|swfdisplayitem|swffill|swffont|swffontchar|swfgradient|swfmorph|swfmovie|swfprebuiltclip|swfshape|swfsound|' + 'swfsoundinstance|swfsprite|swftext|swftextfield|swfvideostream|swish_construct|swish_getmetalist|swish_getpropertylist|swish_prepare|' + 'swish_query|swishresult_getmetalist|swishresult_stem|swishresults_getparsedwords|swishresults_getremovedstopwords|swishresults_nextresult|' + 'swishresults_seekresult|swishsearch_execute|swishsearch_resetlimit|swishsearch_setlimit|swishsearch_setphrasedelimiter|' + 'swishsearch_setsort|swishsearch_setstructure|sybase_affected_rows|sybase_close|sybase_connect|sybase_data_seek|' + 'sybase_deadlock_retry_count|sybase_fetch_array|sybase_fetch_assoc|sybase_fetch_field|sybase_fetch_object|sybase_fetch_row|' + 'sybase_field_seek|sybase_free_result|sybase_get_last_message|sybase_min_client_severity|sybase_min_error_severity|' + 'sybase_min_message_severity|sybase_min_server_severity|sybase_num_fields|sybase_num_rows|sybase_pconnect|sybase_query|sybase_result|' + 'sybase_select_db|sybase_set_message_handler|sybase_unbuffered_query|symlink|sys_get_temp_dir|sys_getloadavg|syslog|system|tag|tan|tanh|' + 'tcpwrap_check|tempnam|textdomain|tidy|tidy_access_count|tidy_config_count|tidy_diagnose|tidy_error_count|tidy_get_error_buffer|' + 'tidy_get_output|tidy_load_config|tidy_reset_config|tidy_save_config|tidy_set_encoding|tidy_setopt|tidy_warning_count|tidynode|time|' + 'time_nanosleep|time_sleep_until|timezone_abbreviations_list|timezone_identifiers_list|timezone_location_get|timezone_name_from_abbr|' + 'timezone_name_get|timezone_offset_get|timezone_open|timezone_transitions_get|timezone_version_get|tmpfile|token_get_all|token_name|' + 'tokyotyrant|tokyotyrantquery|tokyotyranttable|tostring|tostring|touch|trait_exists|transliterator|traversable|trigger_error|trim|uasort|ucfirst|' + 'ucwords|udm_add_search_limit|udm_alloc_agent|udm_alloc_agent_array|udm_api_version|udm_cat_list|udm_cat_path|udm_check_charset|' + 'udm_check_stored|udm_clear_search_limits|udm_close_stored|udm_crc32|udm_errno|udm_error|udm_find|udm_free_agent|udm_free_ispell_data|' + 'udm_free_res|udm_get_doc_count|udm_get_res_field|udm_get_res_param|udm_hash32|udm_load_ispell_data|udm_open_stored|udm_set_agent_param|' + 'uksort|umask|underflowexception|unexpectedvalueexception|uniqid|unixtojd|unlink|unpack|unregister_tick_function|unserialize|unset|' + 'urldecode|urlencode|use_soap_error_handler|user_error|usleep|usort|utf8_decode|utf8_encode|v8js|v8jsexception|var_dump|var_export|variant|' + 'variant_abs|variant_add|variant_and|variant_cast|variant_cat|variant_cmp|variant_date_from_timestamp|variant_date_to_timestamp|' + 'variant_div|variant_eqv|variant_fix|variant_get_type|variant_idiv|variant_imp|variant_int|variant_mod|variant_mul|variant_neg|variant_not|' + 'variant_or|variant_pow|variant_round|variant_set|variant_set_type|variant_sub|variant_xor|version_compare|vfprintf|virtual|' + 'vpopmail_add_alias_domain|vpopmail_add_alias_domain_ex|vpopmail_add_domain|vpopmail_add_domain_ex|vpopmail_add_user|vpopmail_alias_add|' + 'vpopmail_alias_del|vpopmail_alias_del_domain|vpopmail_alias_get|vpopmail_alias_get_all|vpopmail_auth_user|vpopmail_del_domain|' + 'vpopmail_del_domain_ex|vpopmail_del_user|vpopmail_error|vpopmail_passwd|vpopmail_set_user_quota|vprintf|vsprintf|w32api_deftype|' + 'w32api_init_dtype|w32api_invoke_function|w32api_register_function|w32api_set_call_method|wddx_add_vars|wddx_deserialize|wddx_packet_end|' + 'wddx_packet_start|wddx_serialize_value|wddx_serialize_vars|win32_continue_service|win32_create_service|win32_delete_service|' + 'win32_get_last_control_message|win32_pause_service|win32_ps_list_procs|win32_ps_stat_mem|win32_ps_stat_proc|win32_query_service_status|' + 'win32_set_service_status|win32_start_service|win32_start_service_ctrl_dispatcher|win32_stop_service|wincache_fcache_fileinfo|' + 'wincache_fcache_meminfo|wincache_lock|wincache_ocache_fileinfo|wincache_ocache_meminfo|wincache_refresh_if_changed|' + 'wincache_rplist_fileinfo|wincache_rplist_meminfo|wincache_scache_info|wincache_scache_meminfo|wincache_ucache_add|wincache_ucache_cas|' + 'wincache_ucache_clear|wincache_ucache_dec|wincache_ucache_delete|wincache_ucache_exists|wincache_ucache_get|wincache_ucache_inc|' + 'wincache_ucache_info|wincache_ucache_meminfo|wincache_ucache_set|wincache_unlock|wordwrap|xattr_get|xattr_list|xattr_remove|xattr_set|' + 'xattr_supported|xdiff_file_bdiff|xdiff_file_bdiff_size|xdiff_file_bpatch|xdiff_file_diff|xdiff_file_diff_binary|xdiff_file_merge3|' + 'xdiff_file_patch|xdiff_file_patch_binary|xdiff_file_rabdiff|xdiff_string_bdiff|xdiff_string_bdiff_size|xdiff_string_bpatch|' + 'xdiff_string_diff|xdiff_string_diff_binary|xdiff_string_merge3|xdiff_string_patch|xdiff_string_patch_binary|xdiff_string_rabdiff|' + 'xhprof_disable|xhprof_enable|xhprof_sample_disable|xhprof_sample_enable|xml_error_string|xml_get_current_byte_index|' + 'xml_get_current_column_number|xml_get_current_line_number|xml_get_error_code|xml_parse|xml_parse_into_struct|xml_parser_create|' + 'xml_parser_create_ns|xml_parser_free|xml_parser_get_option|xml_parser_set_option|xml_set_character_data_handler|xml_set_default_handler|' + 'xml_set_element_handler|xml_set_end_namespace_decl_handler|xml_set_external_entity_ref_handler|xml_set_notation_decl_handler|' + 'xml_set_object|xml_set_processing_instruction_handler|xml_set_start_namespace_decl_handler|xml_set_unparsed_entity_decl_handler|xmlreader|' + 'xmlrpc_decode|xmlrpc_decode_request|xmlrpc_encode|xmlrpc_encode_request|xmlrpc_get_type|xmlrpc_is_fault|xmlrpc_parse_method_descriptions|' + 'xmlrpc_server_add_introspection_data|xmlrpc_server_call_method|xmlrpc_server_create|xmlrpc_server_destroy|' + 'xmlrpc_server_register_introspection_callback|xmlrpc_server_register_method|xmlrpc_set_type|xmlwriter_end_attribute|xmlwriter_end_cdata|' + 'xmlwriter_end_comment|xmlwriter_end_document|xmlwriter_end_dtd|xmlwriter_end_dtd_attlist|xmlwriter_end_dtd_element|' + 'xmlwriter_end_dtd_entity|xmlwriter_end_element|xmlwriter_end_pi|xmlwriter_flush|xmlwriter_full_end_element|xmlwriter_open_memory|' + 'xmlwriter_open_uri|xmlwriter_output_memory|xmlwriter_set_indent|xmlwriter_set_indent_string|xmlwriter_start_attribute|' + 'xmlwriter_start_attribute_ns|xmlwriter_start_cdata|xmlwriter_start_comment|xmlwriter_start_document|xmlwriter_start_dtd|' + 'xmlwriter_start_dtd_attlist|xmlwriter_start_dtd_element|xmlwriter_start_dtd_entity|xmlwriter_start_element|xmlwriter_start_element_ns|' + 'xmlwriter_start_pi|xmlwriter_text|xmlwriter_write_attribute|xmlwriter_write_attribute_ns|xmlwriter_write_cdata|xmlwriter_write_comment|' + 'xmlwriter_write_dtd|xmlwriter_write_dtd_attlist|xmlwriter_write_dtd_element|xmlwriter_write_dtd_entity|xmlwriter_write_element|' + 'xmlwriter_write_element_ns|xmlwriter_write_pi|xmlwriter_write_raw|xpath_eval|xpath_eval_expression|xpath_new_context|xpath_register_ns|' + 'xpath_register_ns_auto|xptr_eval|xptr_new_context|xslt_backend_info|xslt_backend_name|xslt_backend_version|xslt_create|xslt_errno|' + 'xslt_error|xslt_free|xslt_getopt|xslt_process|xslt_set_base|xslt_set_encoding|xslt_set_error_handler|xslt_set_log|xslt_set_object|' + 'xslt_set_sax_handler|xslt_set_sax_handlers|xslt_set_scheme_handler|xslt_set_scheme_handlers|xslt_setopt|xsltprocessor|yaml_emit|' + 'yaml_emit_file|yaml_parse|yaml_parse_file|yaml_parse_url|yaz_addinfo|yaz_ccl_conf|yaz_ccl_parse|yaz_close|yaz_connect|yaz_database|' + 'yaz_element|yaz_errno|yaz_error|yaz_es|yaz_es_result|yaz_get_option|yaz_hits|yaz_itemorder|yaz_present|yaz_range|yaz_record|yaz_scan|' + 'yaz_scan_result|yaz_schema|yaz_search|yaz_set_option|yaz_sort|yaz_syntax|yaz_wait|yp_all|yp_cat|yp_err_string|yp_errno|yp_first|' + 'yp_get_default_domain|yp_master|yp_match|yp_next|yp_order|zend_logo_guid|zend_thread_id|zend_version|zip_close|zip_entry_close|' + 'zip_entry_compressedsize|zip_entry_compressionmethod|zip_entry_filesize|zip_entry_name|zip_entry_open|zip_entry_read|zip_open|zip_read|' + 'ziparchive|ziparchive_addemptydir|ziparchive_addfile|ziparchive_addfromstring|ziparchive_close|ziparchive_deleteindex|' + 'ziparchive_deletename|ziparchive_extractto|ziparchive_getarchivecomment|ziparchive_getcommentindex|ziparchive_getcommentname|' + 'ziparchive_getfromindex|ziparchive_getfromname|ziparchive_getnameindex|ziparchive_getstatusstring|ziparchive_getstream|' + 'ziparchive_locatename|ziparchive_open|ziparchive_renameindex|ziparchive_renamename|ziparchive_setCommentName|ziparchive_setarchivecomment|' + 'ziparchive_setcommentindex|ziparchive_statindex|ziparchive_statname|ziparchive_unchangeall|ziparchive_unchangearchive|' + 'ziparchive_unchangeindex|ziparchive_unchangename|zlib_get_coding_type').split('|') ); var keywords = lang.arrayToMap( ('abstract|and|array|as|break|case|catch|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|' + 'endswitch|endwhile|extends|final|for|foreach|function|global|goto|if|implements|interface|instanceof|namespace|new|or|private|protected|' + 'public|static|switch|throw|trait|try|use|var|while|xor').split('|') ); var languageConstructs = lang.arrayToMap( ('die|echo|empty|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset').split('|') ); var builtinConstants = lang.arrayToMap( ('true|TRUE|false|FALSE|null|NULL|__CLASS__|__DIR__|__FILE__|__LINE__|__METHOD__|__FUNCTION__|__NAMESPACE__').split('|') ); var builtinVariables = lang.arrayToMap( ('$GLOBALS|$_SERVER|$_GET|$_POST|$_FILES|$_REQUEST|$_SESSION|$_ENV|$_COOKIE|$php_errormsg|$HTTP_RAW_POST_DATA|' + '$http_response_header|$argc|$argv').split('|') ); var builtinFunctionsDeprecated = lang.arrayToMap( ('key_exists|cairo_matrix_create_scale|cairo_matrix_create_translate|call_user_method|call_user_method_array|com_addref|com_get|' + 'com_invoke|com_isenum|com_load|com_release|com_set|connection_timeout|cubrid_load_from_glo|cubrid_new_glo|cubrid_save_to_glo|' + 'cubrid_send_glo|define_syslog_variables|dl|ereg|ereg_replace|eregi|eregi_replace|hw_documentattributes|hw_documentbodytag|' + 'hw_documentsize|hw_outputdocument|imagedashedline|maxdb_bind_param|maxdb_bind_result|maxdb_client_encoding|maxdb_close_long_data|' + 'maxdb_execute|maxdb_fetch|maxdb_get_metadata|maxdb_param_count|maxdb_send_long_data|mcrypt_ecb|mcrypt_generic_end|mime_content_type|' + 'mysql_createdb|mysql_dbname|mysql_db_query|mysql_drop_db|mysql_dropdb|mysql_escape_string|mysql_fieldflags|mysql_fieldflags|' + 'mysql_fieldname|mysql_fieldtable|mysql_fieldtype|mysql_freeresult|mysql_listdbs|mysql_list_fields|mysql_listfields|mysql_list_tables|' + 'mysql_listtables|mysql_numfields|mysql_numrows|mysql_selectdb|mysql_tablename|mysqli_bind_param|mysqli_bind_result|' + 'mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_execute|' + 'mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' + 'mysqli_send_long_data|mysqli_send_query|mysqli_slave_query|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|' + 'ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|' + 'ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|' + 'ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|' + 'ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|' + 'ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|PDF_add_annotation|PDF_add_bookmark|' + 'PDF_add_launchlink|PDF_add_locallink|PDF_add_note|PDF_add_outline|PDF_add_pdflink|PDF_add_weblink|PDF_attach_file|PDF_begin_page|' + 'PDF_begin_template|PDF_close_pdi|PDF_close|PDF_findfont|PDF_get_font|PDF_get_fontname|PDF_get_fontsize|PDF_get_image_height|' + 'PDF_get_image_width|PDF_get_majorversion|PDF_get_minorversion|PDF_get_pdi_parameter|PDF_get_pdi_value|PDF_open_ccitt|PDF_open_file|' + 'PDF_open_gif|PDF_open_image_file|PDF_open_image|PDF_open_jpeg|PDF_open_pdi|PDF_open_tiff|PDF_place_image|PDF_place_pdi_page|' + 'PDF_set_border_color|PDF_set_border_dash|PDF_set_border_style|PDF_set_char_spacing|PDF_set_duration|PDF_set_horiz_scaling|' + 'PDF_set_info_author|PDF_set_info_creator|PDF_set_info_keywords|PDF_set_info_subject|PDF_set_info_title|PDF_set_leading|' + 'PDF_set_text_matrix|PDF_set_text_rendering|PDF_set_text_rise|PDF_set_word_spacing|PDF_setgray_fill|PDF_setgray_stroke|PDF_setgray|' + 'PDF_setpolydash|PDF_setrgbcolor_fill|PDF_setrgbcolor_stroke|PDF_setrgbcolor|PDF_show_boxed|php_check_syntax|px_set_tablename|' + 'px_set_targetencoding|runkit_sandbox_output_handler|session_is_registered|session_register|session_unregister' + 'set_magic_quotes_runtime|magic_quotes_runtime|set_socket_blocking|socket_set_blocking|set_socket_timeout|socket_set_timeout|split|spliti|' + 'sql_regcase').split('|') ); var keywordsDeprecated = lang.arrayToMap( ('cfunction|old_function').split('|') ); var futureReserved = lang.arrayToMap([]); this.$rules = { "start" : [ { token : "comment", regex : /(?:#|\/\/)(?:[^?]|\?[^>])*/ }, docComment.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/][gimy]*\\s*(?=[).,;]|$)" }, { token : "string", // " string start regex : '"', next : "qqstring" }, { token : "string", // ' string start regex : "'", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language", // constants regex : "\\b(?:DEFAULT_INCLUDE_PATH|E_(?:ALL|CO(?:MPILE_(?:ERROR|WARNING)|RE_(?:ERROR|WARNING))|" + "ERROR|NOTICE|PARSE|STRICT|USER_(?:ERROR|NOTICE|WARNING)|WARNING)|P(?:EAR_(?:EXTENSION_DIR|INSTALL_DIR)|" + "HP_(?:BINDIR|CONFIG_FILE_(?:PATH|SCAN_DIR)|DATADIR|E(?:OL|XTENSION_DIR)|INT_(?:MAX|SIZE)|" + "L(?:IBDIR|OCALSTATEDIR)|O(?:S|UTPUT_HANDLER_(?:CONT|END|START))|PREFIX|S(?:API|HLIB_SUFFIX|YSCONFDIR)|" + "VERSION))|__COMPILER_HALT_OFFSET__)\\b" }, { token : ["keyword", "text", "support.class"], regex : "\\b(new)(\\s+)(\\w+)" }, { token : ["support.class", "keyword.operator"], regex : "\\b(\\w+)(::)" }, { token : "constant.language", // constants regex : "\\b(?:A(?:B(?:DAY_(?:1|2|3|4|5|6|7)|MON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9))|LT_DIGITS|M_STR|" + "SSERT_(?:ACTIVE|BAIL|CALLBACK|QUIET_EVAL|WARNING))|C(?:ASE_(?:LOWER|UPPER)|HAR_MAX|" + "O(?:DESET|NNECTION_(?:ABORTED|NORMAL|TIMEOUT)|UNT_(?:NORMAL|RECURSIVE))|" + "R(?:EDITS_(?:ALL|DOCS|FULLPAGE|G(?:ENERAL|ROUP)|MODULES|QA|SAPI)|NCYSTR|" + "YPT_(?:BLOWFISH|EXT_DES|MD5|S(?:ALT_LENGTH|TD_DES)))|URRENCY_SYMBOL)|D(?:AY_(?:1|2|3|4|5|6|7)|" + "ECIMAL_POINT|IRECTORY_SEPARATOR|_(?:FMT|T_FMT))|E(?:NT_(?:COMPAT|NOQUOTES|QUOTES)|RA(?:_(?:D_(?:FMT|T_FMT)|" + "T_FMT|YEAR)|)|XTR_(?:IF_EXISTS|OVERWRITE|PREFIX_(?:ALL|I(?:F_EXISTS|NVALID)|SAME)|SKIP))|FRAC_DIGITS|GROUPING|" + "HTML_(?:ENTITIES|SPECIALCHARS)|IN(?:FO_(?:ALL|C(?:ONFIGURATION|REDITS)|ENVIRONMENT|GENERAL|LICENSE|MODULES|VARIABLES)|" + "I_(?:ALL|PERDIR|SYSTEM|USER)|T_(?:CURR_SYMBOL|FRAC_DIGITS))|L(?:C_(?:ALL|C(?:OLLATE|TYPE)|M(?:ESSAGES|ONETARY)|NUMERIC|TIME)|" + "O(?:CK_(?:EX|NB|SH|UN)|G_(?:A(?:LERT|UTH(?:PRIV|))|C(?:ONS|R(?:IT|ON))|D(?:AEMON|EBUG)|E(?:MERG|RR)|INFO|KERN|" + "L(?:OCAL(?:0|1|2|3|4|5|6|7)|PR)|MAIL|N(?:DELAY|EWS|O(?:TICE|WAIT))|ODELAY|P(?:ERROR|ID)|SYSLOG|U(?:SER|UCP)|WARNING)))|" + "M(?:ON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9|DECIMAL_POINT|GROUPING|THOUSANDS_SEP)|_(?:1_PI|2_(?:PI|SQRTPI)|E|L(?:N(?:10|2)|" + "OG(?:10E|2E))|PI(?:_(?:2|4)|)|SQRT(?:1_2|2)))|N(?:EGATIVE_SIGN|O(?:EXPR|STR)|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "P(?:ATH(?:INFO_(?:BASENAME|DIRNAME|EXTENSION)|_SEPARATOR)|M_STR|OSITIVE_SIGN|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "RADIXCHAR|S(?:EEK_(?:CUR|END|SET)|ORT_(?:ASC|DESC|NUMERIC|REGULAR|STRING)|TR_PAD_(?:BOTH|LEFT|RIGHT))|" + "T(?:HOUS(?:ANDS_SEP|EP)|_FMT(?:_AMPM|))|YES(?:EXPR|STR)|STD(?:IN|OUT|ERR))\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else if(value.match(/^(\$[a-zA-Z_\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*|self|parent)$/)) return "variable"; return "identifier"; }, regex : /[a-zA-Z_$\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*/ }, { onMatch : function(value, currentSate, state) { value = value.substr(3); if (value[0] == "'" || value[0] == '"') value = value.slice(1, -1); state.unshift(this.next, value); return "markup.list"; }, regex : /<<<(?:\w+|'\w+'|"\w+")$/, next: "heredoc" }, { token : "keyword.operator", regex : "::|!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|!=|!==|<=|>=|=>|<<=|>>=|>>>=|<>|<|>|=|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "heredoc" : [ { onMatch : function(value, currentSate, stack) { if (stack[1] != value) return "string"; stack.shift(); stack.shift(); return "markup.list"; }, regex : "^\\w+(?=;?$)", next: "start" }, { token: "string", regex : ".*" } ], "comment" : [ { token : "comment", regex : "\\*\\/", next : "start" }, { defaultToken : "comment" } ], "qqstring" : [ { token : "constant.language.escape", regex : '\\\\(?:[nrtvef\\\\"$]|[0-7]{1,3}|x[0-9A-Fa-f]{1,2})' }, { token : "variable", regex : /\$[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/ }, { token : "variable", regex : /\$\{[^"\}]+\}?/ // this is wrong but ok for now }, {token : "string", regex : '"', next : "start"}, {defaultToken : "string"} ], "qstring" : [ {token : "constant.language.escape", regex : /\\['\\]/}, {token : "string", regex : "'", next : "start"}, {defaultToken : "string"} ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(PhpLangHighlightRules, TextHighlightRules); var PhpHighlightRules = function() { HtmlHighlightRules.call(this); var startRules = [ { token : "support.php_tag", // php open tag regex : "<\\?(?:php|=)?", push : "php-start" } ]; var endRules = [ { token : "support.php_tag", // php close tag regex : "\\?>", next : "pop" } ]; for (var key in this.$rules) this.$rules[key].unshift.apply(this.$rules[key], startRules); this.embedRules(PhpLangHighlightRules, "php-", endRules, ["start"]); this.normalizeRules(); }; oop.inherits(PhpHighlightRules, HtmlHighlightRules); exports.PhpHighlightRules = PhpHighlightRules; exports.PhpLangHighlightRules = PhpLangHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/php_completions",["require","exports","module"], function(require, exports, module) { "use strict"; var functionMap = { "abs": [ "int abs(int number)", "Return the absolute value of the number" ], "acos": [ "float acos(float number)", "Return the arc cosine of the number in radians" ], "acosh": [ "float acosh(float number)", "Returns the inverse hyperbolic cosine of the number, i.e. the value whose hyperbolic cosine is number" ], "addGlob": [ "bool addGlob(string pattern[,int flags [, array options]])", "Add files matching the glob pattern. See php's glob for the pattern syntax." ], "addPattern": [ "bool addPattern(string pattern[, string path [, array options]])", "Add files matching the pcre pattern. See php's pcre for the pattern syntax." ], "addcslashes": [ "string addcslashes(string str, string charlist)", "Escapes all chars mentioned in charlist with backslash. It creates octal representations if asked to backslash characters with 8th bit set or with ASCII<32 (except '\\n', '\\r', '\\t' etc...)" ], "addslashes": [ "string addslashes(string str)", "Escapes single quote, double quotes and backslash characters in a string with backslashes" ], "apache_child_terminate": [ "bool apache_child_terminate(void)", "Terminate apache process after this request" ], "apache_get_modules": [ "array apache_get_modules(void)", "Get a list of loaded Apache modules" ], "apache_get_version": [ "string apache_get_version(void)", "Fetch Apache version" ], "apache_getenv": [ "bool apache_getenv(string variable [, bool walk_to_top])", "Get an Apache subprocess_env variable" ], "apache_lookup_uri": [ "object apache_lookup_uri(string URI)", "Perform a partial request of the given URI to obtain information about it" ], "apache_note": [ "string apache_note(string note_name [, string note_value])", "Get and set Apache request notes" ], "apache_request_auth_name": [ "string apache_request_auth_name()", "" ], "apache_request_auth_type": [ "string apache_request_auth_type()", "" ], "apache_request_discard_request_body": [ "long apache_request_discard_request_body()", "" ], "apache_request_err_headers_out": [ "array apache_request_err_headers_out([{string name|array list} [, string value [, bool replace = false]]])", "* fetch all headers that go out in case of an error or a subrequest" ], "apache_request_headers": [ "array apache_request_headers(void)", "Fetch all HTTP request headers" ], "apache_request_headers_in": [ "array apache_request_headers_in()", "* fetch all incoming request headers" ], "apache_request_headers_out": [ "array apache_request_headers_out([{string name|array list} [, string value [, bool replace = false]]])", "* fetch all outgoing request headers" ], "apache_request_is_initial_req": [ "bool apache_request_is_initial_req()", "" ], "apache_request_log_error": [ "boolean apache_request_log_error(string message, [long facility])", "" ], "apache_request_meets_conditions": [ "long apache_request_meets_conditions()", "" ], "apache_request_remote_host": [ "int apache_request_remote_host([int type])", "" ], "apache_request_run": [ "long apache_request_run()", "This is a wrapper for ap_sub_run_req and ap_destory_sub_req. It takes sub_request, runs it, destroys it, and returns it's status." ], "apache_request_satisfies": [ "long apache_request_satisfies()", "" ], "apache_request_server_port": [ "int apache_request_server_port()", "" ], "apache_request_set_etag": [ "void apache_request_set_etag()", "" ], "apache_request_set_last_modified": [ "void apache_request_set_last_modified()", "" ], "apache_request_some_auth_required": [ "bool apache_request_some_auth_required()", "" ], "apache_request_sub_req_lookup_file": [ "object apache_request_sub_req_lookup_file(string file)", "Returns sub-request for the specified file. You would need to run it yourself with run()." ], "apache_request_sub_req_lookup_uri": [ "object apache_request_sub_req_lookup_uri(string uri)", "Returns sub-request for the specified uri. You would need to run it yourself with run()" ], "apache_request_sub_req_method_uri": [ "object apache_request_sub_req_method_uri(string method, string uri)", "Returns sub-request for the specified file. You would need to run it yourself with run()." ], "apache_request_update_mtime": [ "long apache_request_update_mtime([int dependency_mtime])", "" ], "apache_reset_timeout": [ "bool apache_reset_timeout(void)", "Reset the Apache write timer" ], "apache_response_headers": [ "array apache_response_headers(void)", "Fetch all HTTP response headers" ], "apache_setenv": [ "bool apache_setenv(string variable, string value [, bool walk_to_top])", "Set an Apache subprocess_env variable" ], "array_change_key_case": [ "array array_change_key_case(array input [, int case=CASE_LOWER])", "Retuns an array with all string keys lowercased [or uppercased]" ], "array_chunk": [ "array array_chunk(array input, int size [, bool preserve_keys])", "Split array into chunks" ], "array_combine": [ "array array_combine(array keys, array values)", "Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values" ], "array_count_values": [ "array array_count_values(array input)", "Return the value as key and the frequency of that value in input as value" ], "array_diff": [ "array array_diff(array arr1, array arr2 [, array ...])", "Returns the entries of arr1 that have values which are not present in any of the others arguments." ], "array_diff_assoc": [ "array array_diff_assoc(array arr1, array arr2 [, array ...])", "Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal" ], "array_diff_key": [ "array array_diff_key(array arr1, array arr2 [, array ...])", "Returns the entries of arr1 that have keys which are not present in any of the others arguments. This function is like array_diff() but works on the keys instead of the values. The associativity is preserved." ], "array_diff_uassoc": [ "array array_diff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func)", "Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Elements are compared by user supplied function." ], "array_diff_ukey": [ "array array_diff_ukey(array arr1, array arr2 [, array ...], callback key_comp_func)", "Returns the entries of arr1 that have keys which are not present in any of the others arguments. User supplied function is used for comparing the keys. This function is like array_udiff() but works on the keys instead of the values. The associativity is preserved." ], "array_fill": [ "array array_fill(int start_key, int num, mixed val)", "Create an array containing num elements starting with index start_key each initialized to val" ], "array_fill_keys": [ "array array_fill_keys(array keys, mixed val)", "Create an array using the elements of the first parameter as keys each initialized to val" ], "array_filter": [ "array array_filter(array input [, mixed callback])", "Filters elements from the array via the callback." ], "array_flip": [ "array array_flip(array input)", "Return array with key <-> value flipped" ], "array_intersect": [ "array array_intersect(array arr1, array arr2 [, array ...])", "Returns the entries of arr1 that have values which are present in all the other arguments" ], "array_intersect_assoc": [ "array array_intersect_assoc(array arr1, array arr2 [, array ...])", "Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check" ], "array_intersect_key": [ "array array_intersect_key(array arr1, array arr2 [, array ...])", "Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). Equivalent of array_intersect_assoc() but does not do compare of the data." ], "array_intersect_uassoc": [ "array array_intersect_uassoc(array arr1, array arr2 [, array ...], callback key_compare_func)", "Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check and they are compared by using an user-supplied callback." ], "array_intersect_ukey": [ "array array_intersect_ukey(array arr1, array arr2 [, array ...], callback key_compare_func)", "Returns the entries of arr1 that have keys which are present in all the other arguments. Kind of equivalent to array_diff(array_keys($arr1), array_keys($arr2)[,array_keys(...)]). The comparison of the keys is performed by a user supplied function. Equivalent of array_intersect_uassoc() but does not do compare of the data." ], "array_key_exists": [ "bool array_key_exists(mixed key, array search)", "Checks if the given key or index exists in the array" ], "array_keys": [ "array array_keys(array input [, mixed search_value[, bool strict]])", "Return just the keys from the input array, optionally only for the specified search_value" ], "array_map": [ "array array_map(mixed callback, array input1 [, array input2 ,...])", "Applies the callback to the elements in given arrays." ], "array_merge": [ "array array_merge(array arr1, array arr2 [, array ...])", "Merges elements from passed arrays into one array" ], "array_merge_recursive": [ "array array_merge_recursive(array arr1, array arr2 [, array ...])", "Recursively merges elements from passed arrays into one array" ], "array_multisort": [ "bool array_multisort(array ar1 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING]] [, array ar2 [, SORT_ASC|SORT_DESC [, SORT_REGULAR|SORT_NUMERIC|SORT_STRING]], ...])", "Sort multiple arrays at once similar to how ORDER BY clause works in SQL" ], "array_pad": [ "array array_pad(array input, int pad_size, mixed pad_value)", "Returns a copy of input array padded with pad_value to size pad_size" ], "array_pop": [ "mixed array_pop(array stack)", "Pops an element off the end of the array" ], "array_product": [ "mixed array_product(array input)", "Returns the product of the array entries" ], "array_push": [ "int array_push(array stack, mixed var [, mixed ...])", "Pushes elements onto the end of the array" ], "array_rand": [ "mixed array_rand(array input [, int num_req])", "Return key/keys for random entry/entries in the array" ], "array_reduce": [ "mixed array_reduce(array input, mixed callback [, mixed initial])", "Iteratively reduce the array to a single value via the callback." ], "array_replace": [ "array array_replace(array arr1, array arr2 [, array ...])", "Replaces elements from passed arrays into one array" ], "array_replace_recursive": [ "array array_replace_recursive(array arr1, array arr2 [, array ...])", "Recursively replaces elements from passed arrays into one array" ], "array_reverse": [ "array array_reverse(array input [, bool preserve keys])", "Return input as a new array with the order of the entries reversed" ], "array_search": [ "mixed array_search(mixed needle, array haystack [, bool strict])", "Searches the array for a given value and returns the corresponding key if successful" ], "array_shift": [ "mixed array_shift(array stack)", "Pops an element off the beginning of the array" ], "array_slice": [ "array array_slice(array input, int offset [, int length [, bool preserve_keys]])", "Returns elements specified by offset and length" ], "array_splice": [ "array array_splice(array input, int offset [, int length [, array replacement]])", "Removes the elements designated by offset and length and replace them with supplied array" ], "array_sum": [ "mixed array_sum(array input)", "Returns the sum of the array entries" ], "array_udiff": [ "array array_udiff(array arr1, array arr2 [, array ...], callback data_comp_func)", "Returns the entries of arr1 that have values which are not present in any of the others arguments. Elements are compared by user supplied function." ], "array_udiff_assoc": [ "array array_udiff_assoc(array arr1, array arr2 [, array ...], callback key_comp_func)", "Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys are compared by user supplied function." ], "array_udiff_uassoc": [ "array array_udiff_uassoc(array arr1, array arr2 [, array ...], callback data_comp_func, callback key_comp_func)", "Returns the entries of arr1 that have values which are not present in any of the others arguments but do additional checks whether the keys are equal. Keys and elements are compared by user supplied functions." ], "array_uintersect": [ "array array_uintersect(array arr1, array arr2 [, array ...], callback data_compare_func)", "Returns the entries of arr1 that have values which are present in all the other arguments. Data is compared by using an user-supplied callback." ], "array_uintersect_assoc": [ "array array_uintersect_assoc(array arr1, array arr2 [, array ...], callback data_compare_func)", "Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Data is compared by using an user-supplied callback." ], "array_uintersect_uassoc": [ "array array_uintersect_uassoc(array arr1, array arr2 [, array ...], callback data_compare_func, callback key_compare_func)", "Returns the entries of arr1 that have values which are present in all the other arguments. Keys are used to do more restrictive check. Both data and keys are compared by using user-supplied callbacks." ], "array_unique": [ "array array_unique(array input [, int sort_flags])", "Removes duplicate values from array" ], "array_unshift": [ "int array_unshift(array stack, mixed var [, mixed ...])", "Pushes elements onto the beginning of the array" ], "array_values": [ "array array_values(array input)", "Return just the values from the input array" ], "array_walk": [ "bool array_walk(array input, string funcname [, mixed userdata])", "Apply a user function to every member of an array" ], "array_walk_recursive": [ "bool array_walk_recursive(array input, string funcname [, mixed userdata])", "Apply a user function recursively to every member of an array" ], "arsort": [ "bool arsort(array &array_arg [, int sort_flags])", "Sort an array in reverse order and maintain index association" ], "asin": [ "float asin(float number)", "Returns the arc sine of the number in radians" ], "asinh": [ "float asinh(float number)", "Returns the inverse hyperbolic sine of the number, i.e. the value whose hyperbolic sine is number" ], "asort": [ "bool asort(array &array_arg [, int sort_flags])", "Sort an array and maintain index association" ], "assert": [ "int assert(string|bool assertion)", "Checks if assertion is false" ], "assert_options": [ "mixed assert_options(int what [, mixed value])", "Set/get the various assert flags" ], "atan": [ "float atan(float number)", "Returns the arc tangent of the number in radians" ], "atan2": [ "float atan2(float y, float x)", "Returns the arc tangent of y/x, with the resulting quadrant determined by the signs of y and x" ], "atanh": [ "float atanh(float number)", "Returns the inverse hyperbolic tangent of the number, i.e. the value whose hyperbolic tangent is number" ], "attachIterator": [ "void attachIterator(Iterator iterator[, mixed info])", "Attach a new iterator" ], "base64_decode": [ "string base64_decode(string str[, bool strict])", "Decodes string using MIME base64 algorithm" ], "base64_encode": [ "string base64_encode(string str)", "Encodes string using MIME base64 algorithm" ], "base_convert": [ "string base_convert(string number, int frombase, int tobase)", "Converts a number in a string from any base <= 36 to any base <= 36" ], "basename": [ "string basename(string path [, string suffix])", "Returns the filename component of the path" ], "bcadd": [ "string bcadd(string left_operand, string right_operand [, int scale])", "Returns the sum of two arbitrary precision numbers" ], "bccomp": [ "int bccomp(string left_operand, string right_operand [, int scale])", "Compares two arbitrary precision numbers" ], "bcdiv": [ "string bcdiv(string left_operand, string right_operand [, int scale])", "Returns the quotient of two arbitrary precision numbers (division)" ], "bcmod": [ "string bcmod(string left_operand, string right_operand)", "Returns the modulus of the two arbitrary precision operands" ], "bcmul": [ "string bcmul(string left_operand, string right_operand [, int scale])", "Returns the multiplication of two arbitrary precision numbers" ], "bcpow": [ "string bcpow(string x, string y [, int scale])", "Returns the value of an arbitrary precision number raised to the power of another" ], "bcpowmod": [ "string bcpowmod(string x, string y, string mod [, int scale])", "Returns the value of an arbitrary precision number raised to the power of another reduced by a modulous" ], "bcscale": [ "bool bcscale(int scale)", "Sets default scale parameter for all bc math functions" ], "bcsqrt": [ "string bcsqrt(string operand [, int scale])", "Returns the square root of an arbitray precision number" ], "bcsub": [ "string bcsub(string left_operand, string right_operand [, int scale])", "Returns the difference between two arbitrary precision numbers" ], "bin2hex": [ "string bin2hex(string data)", "Converts the binary representation of data to hex" ], "bind_textdomain_codeset": [ "string bind_textdomain_codeset (string domain, string codeset)", "Specify the character encoding in which the messages from the DOMAIN message catalog will be returned." ], "bindec": [ "int bindec(string binary_number)", "Returns the decimal equivalent of the binary number" ], "bindtextdomain": [ "string bindtextdomain(string domain_name, string dir)", "Bind to the text domain domain_name, looking for translations in dir. Returns the current domain" ], "birdstep_autocommit": [ "bool birdstep_autocommit(int index)", "" ], "birdstep_close": [ "bool birdstep_close(int id)", "" ], "birdstep_commit": [ "bool birdstep_commit(int index)", "" ], "birdstep_connect": [ "int birdstep_connect(string server, string user, string pass)", "" ], "birdstep_exec": [ "int birdstep_exec(int index, string exec_str)", "" ], "birdstep_fetch": [ "bool birdstep_fetch(int index)", "" ], "birdstep_fieldname": [ "string birdstep_fieldname(int index, int col)", "" ], "birdstep_fieldnum": [ "int birdstep_fieldnum(int index)", "" ], "birdstep_freeresult": [ "bool birdstep_freeresult(int index)", "" ], "birdstep_off_autocommit": [ "bool birdstep_off_autocommit(int index)", "" ], "birdstep_result": [ "mixed birdstep_result(int index, mixed col)", "" ], "birdstep_rollback": [ "bool birdstep_rollback(int index)", "" ], "bzcompress": [ "string bzcompress(string source [, int blocksize100k [, int workfactor]])", "Compresses a string into BZip2 encoded data" ], "bzdecompress": [ "string bzdecompress(string source [, int small])", "Decompresses BZip2 compressed data" ], "bzerrno": [ "int bzerrno(resource bz)", "Returns the error number" ], "bzerror": [ "array bzerror(resource bz)", "Returns the error number and error string in an associative array" ], "bzerrstr": [ "string bzerrstr(resource bz)", "Returns the error string" ], "bzopen": [ "resource bzopen(string|int file|fp, string mode)", "Opens a new BZip2 stream" ], "bzread": [ "string bzread(resource bz[, int length])", "Reads up to length bytes from a BZip2 stream, or 1024 bytes if length is not specified" ], "cal_days_in_month": [ "int cal_days_in_month(int calendar, int month, int year)", "Returns the number of days in a month for a given year and calendar" ], "cal_from_jd": [ "array cal_from_jd(int jd, int calendar)", "Converts from Julian Day Count to a supported calendar and return extended information" ], "cal_info": [ "array cal_info([int calendar])", "Returns information about a particular calendar" ], "cal_to_jd": [ "int cal_to_jd(int calendar, int month, int day, int year)", "Converts from a supported calendar to Julian Day Count" ], "call_user_func": [ "mixed call_user_func(mixed function_name [, mixed parmeter] [, mixed ...])", "Call a user function which is the first parameter" ], "call_user_func_array": [ "mixed call_user_func_array(string function_name, array parameters)", "Call a user function which is the first parameter with the arguments contained in array" ], "call_user_method": [ "mixed call_user_method(string method_name, mixed object [, mixed parameter] [, mixed ...])", "Call a user method on a specific object or class" ], "call_user_method_array": [ "mixed call_user_method_array(string method_name, mixed object, array params)", "Call a user method on a specific object or class using a parameter array" ], "ceil": [ "float ceil(float number)", "Returns the next highest integer value of the number" ], "chdir": [ "bool chdir(string directory)", "Change the current directory" ], "checkdate": [ "bool checkdate(int month, int day, int year)", "Returns true(1) if it is a valid date in gregorian calendar" ], "chgrp": [ "bool chgrp(string filename, mixed group)", "Change file group" ], "chmod": [ "bool chmod(string filename, int mode)", "Change file mode" ], "chown": [ "bool chown (string filename, mixed user)", "Change file owner" ], "chr": [ "string chr(int ascii)", "Converts ASCII code to a character" ], "chroot": [ "bool chroot(string directory)", "Change root directory" ], "chunk_split": [ "string chunk_split(string str [, int chunklen [, string ending]])", "Returns split line" ], "class_alias": [ "bool class_alias(string user_class_name , string alias_name [, bool autoload])", "Creates an alias for user defined class" ], "class_exists": [ "bool class_exists(string classname [, bool autoload])", "Checks if the class exists" ], "class_implements": [ "array class_implements(mixed what [, bool autoload ])", "Return all classes and interfaces implemented by SPL" ], "class_parents": [ "array class_parents(object instance [, boolean autoload = true])", "Return an array containing the names of all parent classes" ], "clearstatcache": [ "void clearstatcache([bool clear_realpath_cache[, string filename]])", "Clear file stat cache" ], "closedir": [ "void closedir([resource dir_handle])", "Close directory connection identified by the dir_handle" ], "closelog": [ "bool closelog(void)", "Close connection to system logger" ], "collator_asort": [ "bool collator_asort( Collator $coll, array(string) $arr )", "* Sort array using specified collator, maintaining index association." ], "collator_compare": [ "int collator_compare( Collator $coll, string $str1, string $str2 )", "* Compare two strings." ], "collator_create": [ "Collator collator_create( string $locale )", "* Create collator." ], "collator_get_attribute": [ "int collator_get_attribute( Collator $coll, int $attr )", "* Get collation attribute value." ], "collator_get_error_code": [ "int collator_get_error_code( Collator $coll )", "* Get collator's last error code." ], "collator_get_error_message": [ "string collator_get_error_message( Collator $coll )", "* Get text description for collator's last error code." ], "collator_get_locale": [ "string collator_get_locale( Collator $coll, int $type )", "* Gets the locale name of the collator." ], "collator_get_sort_key": [ "bool collator_get_sort_key( Collator $coll, string $str )", "* Get a sort key for a string from a Collator. }}}" ], "collator_get_strength": [ "int collator_get_strength(Collator coll)", "* Returns the current collation strength." ], "collator_set_attribute": [ "bool collator_set_attribute( Collator $coll, int $attr, int $val )", "* Set collation attribute." ], "collator_set_strength": [ "bool collator_set_strength(Collator coll, int strength)", "* Set the collation strength." ], "collator_sort": [ "bool collator_sort( Collator $coll, array(string) $arr [, int $sort_flags] )", "* Sort array using specified collator." ], "collator_sort_with_sort_keys": [ "bool collator_sort_with_sort_keys( Collator $coll, array(string) $arr )", "* Equivalent to standard PHP sort using Collator. * Uses ICU ucol_getSortKey for performance." ], "com_create_guid": [ "string com_create_guid()", "Generate a globally unique identifier (GUID)" ], "com_event_sink": [ "bool com_event_sink(object comobject, object sinkobject [, mixed sinkinterface])", "Connect events from a COM object to a PHP object" ], "com_get_active_object": [ "object com_get_active_object(string progid [, int code_page ])", "Returns a handle to an already running instance of a COM object" ], "com_load_typelib": [ "bool com_load_typelib(string typelib_name [, int case_insensitive])", "Loads a Typelibrary and registers its constants" ], "com_message_pump": [ "bool com_message_pump([int timeoutms])", "Process COM messages, sleeping for up to timeoutms milliseconds" ], "com_print_typeinfo": [ "bool com_print_typeinfo(object comobject | string typelib, string dispinterface, bool wantsink)", "Print out a PHP class definition for a dispatchable interface" ], "compact": [ "array compact(mixed var_names [, mixed ...])", "Creates a hash containing variables and their values" ], "compose_locale": [ "static string compose_locale($array)", "* Creates a locale by combining the parts of locale-ID passed * }}}" ], "confirm_extname_compiled": [ "string confirm_extname_compiled(string arg)", "Return a string to confirm that the module is compiled in" ], "connection_aborted": [ "int connection_aborted(void)", "Returns true if client disconnected" ], "connection_status": [ "int connection_status(void)", "Returns the connection status bitfield" ], "constant": [ "mixed constant(string const_name)", "Given the name of a constant this function will return the constant's associated value" ], "convert_cyr_string": [ "string convert_cyr_string(string str, string from, string to)", "Convert from one Cyrillic character set to another" ], "convert_uudecode": [ "string convert_uudecode(string data)", "decode a uuencoded string" ], "convert_uuencode": [ "string convert_uuencode(string data)", "uuencode a string" ], "copy": [ "bool copy(string source_file, string destination_file [, resource context])", "Copy a file" ], "cos": [ "float cos(float number)", "Returns the cosine of the number in radians" ], "cosh": [ "float cosh(float number)", "Returns the hyperbolic cosine of the number, defined as (exp(number) + exp(-number))/2" ], "count": [ "int count(mixed var [, int mode])", "Count the number of elements in a variable (usually an array)" ], "count_chars": [ "mixed count_chars(string input [, int mode])", "Returns info about what characters are used in input" ], "crc32": [ "string crc32(string str)", "Calculate the crc32 polynomial of a string" ], "create_function": [ "string create_function(string args, string code)", "Creates an anonymous function, and returns its name (funny, eh?)" ], "crypt": [ "string crypt(string str [, string salt])", "Hash a string" ], "ctype_alnum": [ "bool ctype_alnum(mixed c)", "Checks for alphanumeric character(s)" ], "ctype_alpha": [ "bool ctype_alpha(mixed c)", "Checks for alphabetic character(s)" ], "ctype_cntrl": [ "bool ctype_cntrl(mixed c)", "Checks for control character(s)" ], "ctype_digit": [ "bool ctype_digit(mixed c)", "Checks for numeric character(s)" ], "ctype_graph": [ "bool ctype_graph(mixed c)", "Checks for any printable character(s) except space" ], "ctype_lower": [ "bool ctype_lower(mixed c)", "Checks for lowercase character(s)" ], "ctype_print": [ "bool ctype_print(mixed c)", "Checks for printable character(s)" ], "ctype_punct": [ "bool ctype_punct(mixed c)", "Checks for any printable character which is not whitespace or an alphanumeric character" ], "ctype_space": [ "bool ctype_space(mixed c)", "Checks for whitespace character(s)" ], "ctype_upper": [ "bool ctype_upper(mixed c)", "Checks for uppercase character(s)" ], "ctype_xdigit": [ "bool ctype_xdigit(mixed c)", "Checks for character(s) representing a hexadecimal digit" ], "curl_close": [ "void curl_close(resource ch)", "Close a cURL session" ], "curl_copy_handle": [ "resource curl_copy_handle(resource ch)", "Copy a cURL handle along with all of it's preferences" ], "curl_errno": [ "int curl_errno(resource ch)", "Return an integer containing the last error number" ], "curl_error": [ "string curl_error(resource ch)", "Return a string contain the last error for the current session" ], "curl_exec": [ "bool curl_exec(resource ch)", "Perform a cURL session" ], "curl_getinfo": [ "mixed curl_getinfo(resource ch [, int option])", "Get information regarding a specific transfer" ], "curl_init": [ "resource curl_init([string url])", "Initialize a cURL session" ], "curl_multi_add_handle": [ "int curl_multi_add_handle(resource mh, resource ch)", "Add a normal cURL handle to a cURL multi handle" ], "curl_multi_close": [ "void curl_multi_close(resource mh)", "Close a set of cURL handles" ], "curl_multi_exec": [ "int curl_multi_exec(resource mh, int &still_running)", "Run the sub-connections of the current cURL handle" ], "curl_multi_getcontent": [ "string curl_multi_getcontent(resource ch)", "Return the content of a cURL handle if CURLOPT_RETURNTRANSFER is set" ], "curl_multi_info_read": [ "array curl_multi_info_read(resource mh [, long msgs_in_queue])", "Get information about the current transfers" ], "curl_multi_init": [ "resource curl_multi_init(void)", "Returns a new cURL multi handle" ], "curl_multi_remove_handle": [ "int curl_multi_remove_handle(resource mh, resource ch)", "Remove a multi handle from a set of cURL handles" ], "curl_multi_select": [ "int curl_multi_select(resource mh[, double timeout])", "Get all the sockets associated with the cURL extension, which can then be \"selected\"" ], "curl_setopt": [ "bool curl_setopt(resource ch, int option, mixed value)", "Set an option for a cURL transfer" ], "curl_setopt_array": [ "bool curl_setopt_array(resource ch, array options)", "Set an array of option for a cURL transfer" ], "curl_version": [ "array curl_version([int version])", "Return cURL version information." ], "current": [ "mixed current(array array_arg)", "Return the element currently pointed to by the internal array pointer" ], "date": [ "string date(string format [, long timestamp])", "Format a local date/time" ], "date_add": [ "DateTime date_add(DateTime object, DateInterval interval)", "Adds an interval to the current date in object." ], "date_create": [ "DateTime date_create([string time[, DateTimeZone object]])", "Returns new DateTime object" ], "date_create_from_format": [ "DateTime date_create_from_format(string format, string time[, DateTimeZone object])", "Returns new DateTime object formatted according to the specified format" ], "date_date_set": [ "DateTime date_date_set(DateTime object, long year, long month, long day)", "Sets the date." ], "date_default_timezone_get": [ "string date_default_timezone_get()", "Gets the default timezone used by all date/time functions in a script" ], "date_default_timezone_set": [ "bool date_default_timezone_set(string timezone_identifier)", "Sets the default timezone used by all date/time functions in a script" ], "date_diff": [ "DateInterval date_diff(DateTime object [, bool absolute])", "Returns the difference between two DateTime objects." ], "date_format": [ "string date_format(DateTime object, string format)", "Returns date formatted according to given format" ], "date_get_last_errors": [ "array date_get_last_errors()", "Returns the warnings and errors found while parsing a date/time string." ], "date_interval_create_from_date_string": [ "DateInterval date_interval_create_from_date_string(string time)", "Uses the normal date parsers and sets up a DateInterval from the relative parts of the parsed string" ], "date_interval_format": [ "string date_interval_format(DateInterval object, string format)", "Formats the interval." ], "date_isodate_set": [ "DateTime date_isodate_set(DateTime object, long year, long week[, long day])", "Sets the ISO date." ], "date_modify": [ "DateTime date_modify(DateTime object, string modify)", "Alters the timestamp." ], "date_offset_get": [ "long date_offset_get(DateTime object)", "Returns the DST offset." ], "date_parse": [ "array date_parse(string date)", "Returns associative array with detailed info about given date" ], "date_parse_from_format": [ "array date_parse_from_format(string format, string date)", "Returns associative array with detailed info about given date" ], "date_sub": [ "DateTime date_sub(DateTime object, DateInterval interval)", "Subtracts an interval to the current date in object." ], "date_sun_info": [ "array date_sun_info(long time, float latitude, float longitude)", "Returns an array with information about sun set/rise and twilight begin/end" ], "date_sunrise": [ "mixed date_sunrise(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]])", "Returns time of sunrise for a given day and location" ], "date_sunset": [ "mixed date_sunset(mixed time [, int format [, float latitude [, float longitude [, float zenith [, float gmt_offset]]]]])", "Returns time of sunset for a given day and location" ], "date_time_set": [ "DateTime date_time_set(DateTime object, long hour, long minute[, long second])", "Sets the time." ], "date_timestamp_get": [ "long date_timestamp_get(DateTime object)", "Gets the Unix timestamp." ], "date_timestamp_set": [ "DateTime date_timestamp_set(DateTime object, long unixTimestamp)", "Sets the date and time based on an Unix timestamp." ], "date_timezone_get": [ "DateTimeZone date_timezone_get(DateTime object)", "Return new DateTimeZone object relative to give DateTime" ], "date_timezone_set": [ "DateTime date_timezone_set(DateTime object, DateTimeZone object)", "Sets the timezone for the DateTime object." ], "datefmt_create": [ "IntlDateFormatter datefmt_create(string $locale, long date_type, long time_type[, string $timezone_str, long $calendar, string $pattern] )", "* Create formatter." ], "datefmt_format": [ "string datefmt_format( [mixed]int $args or array $args )", "* Format the time value as a string. }}}" ], "datefmt_get_calendar": [ "string datefmt_get_calendar( IntlDateFormatter $mf )", "* Get formatter calendar." ], "datefmt_get_datetype": [ "string datefmt_get_datetype( IntlDateFormatter $mf )", "* Get formatter datetype." ], "datefmt_get_error_code": [ "int datefmt_get_error_code( IntlDateFormatter $nf )", "* Get formatter's last error code." ], "datefmt_get_error_message": [ "string datefmt_get_error_message( IntlDateFormatter $coll )", "* Get text description for formatter's last error code." ], "datefmt_get_locale": [ "string datefmt_get_locale(IntlDateFormatter $mf)", "* Get formatter locale." ], "datefmt_get_pattern": [ "string datefmt_get_pattern( IntlDateFormatter $mf )", "* Get formatter pattern." ], "datefmt_get_timetype": [ "string datefmt_get_timetype( IntlDateFormatter $mf )", "* Get formatter timetype." ], "datefmt_get_timezone_id": [ "string datefmt_get_timezone_id( IntlDateFormatter $mf )", "* Get formatter timezone_id." ], "datefmt_isLenient": [ "string datefmt_isLenient(IntlDateFormatter $mf)", "* Get formatter locale." ], "datefmt_localtime": [ "integer datefmt_localtime( IntlDateFormatter $fmt, string $text_to_parse[, int $parse_pos ])", "* Parse the string $value to a localtime array }}}" ], "datefmt_parse": [ "integer datefmt_parse( IntlDateFormatter $fmt, string $text_to_parse [, int $parse_pos] )", "* Parse the string $value starting at parse_pos to a Unix timestamp -int }}}" ], "datefmt_setLenient": [ "string datefmt_setLenient(IntlDateFormatter $mf)", "* Set formatter lenient." ], "datefmt_set_calendar": [ "bool datefmt_set_calendar( IntlDateFormatter $mf, int $calendar )", "* Set formatter calendar." ], "datefmt_set_pattern": [ "bool datefmt_set_pattern( IntlDateFormatter $mf, string $pattern )", "* Set formatter pattern." ], "datefmt_set_timezone_id": [ "boolean datefmt_set_timezone_id( IntlDateFormatter $mf,$timezone_id)", "* Set formatter timezone_id." ], "dba_close": [ "void dba_close(resource handle)", "Closes database" ], "dba_delete": [ "bool dba_delete(string key, resource handle)", "Deletes the entry associated with key If inifile: remove all other key lines" ], "dba_exists": [ "bool dba_exists(string key, resource handle)", "Checks, if the specified key exists" ], "dba_fetch": [ "string dba_fetch(string key, [int skip ,] resource handle)", "Fetches the data associated with key" ], "dba_firstkey": [ "string dba_firstkey(resource handle)", "Resets the internal key pointer and returns the first key" ], "dba_handlers": [ "array dba_handlers([bool full_info])", "List configured database handlers" ], "dba_insert": [ "bool dba_insert(string key, string value, resource handle)", "If not inifile: Insert value as key, return false, if key exists already If inifile: Add vakue as key (next instance of key)" ], "dba_key_split": [ "array|false dba_key_split(string key)", "Splits an inifile key into an array of the form array(0=>group,1=>value_name) but returns false if input is false or null" ], "dba_list": [ "array dba_list()", "List opened databases" ], "dba_nextkey": [ "string dba_nextkey(resource handle)", "Returns the next key" ], "dba_open": [ "resource dba_open(string path, string mode [, string handlername, string ...])", "Opens path using the specified handler in mode" ], "dba_optimize": [ "bool dba_optimize(resource handle)", "Optimizes (e.g. clean up, vacuum) database" ], "dba_popen": [ "resource dba_popen(string path, string mode [, string handlername, string ...])", "Opens path using the specified handler in mode persistently" ], "dba_replace": [ "bool dba_replace(string key, string value, resource handle)", "Inserts value as key, replaces key, if key exists already If inifile: remove all other key lines" ], "dba_sync": [ "bool dba_sync(resource handle)", "Synchronizes database" ], "dcgettext": [ "string dcgettext(string domain_name, string msgid, long category)", "Return the translation of msgid for domain_name and category, or msgid unaltered if a translation does not exist" ], "dcngettext": [ "string dcngettext (string domain, string msgid1, string msgid2, int n, int category)", "Plural version of dcgettext()" ], "debug_backtrace": [ "array debug_backtrace([bool provide_object])", "Return backtrace as array" ], "debug_print_backtrace": [ "void debug_print_backtrace(void) */", "ZEND_FUNCTION(debug_print_backtrace) { zend_execute_data *ptr, *skip; int lineno; char *function_name; char *filename; char *class_name = NULL; char *call_type; char *include_filename = NULL; zval *arg_array = NULL; int indent = 0; if (zend_parse_parameters_none() == FAILURE) { return; } ptr = EG(current_execute_data);", "PHP_FUNCTION(dom_document_relaxNG_validate_file) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_relaxNG_validate_file" ], "dom_document_relaxNG_validate_xml": [ "boolean dom_document_relaxNG_validate_xml(string source); */", "PHP_FUNCTION(dom_document_relaxNG_validate_xml) { _dom_document_relaxNG_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_relaxNG_validate_xml" ], "dom_document_rename_node": [ "DOMNode dom_document_rename_node(node n, string namespaceURI, string qualifiedName);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Document3-renameNode Since: DOM Level 3" ], "dom_document_save": [ "int dom_document_save(string file);", "Convenience method to save to file" ], "dom_document_save_html": [ "string dom_document_save_html();", "Convenience method to output as html" ], "dom_document_save_html_file": [ "int dom_document_save_html_file(string file);", "Convenience method to save to file as html" ], "dom_document_savexml": [ "string dom_document_savexml([node n]);", "URL: http://www.w3.org/TR/DOM-Level-3-LS/load-save.html#LS-DocumentLS-saveXML Since: DOM Level 3" ], "dom_document_schema_validate": [ "boolean dom_document_schema_validate(string source); */", "PHP_FUNCTION(dom_document_schema_validate_xml) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_STRING); } /* }}} end dom_document_schema_validate" ], "dom_document_schema_validate_file": [ "boolean dom_document_schema_validate_file(string filename); */", "PHP_FUNCTION(dom_document_schema_validate_file) { _dom_document_schema_validate(INTERNAL_FUNCTION_PARAM_PASSTHRU, DOM_LOAD_FILE); } /* }}} end dom_document_schema_validate_file" ], "dom_document_validate": [ "boolean dom_document_validate();", "Since: DOM extended" ], "dom_document_xinclude": [ "int dom_document_xinclude([int options])", "Substitutues xincludes in a DomDocument" ], "dom_domconfiguration_can_set_parameter": [ "boolean dom_domconfiguration_can_set_parameter(string name, domuserdata value);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMConfiguration-canSetParameter Since:" ], "dom_domconfiguration_get_parameter": [ "domdomuserdata dom_domconfiguration_get_parameter(string name);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMConfiguration-getParameter Since:" ], "dom_domconfiguration_set_parameter": [ "dom_void dom_domconfiguration_set_parameter(string name, domuserdata value);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMConfiguration-property Since:" ], "dom_domerrorhandler_handle_error": [ "dom_boolean dom_domerrorhandler_handle_error(domerror error);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-ERRORS-DOMErrorHandler-handleError Since:" ], "dom_domimplementation_create_document": [ "DOMDocument dom_domimplementation_create_document(string namespaceURI, string qualifiedName, DOMDocumentType doctype);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Level-2-Core-DOM-createDocument Since: DOM Level 2" ], "dom_domimplementation_create_document_type": [ "DOMDocumentType dom_domimplementation_create_document_type(string qualifiedName, string publicId, string systemId);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Level-2-Core-DOM-createDocType Since: DOM Level 2" ], "dom_domimplementation_get_feature": [ "DOMNode dom_domimplementation_get_feature(string feature, string version);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementation3-getFeature Since: DOM Level 3" ], "dom_domimplementation_has_feature": [ "boolean dom_domimplementation_has_feature(string feature, string version);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-5CED94D7 Since:" ], "dom_domimplementationlist_item": [ "domdomimplementation dom_domimplementationlist_item(int index);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMImplementationList-item Since:" ], "dom_domimplementationsource_get_domimplementation": [ "domdomimplementation dom_domimplementationsource_get_domimplementation(string features);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-getDOMImpl Since:" ], "dom_domimplementationsource_get_domimplementations": [ "domimplementationlist dom_domimplementationsource_get_domimplementations(string features);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-getDOMImpls Since:" ], "dom_domstringlist_item": [ "domstring dom_domstringlist_item(int index);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#DOMStringList-item Since:" ], "dom_element_get_attribute": [ "string dom_element_get_attribute(string name);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-666EE0F9 Since:" ], "dom_element_get_attribute_node": [ "DOMAttr dom_element_get_attribute_node(string name);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-217A91B8 Since:" ], "dom_element_get_attribute_node_ns": [ "DOMAttr dom_element_get_attribute_node_ns(string namespaceURI, string localName);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElGetAtNodeNS Since: DOM Level 2" ], "dom_element_get_attribute_ns": [ "string dom_element_get_attribute_ns(string namespaceURI, string localName);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElGetAttrNS Since: DOM Level 2" ], "dom_element_get_elements_by_tag_name": [ "DOMNodeList dom_element_get_elements_by_tag_name(string name);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1938918D Since:" ], "dom_element_get_elements_by_tag_name_ns": [ "DOMNodeList dom_element_get_elements_by_tag_name_ns(string namespaceURI, string localName);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-A6C90942 Since: DOM Level 2" ], "dom_element_has_attribute": [ "boolean dom_element_has_attribute(string name);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElHasAttr Since: DOM Level 2" ], "dom_element_has_attribute_ns": [ "boolean dom_element_has_attribute_ns(string namespaceURI, string localName);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElHasAttrNS Since: DOM Level 2" ], "dom_element_remove_attribute": [ "void dom_element_remove_attribute(string name);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-6D6AC0F9 Since:" ], "dom_element_remove_attribute_node": [ "DOMAttr dom_element_remove_attribute_node(DOMAttr oldAttr);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D589198 Since:" ], "dom_element_remove_attribute_ns": [ "void dom_element_remove_attribute_ns(string namespaceURI, string localName);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElRemAtNS Since: DOM Level 2" ], "dom_element_set_attribute": [ "void dom_element_set_attribute(string name, string value);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-F68F082 Since:" ], "dom_element_set_attribute_node": [ "DOMAttr dom_element_set_attribute_node(DOMAttr newAttr);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-887236154 Since:" ], "dom_element_set_attribute_node_ns": [ "DOMAttr dom_element_set_attribute_node_ns(DOMAttr newAttr);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetAtNodeNS Since: DOM Level 2" ], "dom_element_set_attribute_ns": [ "void dom_element_set_attribute_ns(string namespaceURI, string qualifiedName, string value);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetAttrNS Since: DOM Level 2" ], "dom_element_set_id_attribute": [ "void dom_element_set_id_attribute(string name, boolean isId);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttr Since: DOM Level 3" ], "dom_element_set_id_attribute_node": [ "void dom_element_set_id_attribute_node(attr idAttr, boolean isId);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttrNode Since: DOM Level 3" ], "dom_element_set_id_attribute_ns": [ "void dom_element_set_id_attribute_ns(string namespaceURI, string localName, boolean isId);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-ElSetIdAttrNS Since: DOM Level 3" ], "dom_import_simplexml": [ "somNode dom_import_simplexml(sxeobject node)", "Get a simplexml_element object from dom to allow for processing" ], "dom_namednodemap_get_named_item": [ "DOMNode dom_namednodemap_get_named_item(string name);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1074577549 Since:" ], "dom_namednodemap_get_named_item_ns": [ "DOMNode dom_namednodemap_get_named_item_ns(string namespaceURI, string localName);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-getNamedItemNS Since: DOM Level 2" ], "dom_namednodemap_item": [ "DOMNode dom_namednodemap_item(int index);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-349467F9 Since:" ], "dom_namednodemap_remove_named_item": [ "DOMNode dom_namednodemap_remove_named_item(string name);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-D58B193 Since:" ], "dom_namednodemap_remove_named_item_ns": [ "DOMNode dom_namednodemap_remove_named_item_ns(string namespaceURI, string localName);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-removeNamedItemNS Since: DOM Level 2" ], "dom_namednodemap_set_named_item": [ "DOMNode dom_namednodemap_set_named_item(DOMNode arg);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1025163788 Since:" ], "dom_namednodemap_set_named_item_ns": [ "DOMNode dom_namednodemap_set_named_item_ns(DOMNode arg);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-setNamedItemNS Since: DOM Level 2" ], "dom_namelist_get_name": [ "string dom_namelist_get_name(int index);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#NameList-getName Since:" ], "dom_namelist_get_namespace_uri": [ "string dom_namelist_get_namespace_uri(int index);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#NameList-getNamespaceURI Since:" ], "dom_node_append_child": [ "DomNode dom_node_append_child(DomNode newChild);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-184E7107 Since:" ], "dom_node_clone_node": [ "DomNode dom_node_clone_node(boolean deep);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-3A0ED0A4 Since:" ], "dom_node_compare_document_position": [ "short dom_node_compare_document_position(DomNode other);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-compareDocumentPosition Since: DOM Level 3" ], "dom_node_get_feature": [ "DomNode dom_node_get_feature(string feature, string version);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-getFeature Since: DOM Level 3" ], "dom_node_get_user_data": [ "mixed dom_node_get_user_data(string key);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-getUserData Since: DOM Level 3" ], "dom_node_has_attributes": [ "boolean dom_node_has_attributes();", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-NodeHasAttrs Since: DOM Level 2" ], "dom_node_has_child_nodes": [ "boolean dom_node_has_child_nodes();", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-810594187 Since:" ], "dom_node_insert_before": [ "domnode dom_node_insert_before(DomNode newChild, DomNode refChild);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-952280727 Since:" ], "dom_node_is_default_namespace": [ "boolean dom_node_is_default_namespace(string namespaceURI);", "URL: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-isDefaultNamespace Since: DOM Level 3" ], "dom_node_is_equal_node": [ "boolean dom_node_is_equal_node(DomNode arg);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-isEqualNode Since: DOM Level 3" ], "dom_node_is_same_node": [ "boolean dom_node_is_same_node(DomNode other);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-isSameNode Since: DOM Level 3" ], "dom_node_is_supported": [ "boolean dom_node_is_supported(string feature, string version);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Level-2-Core-Node-supports Since: DOM Level 2" ], "dom_node_lookup_namespace_uri": [ "string dom_node_lookup_namespace_uri(string prefix);", "URL: http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-lookupNamespaceURI Since: DOM Level 3" ], "dom_node_lookup_prefix": [ "string dom_node_lookup_prefix(string namespaceURI);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-lookupNamespacePrefix Since: DOM Level 3" ], "dom_node_normalize": [ "void dom_node_normalize();", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-normalize Since:" ], "dom_node_remove_child": [ "DomNode dom_node_remove_child(DomNode oldChild);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-1734834066 Since:" ], "dom_node_replace_child": [ "DomNode dom_node_replace_child(DomNode newChild, DomNode oldChild);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-785887307 Since:" ], "dom_node_set_user_data": [ "mixed dom_node_set_user_data(string key, mixed data, userdatahandler handler);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#Node3-setUserData Since: DOM Level 3" ], "dom_nodelist_item": [ "DOMNode dom_nodelist_item(int index);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-844377136 Since:" ], "dom_string_extend_find_offset16": [ "int dom_string_extend_find_offset16(int offset32);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#i18n-methods-StringExtend-findOffset16 Since:" ], "dom_string_extend_find_offset32": [ "int dom_string_extend_find_offset32(int offset16);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#i18n-methods-StringExtend-findOffset32 Since:" ], "dom_text_is_whitespace_in_element_content": [ "boolean dom_text_is_whitespace_in_element_content();", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Text3-isWhitespaceInElementContent Since: DOM Level 3" ], "dom_text_replace_whole_text": [ "DOMText dom_text_replace_whole_text(string content);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-Text3-replaceWholeText Since: DOM Level 3" ], "dom_text_split_text": [ "DOMText dom_text_split_text(int offset);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#core-ID-38853C1D Since:" ], "dom_userdatahandler_handle": [ "dom_void dom_userdatahandler_handle(short operation, string key, domobject data, node src, node dst);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html#ID-handleUserDataEvent Since:" ], "dom_xpath_evaluate": [ "mixed dom_xpath_evaluate(string expr [,DOMNode context]); */", "PHP_FUNCTION(dom_xpath_evaluate) { php_xpath_eval(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_DOM_XPATH_EVALUATE); } /* }}} end dom_xpath_evaluate" ], "dom_xpath_query": [ "DOMNodeList dom_xpath_query(string expr [,DOMNode context]); */", "PHP_FUNCTION(dom_xpath_query) { php_xpath_eval(INTERNAL_FUNCTION_PARAM_PASSTHRU, PHP_DOM_XPATH_QUERY); } /* }}} end dom_xpath_query" ], "dom_xpath_register_ns": [ "boolean dom_xpath_register_ns(string prefix, string uri); */", "PHP_FUNCTION(dom_xpath_register_ns) { zval *id; xmlXPathContextPtr ctxp; int prefix_len, ns_uri_len; dom_xpath_object *intern; unsigned char *prefix, *ns_uri; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Oss\", &id, dom_xpath_class_entry, &prefix, &prefix_len, &ns_uri, &ns_uri_len) == FAILURE) { return; } intern = (dom_xpath_object *)zend_object_store_get_object(id TSRMLS_CC); ctxp = (xmlXPathContextPtr) intern->ptr; if (ctxp == NULL) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid XPath Context\"); RETURN_FALSE; } if (xmlXPathRegisterNs(ctxp, prefix, ns_uri) != 0) { RETURN_FALSE } RETURN_TRUE; } /* }}}" ], "dom_xpath_register_php_functions": [ "void dom_xpath_register_php_functions() */", "PHP_FUNCTION(dom_xpath_register_php_functions) { zval *id; dom_xpath_object *intern; zval *array_value, **entry, *new_string; int name_len = 0; char *name; DOM_GET_THIS(id); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, \"a\", &array_value) == SUCCESS) { intern = (dom_xpath_object *)zend_object_store_get_object(id TSRMLS_CC); zend_hash_internal_pointer_reset(Z_ARRVAL_P(array_value)); while (zend_hash_get_current_data(Z_ARRVAL_P(array_value), (void **)&entry) == SUCCESS) { SEPARATE_ZVAL(entry); convert_to_string_ex(entry); MAKE_STD_ZVAL(new_string); ZVAL_LONG(new_string,1); zend_hash_update(intern->registered_phpfunctions, Z_STRVAL_PP(entry), Z_STRLEN_PP(entry) + 1, &new_string, sizeof(zval*), NULL); zend_hash_move_forward(Z_ARRVAL_P(array_value)); } intern->registerPhpFunctions = 2; RETURN_TRUE; } else if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &name, &name_len) == SUCCESS) { intern = (dom_xpath_object *)zend_object_store_get_object(id TSRMLS_CC); MAKE_STD_ZVAL(new_string); ZVAL_LONG(new_string,1); zend_hash_update(intern->registered_phpfunctions, name, name_len + 1, &new_string, sizeof(zval*), NULL); intern->registerPhpFunctions = 2; } else { intern = (dom_xpath_object *)zend_object_store_get_object(id TSRMLS_CC); intern->registerPhpFunctions = 1; } } /* }}} end dom_xpath_register_php_functions" ], "each": [ "array each(array arr)", "Return the currently pointed key..value pair in the passed array, and advance the pointer to the next element" ], "easter_date": [ "int easter_date([int year])", "Return the timestamp of midnight on Easter of a given year (defaults to current year)" ], "easter_days": [ "int easter_days([int year, [int method]])", "Return the number of days after March 21 that Easter falls on for a given year (defaults to current year)" ], "echo": [ "void echo(string arg1 [, string ...])", "Output one or more strings" ], "empty": [ "bool empty( mixed var )", "Determine whether a variable is empty" ], "enchant_broker_describe": [ "array enchant_broker_describe(resource broker)", "Enumerates the Enchant providers and tells you some rudimentary information about them. The same info is provided through phpinfo()" ], "enchant_broker_dict_exists": [ "bool enchant_broker_dict_exists(resource broker, string tag)", "Wether a dictionary exists or not. Using non-empty tag" ], "enchant_broker_free": [ "boolean enchant_broker_free(resource broker)", "Destroys the broker object and its dictionnaries" ], "enchant_broker_free_dict": [ "resource enchant_broker_free_dict(resource dict)", "Free the dictionary resource" ], "enchant_broker_get_dict_path": [ "string enchant_broker_get_dict_path(resource broker, int dict_type)", "Get the directory path for a given backend, works with ispell and myspell" ], "enchant_broker_get_error": [ "string enchant_broker_get_error(resource broker)", "Returns the last error of the broker" ], "enchant_broker_init": [ "resource enchant_broker_init()", "create a new broker object capable of requesting" ], "enchant_broker_list_dicts": [ "string enchant_broker_list_dicts(resource broker)", "Lists the dictionaries available for the given broker" ], "enchant_broker_request_dict": [ "resource enchant_broker_request_dict(resource broker, string tag)", "create a new dictionary using tag, the non-empty language tag you wish to request a dictionary for (\"en_US\", \"de_DE\", ...)" ], "enchant_broker_request_pwl_dict": [ "resource enchant_broker_request_pwl_dict(resource broker, string filename)", "creates a dictionary using a PWL file. A PWL file is personal word file one word per line. It must exist before the call." ], "enchant_broker_set_dict_path": [ "bool enchant_broker_set_dict_path(resource broker, int dict_type, string value)", "Set the directory path for a given backend, works with ispell and myspell" ], "enchant_broker_set_ordering": [ "bool enchant_broker_set_ordering(resource broker, string tag, string ordering)", "Declares a preference of dictionaries to use for the language described/referred to by 'tag'. The ordering is a comma delimited list of provider names. As a special exception, the \"*\" tag can be used as a language tag to declare a default ordering for any language that does not explictly declare an ordering." ], "enchant_dict_add_to_personal": [ "void enchant_dict_add_to_personal(resource dict, string word)", "add 'word' to personal word list" ], "enchant_dict_add_to_session": [ "void enchant_dict_add_to_session(resource dict, string word)", "add 'word' to this spell-checking session" ], "enchant_dict_check": [ "bool enchant_dict_check(resource dict, string word)", "If the word is correctly spelled return true, otherwise return false" ], "enchant_dict_describe": [ "array enchant_dict_describe(resource dict)", "Describes an individual dictionary 'dict'" ], "enchant_dict_get_error": [ "string enchant_dict_get_error(resource dict)", "Returns the last error of the current spelling-session" ], "enchant_dict_is_in_session": [ "bool enchant_dict_is_in_session(resource dict, string word)", "whether or not 'word' exists in this spelling-session" ], "enchant_dict_quick_check": [ "bool enchant_dict_quick_check(resource dict, string word [, array &suggestions])", "If the word is correctly spelled return true, otherwise return false, if suggestions variable is provided, fill it with spelling alternatives." ], "enchant_dict_store_replacement": [ "void enchant_dict_store_replacement(resource dict, string mis, string cor)", "add a correction for 'mis' using 'cor'. Notes that you replaced @mis with @cor, so it's possibly more likely that future occurrences of @mis will be replaced with @cor. So it might bump @cor up in the suggestion list." ], "enchant_dict_suggest": [ "array enchant_dict_suggest(resource dict, string word)", "Will return a list of values if any of those pre-conditions are not met." ], "end": [ "mixed end(array array_arg)", "Advances array argument's internal pointer to the last element and return it" ], "ereg": [ "int ereg(string pattern, string string [, array registers])", "Regular expression match" ], "ereg_replace": [ "string ereg_replace(string pattern, string replacement, string string)", "Replace regular expression" ], "eregi": [ "int eregi(string pattern, string string [, array registers])", "Case-insensitive regular expression match" ], "eregi_replace": [ "string eregi_replace(string pattern, string replacement, string string)", "Case insensitive replace regular expression" ], "error_get_last": [ "array error_get_last()", "Get the last occurred error as associative array. Returns NULL if there hasn't been an error yet." ], "error_log": [ "bool error_log(string message [, int message_type [, string destination [, string extra_headers]]])", "Send an error message somewhere" ], "error_reporting": [ "int error_reporting([int new_error_level])", "Return the current error_reporting level, and if an argument was passed - change to the new level" ], "escapeshellarg": [ "string escapeshellarg(string arg)", "Quote and escape an argument for use in a shell command" ], "escapeshellcmd": [ "string escapeshellcmd(string command)", "Escape shell metacharacters" ], "exec": [ "string exec(string command [, array &output [, int &return_value]])", "Execute an external program" ], "exif_imagetype": [ "int exif_imagetype(string imagefile)", "Get the type of an image" ], "exif_read_data": [ "array exif_read_data(string filename [, sections_needed [, sub_arrays[, read_thumbnail]]])", "Reads header data from the JPEG/TIFF image filename and optionally reads the internal thumbnails" ], "exif_tagname": [ "string exif_tagname(index)", "Get headername for index or false if not defined" ], "exif_thumbnail": [ "string exif_thumbnail(string filename [, &width, &height [, &imagetype]])", "Reads the embedded thumbnail" ], "exit": [ "void exit([mixed status])", "Output a message and terminate the current script" ], "exp": [ "float exp(float number)", "Returns e raised to the power of the number" ], "explode": [ "array explode(string separator, string str [, int limit])", "Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned." ], "expm1": [ "float expm1(float number)", "Returns exp(number) - 1, computed in a way that accurate even when the value of number is close to zero" ], "extension_loaded": [ "bool extension_loaded(string extension_name)", "Returns true if the named extension is loaded" ], "extract": [ "int extract(array var_array [, int extract_type [, string prefix]])", "Imports variables into symbol table from an array" ], "ezmlm_hash": [ "int ezmlm_hash(string addr)", "Calculate EZMLM list hash value." ], "fclose": [ "bool fclose(resource fp)", "Close an open file pointer" ], "feof": [ "bool feof(resource fp)", "Test for end-of-file on a file pointer" ], "fflush": [ "bool fflush(resource fp)", "Flushes output" ], "fgetc": [ "string fgetc(resource fp)", "Get a character from file pointer" ], "fgetcsv": [ "array fgetcsv(resource fp [,int length [, string delimiter [, string enclosure [, string escape]]]])", "Get line from file pointer and parse for CSV fields" ], "fgets": [ "string fgets(resource fp[, int length])", "Get a line from file pointer" ], "fgetss": [ "string fgetss(resource fp [, int length [, string allowable_tags]])", "Get a line from file pointer and strip HTML tags" ], "file": [ "array file(string filename [, int flags[, resource context]])", "Read entire file into an array" ], "file_exists": [ "bool file_exists(string filename)", "Returns true if filename exists" ], "file_get_contents": [ "string file_get_contents(string filename [, bool use_include_path [, resource context [, long offset [, long maxlen]]]])", "Read the entire file into a string" ], "file_put_contents": [ "int file_put_contents(string file, mixed data [, int flags [, resource context]])", "Write/Create a file with contents data and return the number of bytes written" ], "fileatime": [ "int fileatime(string filename)", "Get last access time of file" ], "filectime": [ "int filectime(string filename)", "Get inode modification time of file" ], "filegroup": [ "int filegroup(string filename)", "Get file group" ], "fileinode": [ "int fileinode(string filename)", "Get file inode" ], "filemtime": [ "int filemtime(string filename)", "Get last modification time of file" ], "fileowner": [ "int fileowner(string filename)", "Get file owner" ], "fileperms": [ "int fileperms(string filename)", "Get file permissions" ], "filesize": [ "int filesize(string filename)", "Get file size" ], "filetype": [ "string filetype(string filename)", "Get file type" ], "filter_has_var": [ "mixed filter_has_var(constant type, string variable_name)", "* Returns true if the variable with the name 'name' exists in source." ], "filter_input": [ "mixed filter_input(constant type, string variable_name [, long filter [, mixed options]])", "* Returns the filtered variable 'name'* from source `type`." ], "filter_input_array": [ "mixed filter_input_array(constant type, [, mixed options]])", "* Returns an array with all arguments defined in 'definition'." ], "filter_var": [ "mixed filter_var(mixed variable [, long filter [, mixed options]])", "* Returns the filtered version of the vriable." ], "filter_var_array": [ "mixed filter_var_array(array data, [, mixed options]])", "* Returns an array with all arguments defined in 'definition'." ], "finfo_buffer": [ "string finfo_buffer(resource finfo, char *string [, int options [, resource context]])", "Return infromation about a string buffer." ], "finfo_close": [ "resource finfo_close(resource finfo)", "Close fileinfo resource." ], "finfo_file": [ "string finfo_file(resource finfo, char *file_name [, int options [, resource context]])", "Return information about a file." ], "finfo_open": [ "resource finfo_open([int options [, string arg]])", "Create a new fileinfo resource." ], "finfo_set_flags": [ "bool finfo_set_flags(resource finfo, int options)", "Set libmagic configuration options." ], "floatval": [ "float floatval(mixed var)", "Get the float value of a variable" ], "flock": [ "bool flock(resource fp, int operation [, int &wouldblock])", "Portable file locking" ], "floor": [ "float floor(float number)", "Returns the next lowest integer value from the number" ], "flush": [ "void flush(void)", "Flush the output buffer" ], "fmod": [ "float fmod(float x, float y)", "Returns the remainder of dividing x by y as a float" ], "fnmatch": [ "bool fnmatch(string pattern, string filename [, int flags])", "Match filename against pattern" ], "fopen": [ "resource fopen(string filename, string mode [, bool use_include_path [, resource context]])", "Open a file or a URL and return a file pointer" ], "forward_static_call": [ "mixed forward_static_call(mixed function_name [, mixed parmeter] [, mixed ...])", "Call a user function which is the first parameter" ], "fpassthru": [ "int fpassthru(resource fp)", "Output all remaining data from a file pointer" ], "fprintf": [ "int fprintf(resource stream, string format [, mixed arg1 [, mixed ...]])", "Output a formatted string into a stream" ], "fputcsv": [ "int fputcsv(resource fp, array fields [, string delimiter [, string enclosure]])", "Format line as CSV and write to file pointer" ], "fread": [ "string fread(resource fp, int length)", "Binary-safe file read" ], "frenchtojd": [ "int frenchtojd(int month, int day, int year)", "Converts a french republic calendar date to julian day count" ], "fscanf": [ "mixed fscanf(resource stream, string format [, string ...])", "Implements a mostly ANSI compatible fscanf()" ], "fseek": [ "int fseek(resource fp, int offset [, int whence])", "Seek on a file pointer" ], "fsockopen": [ "resource fsockopen(string hostname, int port [, int errno [, string errstr [, float timeout]]])", "Open Internet or Unix domain socket connection" ], "fstat": [ "array fstat(resource fp)", "Stat() on a filehandle" ], "ftell": [ "int ftell(resource fp)", "Get file pointer's read/write position" ], "ftok": [ "int ftok(string pathname, string proj)", "Convert a pathname and a project identifier to a System V IPC key" ], "ftp_alloc": [ "bool ftp_alloc(resource stream, int size[, &response])", "Attempt to allocate space on the remote FTP server" ], "ftp_cdup": [ "bool ftp_cdup(resource stream)", "Changes to the parent directory" ], "ftp_chdir": [ "bool ftp_chdir(resource stream, string directory)", "Changes directories" ], "ftp_chmod": [ "int ftp_chmod(resource stream, int mode, string filename)", "Sets permissions on a file" ], "ftp_close": [ "bool ftp_close(resource stream)", "Closes the FTP stream" ], "ftp_connect": [ "resource ftp_connect(string host [, int port [, int timeout]])", "Opens a FTP stream" ], "ftp_delete": [ "bool ftp_delete(resource stream, string file)", "Deletes a file" ], "ftp_exec": [ "bool ftp_exec(resource stream, string command)", "Requests execution of a program on the FTP server" ], "ftp_fget": [ "bool ftp_fget(resource stream, resource fp, string remote_file, int mode[, int resumepos])", "Retrieves a file from the FTP server and writes it to an open file" ], "ftp_fput": [ "bool ftp_fput(resource stream, string remote_file, resource fp, int mode[, int startpos])", "Stores a file from an open file to the FTP server" ], "ftp_get": [ "bool ftp_get(resource stream, string local_file, string remote_file, int mode[, int resume_pos])", "Retrieves a file from the FTP server and writes it to a local file" ], "ftp_get_option": [ "mixed ftp_get_option(resource stream, int option)", "Gets an FTP option" ], "ftp_login": [ "bool ftp_login(resource stream, string username, string password)", "Logs into the FTP server" ], "ftp_mdtm": [ "int ftp_mdtm(resource stream, string filename)", "Returns the last modification time of the file, or -1 on error" ], "ftp_mkdir": [ "string ftp_mkdir(resource stream, string directory)", "Creates a directory and returns the absolute path for the new directory or false on error" ], "ftp_nb_continue": [ "int ftp_nb_continue(resource stream)", "Continues retrieving/sending a file nbronously" ], "ftp_nb_fget": [ "int ftp_nb_fget(resource stream, resource fp, string remote_file, int mode[, int resumepos])", "Retrieves a file from the FTP server asynchronly and writes it to an open file" ], "ftp_nb_fput": [ "int ftp_nb_fput(resource stream, string remote_file, resource fp, int mode[, int startpos])", "Stores a file from an open file to the FTP server nbronly" ], "ftp_nb_get": [ "int ftp_nb_get(resource stream, string local_file, string remote_file, int mode[, int resume_pos])", "Retrieves a file from the FTP server nbhronly and writes it to a local file" ], "ftp_nb_put": [ "int ftp_nb_put(resource stream, string remote_file, string local_file, int mode[, int startpos])", "Stores a file on the FTP server" ], "ftp_nlist": [ "array ftp_nlist(resource stream, string directory)", "Returns an array of filenames in the given directory" ], "ftp_pasv": [ "bool ftp_pasv(resource stream, bool pasv)", "Turns passive mode on or off" ], "ftp_put": [ "bool ftp_put(resource stream, string remote_file, string local_file, int mode[, int startpos])", "Stores a file on the FTP server" ], "ftp_pwd": [ "string ftp_pwd(resource stream)", "Returns the present working directory" ], "ftp_raw": [ "array ftp_raw(resource stream, string command)", "Sends a literal command to the FTP server" ], "ftp_rawlist": [ "array ftp_rawlist(resource stream, string directory [, bool recursive])", "Returns a detailed listing of a directory as an array of output lines" ], "ftp_rename": [ "bool ftp_rename(resource stream, string src, string dest)", "Renames the given file to a new path" ], "ftp_rmdir": [ "bool ftp_rmdir(resource stream, string directory)", "Removes a directory" ], "ftp_set_option": [ "bool ftp_set_option(resource stream, int option, mixed value)", "Sets an FTP option" ], "ftp_site": [ "bool ftp_site(resource stream, string cmd)", "Sends a SITE command to the server" ], "ftp_size": [ "int ftp_size(resource stream, string filename)", "Returns the size of the file, or -1 on error" ], "ftp_ssl_connect": [ "resource ftp_ssl_connect(string host [, int port [, int timeout]])", "Opens a FTP-SSL stream" ], "ftp_systype": [ "string ftp_systype(resource stream)", "Returns the system type identifier" ], "ftruncate": [ "bool ftruncate(resource fp, int size)", "Truncate file to 'size' length" ], "func_get_arg": [ "mixed func_get_arg(int arg_num)", "Get the $arg_num'th argument that was passed to the function" ], "func_get_args": [ "array func_get_args()", "Get an array of the arguments that were passed to the function" ], "func_num_args": [ "int func_num_args(void)", "Get the number of arguments that were passed to the function" ], "function_exists": [ "bool function_exists(string function_name)", "Checks if the function exists" ], "fwrite": [ "int fwrite(resource fp, string str [, int length])", "Binary-safe file write" ], "gc_collect_cycles": [ "int gc_collect_cycles(void)", "Forces collection of any existing garbage cycles. Returns number of freed zvals" ], "gc_disable": [ "void gc_disable(void)", "Deactivates the circular reference collector" ], "gc_enable": [ "void gc_enable(void)", "Activates the circular reference collector" ], "gc_enabled": [ "void gc_enabled(void)", "Returns status of the circular reference collector" ], "gd_info": [ "array gd_info()", "" ], "getKeywords": [ "static array getKeywords(string $locale) {", "* return an associative array containing keyword-value * pairs for this locale. The keys are keys to the array (doh!) * }}}" ], "get_browser": [ "mixed get_browser([string browser_name [, bool return_array]])", "Get information about the capabilities of a browser. If browser_name is omitted or null, HTTP_USER_AGENT is used. Returns an object by default; if return_array is true, returns an array." ], "get_called_class": [ "string get_called_class()", "Retrieves the \"Late Static Binding\" class name" ], "get_cfg_var": [ "mixed get_cfg_var(string option_name)", "Get the value of a PHP configuration option" ], "get_class": [ "string get_class([object object])", "Retrieves the class name" ], "get_class_methods": [ "array get_class_methods(mixed class)", "Returns an array of method names for class or class instance." ], "get_class_vars": [ "array get_class_vars(string class_name)", "Returns an array of default properties of the class." ], "get_current_user": [ "string get_current_user(void)", "Get the name of the owner of the current PHP script" ], "get_declared_classes": [ "array get_declared_classes()", "Returns an array of all declared classes." ], "get_declared_interfaces": [ "array get_declared_interfaces()", "Returns an array of all declared interfaces." ], "get_defined_constants": [ "array get_defined_constants([bool categorize])", "Return an array containing the names and values of all defined constants" ], "get_defined_functions": [ "array get_defined_functions(void)", "Returns an array of all defined functions" ], "get_defined_vars": [ "array get_defined_vars(void)", "Returns an associative array of names and values of all currently defined variable names (variables in the current scope)" ], "get_display_language": [ "static string get_display_language($locale[, $in_locale = null])", "* gets the language for the $locale in $in_locale or default_locale" ], "get_display_name": [ "static string get_display_name($locale[, $in_locale = null])", "* gets the name for the $locale in $in_locale or default_locale" ], "get_display_region": [ "static string get_display_region($locale, $in_locale = null)", "* gets the region for the $locale in $in_locale or default_locale" ], "get_display_script": [ "static string get_display_script($locale, $in_locale = null)", "* gets the script for the $locale in $in_locale or default_locale" ], "get_extension_funcs": [ "array get_extension_funcs(string extension_name)", "Returns an array with the names of functions belonging to the named extension" ], "get_headers": [ "array get_headers(string url[, int format])", "fetches all the headers sent by the server in response to a HTTP request" ], "get_html_translation_table": [ "array get_html_translation_table([int table [, int quote_style]])", "Returns the internal translation table used by htmlspecialchars and htmlentities" ], "get_include_path": [ "string get_include_path()", "Get the current include_path configuration option" ], "get_included_files": [ "array get_included_files(void)", "Returns an array with the file names that were include_once()'d" ], "get_loaded_extensions": [ "array get_loaded_extensions([bool zend_extensions])", "Return an array containing names of loaded extensions" ], "get_magic_quotes_gpc": [ "int get_magic_quotes_gpc(void)", "Get the current active configuration setting of magic_quotes_gpc" ], "get_magic_quotes_runtime": [ "int get_magic_quotes_runtime(void)", "Get the current active configuration setting of magic_quotes_runtime" ], "get_meta_tags": [ "array get_meta_tags(string filename [, bool use_include_path])", "Extracts all meta tag content attributes from a file and returns an array" ], "get_object_vars": [ "array get_object_vars(object obj)", "Returns an array of object properties" ], "get_parent_class": [ "string get_parent_class([mixed object])", "Retrieves the parent class name for object or class or current scope." ], "get_resource_type": [ "string get_resource_type(resource res)", "Get the resource type name for a given resource" ], "getallheaders": [ "array getallheaders(void)", "" ], "getcwd": [ "mixed getcwd(void)", "Gets the current directory" ], "getdate": [ "array getdate([int timestamp])", "Get date/time information" ], "getenv": [ "string getenv(string varname)", "Get the value of an environment variable" ], "gethostbyaddr": [ "string gethostbyaddr(string ip_address)", "Get the Internet host name corresponding to a given IP address" ], "gethostbyname": [ "string gethostbyname(string hostname)", "Get the IP address corresponding to a given Internet host name" ], "gethostbynamel": [ "array gethostbynamel(string hostname)", "Return a list of IP addresses that a given hostname resolves to." ], "gethostname": [ "string gethostname()", "Get the host name of the current machine" ], "getimagesize": [ "array getimagesize(string imagefile [, array info])", "Get the size of an image as 4-element array" ], "getlastmod": [ "int getlastmod(void)", "Get time of last page modification" ], "getmygid": [ "int getmygid(void)", "Get PHP script owner's GID" ], "getmyinode": [ "int getmyinode(void)", "Get the inode of the current script being parsed" ], "getmypid": [ "int getmypid(void)", "Get current process ID" ], "getmyuid": [ "int getmyuid(void)", "Get PHP script owner's UID" ], "getopt": [ "array getopt(string options [, array longopts])", "Get options from the command line argument list" ], "getprotobyname": [ "int getprotobyname(string name)", "Returns protocol number associated with name as per /etc/protocols" ], "getprotobynumber": [ "string getprotobynumber(int proto)", "Returns protocol name associated with protocol number proto" ], "getrandmax": [ "int getrandmax(void)", "Returns the maximum value a random number can have" ], "getrusage": [ "array getrusage([int who])", "Returns an array of usage statistics" ], "getservbyname": [ "int getservbyname(string service, string protocol)", "Returns port associated with service. Protocol must be \"tcp\" or \"udp\"" ], "getservbyport": [ "string getservbyport(int port, string protocol)", "Returns service name associated with port. Protocol must be \"tcp\" or \"udp\"" ], "gettext": [ "string gettext(string msgid)", "Return the translation of msgid for the current domain, or msgid unaltered if a translation does not exist" ], "gettimeofday": [ "array gettimeofday([bool get_as_float])", "Returns the current time as array" ], "gettype": [ "string gettype(mixed var)", "Returns the type of the variable" ], "glob": [ "array glob(string pattern [, int flags])", "Find pathnames matching a pattern" ], "gmdate": [ "string gmdate(string format [, long timestamp])", "Format a GMT date/time" ], "gmmktime": [ "int gmmktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]])", "Get UNIX timestamp for a GMT date" ], "gmp_abs": [ "resource gmp_abs(resource a)", "Calculates absolute value" ], "gmp_add": [ "resource gmp_add(resource a, resource b)", "Add a and b" ], "gmp_and": [ "resource gmp_and(resource a, resource b)", "Calculates logical AND of a and b" ], "gmp_clrbit": [ "void gmp_clrbit(resource &a, int index)", "Clears bit in a" ], "gmp_cmp": [ "int gmp_cmp(resource a, resource b)", "Compares two numbers" ], "gmp_com": [ "resource gmp_com(resource a)", "Calculates one's complement of a" ], "gmp_div_q": [ "resource gmp_div_q(resource a, resource b [, int round])", "Divide a by b, returns quotient only" ], "gmp_div_qr": [ "array gmp_div_qr(resource a, resource b [, int round])", "Divide a by b, returns quotient and reminder" ], "gmp_div_r": [ "resource gmp_div_r(resource a, resource b [, int round])", "Divide a by b, returns reminder only" ], "gmp_divexact": [ "resource gmp_divexact(resource a, resource b)", "Divide a by b using exact division algorithm" ], "gmp_fact": [ "resource gmp_fact(int a)", "Calculates factorial function" ], "gmp_gcd": [ "resource gmp_gcd(resource a, resource b)", "Computes greatest common denominator (gcd) of a and b" ], "gmp_gcdext": [ "array gmp_gcdext(resource a, resource b)", "Computes G, S, and T, such that AS + BT = G = `gcd' (A, B)" ], "gmp_hamdist": [ "int gmp_hamdist(resource a, resource b)", "Calculates hamming distance between a and b" ], "gmp_init": [ "resource gmp_init(mixed number [, int base])", "Initializes GMP number" ], "gmp_intval": [ "int gmp_intval(resource gmpnumber)", "Gets signed long value of GMP number" ], "gmp_invert": [ "resource gmp_invert(resource a, resource b)", "Computes the inverse of a modulo b" ], "gmp_jacobi": [ "int gmp_jacobi(resource a, resource b)", "Computes Jacobi symbol" ], "gmp_legendre": [ "int gmp_legendre(resource a, resource b)", "Computes Legendre symbol" ], "gmp_mod": [ "resource gmp_mod(resource a, resource b)", "Computes a modulo b" ], "gmp_mul": [ "resource gmp_mul(resource a, resource b)", "Multiply a and b" ], "gmp_neg": [ "resource gmp_neg(resource a)", "Negates a number" ], "gmp_nextprime": [ "resource gmp_nextprime(resource a)", "Finds next prime of a" ], "gmp_or": [ "resource gmp_or(resource a, resource b)", "Calculates logical OR of a and b" ], "gmp_perfect_square": [ "bool gmp_perfect_square(resource a)", "Checks if a is an exact square" ], "gmp_popcount": [ "int gmp_popcount(resource a)", "Calculates the population count of a" ], "gmp_pow": [ "resource gmp_pow(resource base, int exp)", "Raise base to power exp" ], "gmp_powm": [ "resource gmp_powm(resource base, resource exp, resource mod)", "Raise base to power exp and take result modulo mod" ], "gmp_prob_prime": [ "int gmp_prob_prime(resource a[, int reps])", "Checks if a is \"probably prime\"" ], "gmp_random": [ "resource gmp_random([int limiter])", "Gets random number" ], "gmp_scan0": [ "int gmp_scan0(resource a, int start)", "Finds first zero bit" ], "gmp_scan1": [ "int gmp_scan1(resource a, int start)", "Finds first non-zero bit" ], "gmp_setbit": [ "void gmp_setbit(resource &a, int index[, bool set_clear])", "Sets or clear bit in a" ], "gmp_sign": [ "int gmp_sign(resource a)", "Gets the sign of the number" ], "gmp_sqrt": [ "resource gmp_sqrt(resource a)", "Takes integer part of square root of a" ], "gmp_sqrtrem": [ "array gmp_sqrtrem(resource a)", "Square root with remainder" ], "gmp_strval": [ "string gmp_strval(resource gmpnumber [, int base])", "Gets string representation of GMP number" ], "gmp_sub": [ "resource gmp_sub(resource a, resource b)", "Subtract b from a" ], "gmp_testbit": [ "bool gmp_testbit(resource a, int index)", "Tests if bit is set in a" ], "gmp_xor": [ "resource gmp_xor(resource a, resource b)", "Calculates logical exclusive OR of a and b" ], "gmstrftime": [ "string gmstrftime(string format [, int timestamp])", "Format a GMT/UCT time/date according to locale settings" ], "grapheme_extract": [ "string grapheme_extract(string str, int size[, int extract_type[, int start[, int next]]])", "Function to extract a sequence of default grapheme clusters" ], "grapheme_stripos": [ "int grapheme_stripos(string haystack, string needle [, int offset ])", "Find position of first occurrence of a string within another, ignoring case differences" ], "grapheme_stristr": [ "string grapheme_stristr(string haystack, string needle[, bool part])", "Finds first occurrence of a string within another" ], "grapheme_strlen": [ "int grapheme_strlen(string str)", "Get number of graphemes in a string" ], "grapheme_strpos": [ "int grapheme_strpos(string haystack, string needle [, int offset ])", "Find position of first occurrence of a string within another" ], "grapheme_strripos": [ "int grapheme_strripos(string haystack, string needle [, int offset])", "Find position of last occurrence of a string within another, ignoring case" ], "grapheme_strrpos": [ "int grapheme_strrpos(string haystack, string needle [, int offset])", "Find position of last occurrence of a string within another" ], "grapheme_strstr": [ "string grapheme_strstr(string haystack, string needle[, bool part])", "Finds first occurrence of a string within another" ], "grapheme_substr": [ "string grapheme_substr(string str, int start [, int length])", "Returns part of a string" ], "gregoriantojd": [ "int gregoriantojd(int month, int day, int year)", "Converts a gregorian calendar date to julian day count" ], "gzcompress": [ "string gzcompress(string data [, int level])", "Gzip-compress a string" ], "gzdeflate": [ "string gzdeflate(string data [, int level])", "Gzip-compress a string" ], "gzencode": [ "string gzencode(string data [, int level [, int encoding_mode]])", "GZ encode a string" ], "gzfile": [ "array gzfile(string filename [, int use_include_path])", "Read und uncompress entire .gz-file into an array" ], "gzinflate": [ "string gzinflate(string data [, int length])", "Unzip a gzip-compressed string" ], "gzopen": [ "resource gzopen(string filename, string mode [, int use_include_path])", "Open a .gz-file and return a .gz-file pointer" ], "gzuncompress": [ "string gzuncompress(string data [, int length])", "Unzip a gzip-compressed string" ], "hash": [ "string hash(string algo, string data[, bool raw_output = false])", "Generate a hash of a given input string Returns lowercase hexits by default" ], "hash_algos": [ "array hash_algos(void)", "Return a list of registered hashing algorithms" ], "hash_copy": [ "resource hash_copy(resource context)", "Copy hash resource" ], "hash_file": [ "string hash_file(string algo, string filename[, bool raw_output = false])", "Generate a hash of a given file Returns lowercase hexits by default" ], "hash_final": [ "string hash_final(resource context[, bool raw_output=false])", "Output resulting digest" ], "hash_hmac": [ "string hash_hmac(string algo, string data, string key[, bool raw_output = false])", "Generate a hash of a given input string with a key using HMAC Returns lowercase hexits by default" ], "hash_hmac_file": [ "string hash_hmac_file(string algo, string filename, string key[, bool raw_output = false])", "Generate a hash of a given file with a key using HMAC Returns lowercase hexits by default" ], "hash_init": [ "resource hash_init(string algo[, int options, string key])", "Initialize a hashing context" ], "hash_update": [ "bool hash_update(resource context, string data)", "Pump data into the hashing algorithm" ], "hash_update_file": [ "bool hash_update_file(resource context, string filename[, resource context])", "Pump data into the hashing algorithm from a file" ], "hash_update_stream": [ "int hash_update_stream(resource context, resource handle[, integer length])", "Pump data into the hashing algorithm from an open stream" ], "header": [ "void header(string header [, bool replace, [int http_response_code]])", "Sends a raw HTTP header" ], "header_remove": [ "void header_remove([string name])", "Removes an HTTP header previously set using header()" ], "headers_list": [ "array headers_list(void)", "Return list of headers to be sent / already sent" ], "headers_sent": [ "bool headers_sent([string &$file [, int &$line]])", "Returns true if headers have already been sent, false otherwise" ], "hebrev": [ "string hebrev(string str [, int max_chars_per_line])", "Converts logical Hebrew text to visual text" ], "hebrevc": [ "string hebrevc(string str [, int max_chars_per_line])", "Converts logical Hebrew text to visual text with newline conversion" ], "hexdec": [ "int hexdec(string hexadecimal_number)", "Returns the decimal equivalent of the hexadecimal number" ], "highlight_file": [ "bool highlight_file(string file_name [, bool return] )", "Syntax highlight a source file" ], "highlight_string": [ "bool highlight_string(string string [, bool return] )", "Syntax highlight a string or optionally return it" ], "html_entity_decode": [ "string html_entity_decode(string string [, int quote_style][, string charset])", "Convert all HTML entities to their applicable characters" ], "htmlentities": [ "string htmlentities(string string [, int quote_style[, string charset[, bool double_encode]]])", "Convert all applicable characters to HTML entities" ], "htmlspecialchars": [ "string htmlspecialchars(string string [, int quote_style[, string charset[, bool double_encode]]])", "Convert special characters to HTML entities" ], "htmlspecialchars_decode": [ "string htmlspecialchars_decode(string string [, int quote_style])", "Convert special HTML entities back to characters" ], "http_build_query": [ "string http_build_query(mixed formdata [, string prefix [, string arg_separator]])", "Generates a form-encoded query string from an associative array or object." ], "hypot": [ "float hypot(float num1, float num2)", "Returns sqrt(num1*num1 + num2*num2)" ], "ibase_add_user": [ "bool ibase_add_user(resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])", "Add a user to security database" ], "ibase_affected_rows": [ "int ibase_affected_rows( [ resource link_identifier ] )", "Returns the number of rows affected by the previous INSERT, UPDATE or DELETE statement" ], "ibase_backup": [ "mixed ibase_backup(resource service_handle, string source_db, string dest_file [, int options [, bool verbose]])", "Initiates a backup task in the service manager and returns immediately" ], "ibase_blob_add": [ "bool ibase_blob_add(resource blob_handle, string data)", "Add data into created blob" ], "ibase_blob_cancel": [ "bool ibase_blob_cancel(resource blob_handle)", "Cancel creating blob" ], "ibase_blob_close": [ "string ibase_blob_close(resource blob_handle)", "Close blob" ], "ibase_blob_create": [ "resource ibase_blob_create([resource link_identifier])", "Create blob for adding data" ], "ibase_blob_echo": [ "bool ibase_blob_echo([ resource link_identifier, ] string blob_id)", "Output blob contents to browser" ], "ibase_blob_get": [ "string ibase_blob_get(resource blob_handle, int len)", "Get len bytes data from open blob" ], "ibase_blob_import": [ "string ibase_blob_import([ resource link_identifier, ] resource file)", "Create blob, copy file in it, and close it" ], "ibase_blob_info": [ "array ibase_blob_info([ resource link_identifier, ] string blob_id)", "Return blob length and other useful info" ], "ibase_blob_open": [ "resource ibase_blob_open([ resource link_identifier, ] string blob_id)", "Open blob for retrieving data parts" ], "ibase_close": [ "bool ibase_close([resource link_identifier])", "Close an InterBase connection" ], "ibase_commit": [ "bool ibase_commit( resource link_identifier )", "Commit transaction" ], "ibase_commit_ret": [ "bool ibase_commit_ret( resource link_identifier )", "Commit transaction and retain the transaction context" ], "ibase_connect": [ "resource ibase_connect(string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])", "Open a connection to an InterBase database" ], "ibase_db_info": [ "string ibase_db_info(resource service_handle, string db, int action [, int argument])", "Request statistics about a database" ], "ibase_delete_user": [ "bool ibase_delete_user(resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])", "Delete a user from security database" ], "ibase_drop_db": [ "bool ibase_drop_db([resource link_identifier])", "Drop an InterBase database" ], "ibase_errcode": [ "int ibase_errcode(void)", "Return error code" ], "ibase_errmsg": [ "string ibase_errmsg(void)", "Return error message" ], "ibase_execute": [ "mixed ibase_execute(resource query [, mixed bind_arg [, mixed bind_arg [, ...]]])", "Execute a previously prepared query" ], "ibase_fetch_assoc": [ "array ibase_fetch_assoc(resource result [, int fetch_flags])", "Fetch a row from the results of a query" ], "ibase_fetch_object": [ "object ibase_fetch_object(resource result [, int fetch_flags])", "Fetch a object from the results of a query" ], "ibase_fetch_row": [ "array ibase_fetch_row(resource result [, int fetch_flags])", "Fetch a row from the results of a query" ], "ibase_field_info": [ "array ibase_field_info(resource query_result, int field_number)", "Get information about a field" ], "ibase_free_event_handler": [ "bool ibase_free_event_handler(resource event)", "Frees the event handler set by ibase_set_event_handler()" ], "ibase_free_query": [ "bool ibase_free_query(resource query)", "Free memory used by a query" ], "ibase_free_result": [ "bool ibase_free_result(resource result)", "Free the memory used by a result" ], "ibase_gen_id": [ "int ibase_gen_id(string generator [, int increment [, resource link_identifier ]])", "Increments the named generator and returns its new value" ], "ibase_maintain_db": [ "bool ibase_maintain_db(resource service_handle, string db, int action [, int argument])", "Execute a maintenance command on the database server" ], "ibase_modify_user": [ "bool ibase_modify_user(resource service_handle, string user_name, string password [, string first_name [, string middle_name [, string last_name]]])", "Modify a user in security database" ], "ibase_name_result": [ "bool ibase_name_result(resource result, string name)", "Assign a name to a result for use with ... WHERE CURRENT OF <name> statements" ], "ibase_num_fields": [ "int ibase_num_fields(resource query_result)", "Get the number of fields in result" ], "ibase_num_params": [ "int ibase_num_params(resource query)", "Get the number of params in a prepared query" ], "ibase_num_rows": [ "int ibase_num_rows( resource result_identifier )", "Return the number of rows that are available in a result" ], "ibase_param_info": [ "array ibase_param_info(resource query, int field_number)", "Get information about a parameter" ], "ibase_pconnect": [ "resource ibase_pconnect(string database [, string username [, string password [, string charset [, int buffers [, int dialect [, string role]]]]]])", "Open a persistent connection to an InterBase database" ], "ibase_prepare": [ "resource ibase_prepare(resource link_identifier[, string query [, resource trans_identifier ]])", "Prepare a query for later execution" ], "ibase_query": [ "mixed ibase_query([resource link_identifier, [ resource link_identifier, ]] string query [, mixed bind_arg [, mixed bind_arg [, ...]]])", "Execute a query" ], "ibase_restore": [ "mixed ibase_restore(resource service_handle, string source_file, string dest_db [, int options [, bool verbose]])", "Initiates a restore task in the service manager and returns immediately" ], "ibase_rollback": [ "bool ibase_rollback( resource link_identifier )", "Rollback transaction" ], "ibase_rollback_ret": [ "bool ibase_rollback_ret( resource link_identifier )", "Rollback transaction and retain the transaction context" ], "ibase_server_info": [ "string ibase_server_info(resource service_handle, int action)", "Request information about a database server" ], "ibase_service_attach": [ "resource ibase_service_attach(string host, string dba_username, string dba_password)", "Connect to the service manager" ], "ibase_service_detach": [ "bool ibase_service_detach(resource service_handle)", "Disconnect from the service manager" ], "ibase_set_event_handler": [ "resource ibase_set_event_handler([resource link_identifier,] callback handler, string event [, string event [, ...]])", "Register the callback for handling each of the named events" ], "ibase_trans": [ "resource ibase_trans([int trans_args [, resource link_identifier [, ... ], int trans_args [, resource link_identifier [, ... ]] [, ...]]])", "Start a transaction over one or several databases" ], "ibase_wait_event": [ "string ibase_wait_event([resource link_identifier,] string event [, string event [, ...]])", "Waits for any one of the passed Interbase events to be posted by the database, and returns its name" ], "iconv": [ "string iconv(string in_charset, string out_charset, string str)", "Returns str converted to the out_charset character set" ], "iconv_get_encoding": [ "mixed iconv_get_encoding([string type])", "Get internal encoding and output encoding for ob_iconv_handler()" ], "iconv_mime_decode": [ "string iconv_mime_decode(string encoded_string [, int mode, string charset])", "Decodes a mime header field" ], "iconv_mime_decode_headers": [ "array iconv_mime_decode_headers(string headers [, int mode, string charset])", "Decodes multiple mime header fields" ], "iconv_mime_encode": [ "string iconv_mime_encode(string field_name, string field_value [, array preference])", "Composes a mime header field with field_name and field_value in a specified scheme" ], "iconv_set_encoding": [ "bool iconv_set_encoding(string type, string charset)", "Sets internal encoding and output encoding for ob_iconv_handler()" ], "iconv_strlen": [ "int iconv_strlen(string str [, string charset])", "Returns the character count of str" ], "iconv_strpos": [ "int iconv_strpos(string haystack, string needle [, int offset [, string charset]])", "Finds position of first occurrence of needle within part of haystack beginning with offset" ], "iconv_strrpos": [ "int iconv_strrpos(string haystack, string needle [, string charset])", "Finds position of last occurrence of needle within part of haystack beginning with offset" ], "iconv_substr": [ "string iconv_substr(string str, int offset, [int length, string charset])", "Returns specified part of a string" ], "idate": [ "int idate(string format [, int timestamp])", "Format a local time/date as integer" ], "idn_to_ascii": [ "int idn_to_ascii(string domain[, int options])", "Converts an Unicode domain to ASCII representation, as defined in the IDNA RFC" ], "idn_to_utf8": [ "int idn_to_utf8(string domain[, int options])", "Converts an ASCII representation of the domain to Unicode (UTF-8), as defined in the IDNA RFC" ], "ignore_user_abort": [ "int ignore_user_abort([string value])", "Set whether we want to ignore a user abort event or not" ], "image2wbmp": [ "bool image2wbmp(resource im [, string filename [, int threshold]])", "Output WBMP image to browser or file" ], "image_type_to_extension": [ "string image_type_to_extension(int imagetype [, bool include_dot])", "Get file extension for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype" ], "image_type_to_mime_type": [ "string image_type_to_mime_type(int imagetype)", "Get Mime-Type for image-type returned by getimagesize, exif_read_data, exif_thumbnail, exif_imagetype" ], "imagealphablending": [ "bool imagealphablending(resource im, bool on)", "Turn alpha blending mode on or off for the given image" ], "imageantialias": [ "bool imageantialias(resource im, bool on)", "Should antialiased functions used or not" ], "imagearc": [ "bool imagearc(resource im, int cx, int cy, int w, int h, int s, int e, int col)", "Draw a partial ellipse" ], "imagechar": [ "bool imagechar(resource im, int font, int x, int y, string c, int col)", "Draw a character" ], "imagecharup": [ "bool imagecharup(resource im, int font, int x, int y, string c, int col)", "Draw a character rotated 90 degrees counter-clockwise" ], "imagecolorallocate": [ "int imagecolorallocate(resource im, int red, int green, int blue)", "Allocate a color for an image" ], "imagecolorallocatealpha": [ "int imagecolorallocatealpha(resource im, int red, int green, int blue, int alpha)", "Allocate a color with an alpha level. Works for true color and palette based images" ], "imagecolorat": [ "int imagecolorat(resource im, int x, int y)", "Get the index of the color of a pixel" ], "imagecolorclosest": [ "int imagecolorclosest(resource im, int red, int green, int blue)", "Get the index of the closest color to the specified color" ], "imagecolorclosestalpha": [ "int imagecolorclosestalpha(resource im, int red, int green, int blue, int alpha)", "Find the closest matching colour with alpha transparency" ], "imagecolorclosesthwb": [ "int imagecolorclosesthwb(resource im, int red, int green, int blue)", "Get the index of the color which has the hue, white and blackness nearest to the given color" ], "imagecolordeallocate": [ "bool imagecolordeallocate(resource im, int index)", "De-allocate a color for an image" ], "imagecolorexact": [ "int imagecolorexact(resource im, int red, int green, int blue)", "Get the index of the specified color" ], "imagecolorexactalpha": [ "int imagecolorexactalpha(resource im, int red, int green, int blue, int alpha)", "Find exact match for colour with transparency" ], "imagecolormatch": [ "bool imagecolormatch(resource im1, resource im2)", "Makes the colors of the palette version of an image more closely match the true color version" ], "imagecolorresolve": [ "int imagecolorresolve(resource im, int red, int green, int blue)", "Get the index of the specified color or its closest possible alternative" ], "imagecolorresolvealpha": [ "int imagecolorresolvealpha(resource im, int red, int green, int blue, int alpha)", "Resolve/Allocate a colour with an alpha level. Works for true colour and palette based images" ], "imagecolorset": [ "void imagecolorset(resource im, int col, int red, int green, int blue)", "Set the color for the specified palette index" ], "imagecolorsforindex": [ "array imagecolorsforindex(resource im, int col)", "Get the colors for an index" ], "imagecolorstotal": [ "int imagecolorstotal(resource im)", "Find out the number of colors in an image's palette" ], "imagecolortransparent": [ "int imagecolortransparent(resource im [, int col])", "Define a color as transparent" ], "imageconvolution": [ "resource imageconvolution(resource src_im, array matrix3x3, double div, double offset)", "Apply a 3x3 convolution matrix, using coefficient div and offset" ], "imagecopy": [ "bool imagecopy(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h)", "Copy part of an image" ], "imagecopymerge": [ "bool imagecopymerge(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)", "Merge one part of an image with another" ], "imagecopymergegray": [ "bool imagecopymergegray(resource src_im, resource dst_im, int dst_x, int dst_y, int src_x, int src_y, int src_w, int src_h, int pct)", "Merge one part of an image with another" ], "imagecopyresampled": [ "bool imagecopyresampled(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h)", "Copy and resize part of an image using resampling to help ensure clarity" ], "imagecopyresized": [ "bool imagecopyresized(resource dst_im, resource src_im, int dst_x, int dst_y, int src_x, int src_y, int dst_w, int dst_h, int src_w, int src_h)", "Copy and resize part of an image" ], "imagecreate": [ "resource imagecreate(int x_size, int y_size)", "Create a new image" ], "imagecreatefromgd": [ "resource imagecreatefromgd(string filename)", "Create a new image from GD file or URL" ], "imagecreatefromgd2": [ "resource imagecreatefromgd2(string filename)", "Create a new image from GD2 file or URL" ], "imagecreatefromgd2part": [ "resource imagecreatefromgd2part(string filename, int srcX, int srcY, int width, int height)", "Create a new image from a given part of GD2 file or URL" ], "imagecreatefromgif": [ "resource imagecreatefromgif(string filename)", "Create a new image from GIF file or URL" ], "imagecreatefromjpeg": [ "resource imagecreatefromjpeg(string filename)", "Create a new image from JPEG file or URL" ], "imagecreatefrompng": [ "resource imagecreatefrompng(string filename)", "Create a new image from PNG file or URL" ], "imagecreatefromstring": [ "resource imagecreatefromstring(string image)", "Create a new image from the image stream in the string" ], "imagecreatefromwbmp": [ "resource imagecreatefromwbmp(string filename)", "Create a new image from WBMP file or URL" ], "imagecreatefromxbm": [ "resource imagecreatefromxbm(string filename)", "Create a new image from XBM file or URL" ], "imagecreatefromxpm": [ "resource imagecreatefromxpm(string filename)", "Create a new image from XPM file or URL" ], "imagecreatetruecolor": [ "resource imagecreatetruecolor(int x_size, int y_size)", "Create a new true color image" ], "imagedashedline": [ "bool imagedashedline(resource im, int x1, int y1, int x2, int y2, int col)", "Draw a dashed line" ], "imagedestroy": [ "bool imagedestroy(resource im)", "Destroy an image" ], "imageellipse": [ "bool imageellipse(resource im, int cx, int cy, int w, int h, int color)", "Draw an ellipse" ], "imagefill": [ "bool imagefill(resource im, int x, int y, int col)", "Flood fill" ], "imagefilledarc": [ "bool imagefilledarc(resource im, int cx, int cy, int w, int h, int s, int e, int col, int style)", "Draw a filled partial ellipse" ], "imagefilledellipse": [ "bool imagefilledellipse(resource im, int cx, int cy, int w, int h, int color)", "Draw an ellipse" ], "imagefilledpolygon": [ "bool imagefilledpolygon(resource im, array point, int num_points, int col)", "Draw a filled polygon" ], "imagefilledrectangle": [ "bool imagefilledrectangle(resource im, int x1, int y1, int x2, int y2, int col)", "Draw a filled rectangle" ], "imagefilltoborder": [ "bool imagefilltoborder(resource im, int x, int y, int border, int col)", "Flood fill to specific color" ], "imagefilter": [ "bool imagefilter(resource src_im, int filtertype, [args] )", "Applies Filter an image using a custom angle" ], "imagefontheight": [ "int imagefontheight(int font)", "Get font height" ], "imagefontwidth": [ "int imagefontwidth(int font)", "Get font width" ], "imageftbbox": [ "array imageftbbox(float size, float angle, string font_file, string text [, array extrainfo])", "Give the bounding box of a text using fonts via freetype2" ], "imagefttext": [ "array imagefttext(resource im, float size, float angle, int x, int y, int col, string font_file, string text [, array extrainfo])", "Write text to the image using fonts via freetype2" ], "imagegammacorrect": [ "bool imagegammacorrect(resource im, float inputgamma, float outputgamma)", "Apply a gamma correction to a GD image" ], "imagegd": [ "bool imagegd(resource im [, string filename])", "Output GD image to browser or file" ], "imagegd2": [ "bool imagegd2(resource im [, string filename, [, int chunk_size, [, int type]]])", "Output GD2 image to browser or file" ], "imagegif": [ "bool imagegif(resource im [, string filename])", "Output GIF image to browser or file" ], "imagegrabscreen": [ "resource imagegrabscreen()", "Grab a screenshot" ], "imagegrabwindow": [ "resource imagegrabwindow(int window_handle [, int client_area])", "Grab a window or its client area using a windows handle (HWND property in COM instance)" ], "imageinterlace": [ "int imageinterlace(resource im [, int interlace])", "Enable or disable interlace" ], "imageistruecolor": [ "bool imageistruecolor(resource im)", "return true if the image uses truecolor" ], "imagejpeg": [ "bool imagejpeg(resource im [, string filename [, int quality]])", "Output JPEG image to browser or file" ], "imagelayereffect": [ "bool imagelayereffect(resource im, int effect)", "Set the alpha blending flag to use the bundled libgd layering effects" ], "imageline": [ "bool imageline(resource im, int x1, int y1, int x2, int y2, int col)", "Draw a line" ], "imageloadfont": [ "int imageloadfont(string filename)", "Load a new font" ], "imagepalettecopy": [ "void imagepalettecopy(resource dst, resource src)", "Copy the palette from the src image onto the dst image" ], "imagepng": [ "bool imagepng(resource im [, string filename])", "Output PNG image to browser or file" ], "imagepolygon": [ "bool imagepolygon(resource im, array point, int num_points, int col)", "Draw a polygon" ], "imagepsbbox": [ "array imagepsbbox(string text, resource font, int size [, int space, int tightness, float angle])", "Return the bounding box needed by a string if rasterized" ], "imagepscopyfont": [ "int imagepscopyfont(int font_index)", "Make a copy of a font for purposes like extending or reenconding" ], "imagepsencodefont": [ "bool imagepsencodefont(resource font_index, string filename)", "To change a fonts character encoding vector" ], "imagepsextendfont": [ "bool imagepsextendfont(resource font_index, float extend)", "Extend or or condense (if extend < 1) a font" ], "imagepsfreefont": [ "bool imagepsfreefont(resource font_index)", "Free memory used by a font" ], "imagepsloadfont": [ "resource imagepsloadfont(string pathname)", "Load a new font from specified file" ], "imagepsslantfont": [ "bool imagepsslantfont(resource font_index, float slant)", "Slant a font" ], "imagepstext": [ "array imagepstext(resource image, string text, resource font, int size, int foreground, int background, int xcoord, int ycoord [, int space [, int tightness [, float angle [, int antialias])", "Rasterize a string over an image" ], "imagerectangle": [ "bool imagerectangle(resource im, int x1, int y1, int x2, int y2, int col)", "Draw a rectangle" ], "imagerotate": [ "resource imagerotate(resource src_im, float angle, int bgdcolor [, int ignoretransparent])", "Rotate an image using a custom angle" ], "imagesavealpha": [ "bool imagesavealpha(resource im, bool on)", "Include alpha channel to a saved image" ], "imagesetbrush": [ "bool imagesetbrush(resource image, resource brush)", "Set the brush image to $brush when filling $image with the \"IMG_COLOR_BRUSHED\" color" ], "imagesetpixel": [ "bool imagesetpixel(resource im, int x, int y, int col)", "Set a single pixel" ], "imagesetstyle": [ "bool imagesetstyle(resource im, array styles)", "Set the line drawing styles for use with imageline and IMG_COLOR_STYLED." ], "imagesetthickness": [ "bool imagesetthickness(resource im, int thickness)", "Set line thickness for drawing lines, ellipses, rectangles, polygons etc." ], "imagesettile": [ "bool imagesettile(resource image, resource tile)", "Set the tile image to $tile when filling $image with the \"IMG_COLOR_TILED\" color" ], "imagestring": [ "bool imagestring(resource im, int font, int x, int y, string str, int col)", "Draw a string horizontally" ], "imagestringup": [ "bool imagestringup(resource im, int font, int x, int y, string str, int col)", "Draw a string vertically - rotated 90 degrees counter-clockwise" ], "imagesx": [ "int imagesx(resource im)", "Get image width" ], "imagesy": [ "int imagesy(resource im)", "Get image height" ], "imagetruecolortopalette": [ "void imagetruecolortopalette(resource im, bool ditherFlag, int colorsWanted)", "Convert a true colour image to a palette based image with a number of colours, optionally using dithering." ], "imagettfbbox": [ "array imagettfbbox(float size, float angle, string font_file, string text)", "Give the bounding box of a text using TrueType fonts" ], "imagettftext": [ "array imagettftext(resource im, float size, float angle, int x, int y, int col, string font_file, string text)", "Write text to the image using a TrueType font" ], "imagetypes": [ "int imagetypes(void)", "Return the types of images supported in a bitfield - 1=GIF, 2=JPEG, 4=PNG, 8=WBMP, 16=XPM" ], "imagewbmp": [ "bool imagewbmp(resource im [, string filename, [, int foreground]])", "Output WBMP image to browser or file" ], "imagexbm": [ "int imagexbm(int im, string filename [, int foreground])", "Output XBM image to browser or file" ], "imap_8bit": [ "string imap_8bit(string text)", "Convert an 8-bit string to a quoted-printable string" ], "imap_alerts": [ "array imap_alerts(void)", "Returns an array of all IMAP alerts that have been generated since the last page load or since the last imap_alerts() call, whichever came last. The alert stack is cleared after imap_alerts() is called." ], "imap_append": [ "bool imap_append(resource stream_id, string folder, string message [, string options [, string internal_date]])", "Append a new message to a specified mailbox" ], "imap_base64": [ "string imap_base64(string text)", "Decode BASE64 encoded text" ], "imap_binary": [ "string imap_binary(string text)", "Convert an 8bit string to a base64 string" ], "imap_body": [ "string imap_body(resource stream_id, int msg_no [, int options])", "Read the message body" ], "imap_bodystruct": [ "object imap_bodystruct(resource stream_id, int msg_no, string section)", "Read the structure of a specified body section of a specific message" ], "imap_check": [ "object imap_check(resource stream_id)", "Get mailbox properties" ], "imap_clearflag_full": [ "bool imap_clearflag_full(resource stream_id, string sequence, string flag [, int options])", "Clears flags on messages" ], "imap_close": [ "bool imap_close(resource stream_id [, int options])", "Close an IMAP stream" ], "imap_createmailbox": [ "bool imap_createmailbox(resource stream_id, string mailbox)", "Create a new mailbox" ], "imap_delete": [ "bool imap_delete(resource stream_id, int msg_no [, int options])", "Mark a message for deletion" ], "imap_deletemailbox": [ "bool imap_deletemailbox(resource stream_id, string mailbox)", "Delete a mailbox" ], "imap_errors": [ "array imap_errors(void)", "Returns an array of all IMAP errors generated since the last page load, or since the last imap_errors() call, whichever came last. The error stack is cleared after imap_errors() is called." ], "imap_expunge": [ "bool imap_expunge(resource stream_id)", "Permanently delete all messages marked for deletion" ], "imap_fetch_overview": [ "array imap_fetch_overview(resource stream_id, string sequence [, int options])", "Read an overview of the information in the headers of the given message sequence" ], "imap_fetchbody": [ "string imap_fetchbody(resource stream_id, int msg_no, string section [, int options])", "Get a specific body section" ], "imap_fetchheader": [ "string imap_fetchheader(resource stream_id, int msg_no [, int options])", "Get the full unfiltered header for a message" ], "imap_fetchstructure": [ "object imap_fetchstructure(resource stream_id, int msg_no [, int options])", "Read the full structure of a message" ], "imap_gc": [ "bool imap_gc(resource stream_id, int flags)", "This function garbage collects (purges) the cache of entries of a specific type." ], "imap_get_quota": [ "array imap_get_quota(resource stream_id, string qroot)", "Returns the quota set to the mailbox account qroot" ], "imap_get_quotaroot": [ "array imap_get_quotaroot(resource stream_id, string mbox)", "Returns the quota set to the mailbox account mbox" ], "imap_getacl": [ "array imap_getacl(resource stream_id, string mailbox)", "Gets the ACL for a given mailbox" ], "imap_getmailboxes": [ "array imap_getmailboxes(resource stream_id, string ref, string pattern)", "Reads the list of mailboxes and returns a full array of objects containing name, attributes, and delimiter" ], "imap_getsubscribed": [ "array imap_getsubscribed(resource stream_id, string ref, string pattern)", "Return a list of subscribed mailboxes, in the same format as imap_getmailboxes()" ], "imap_headerinfo": [ "object imap_headerinfo(resource stream_id, int msg_no [, int from_length [, int subject_length [, string default_host]]])", "Read the headers of the message" ], "imap_headers": [ "array imap_headers(resource stream_id)", "Returns headers for all messages in a mailbox" ], "imap_last_error": [ "string imap_last_error(void)", "Returns the last error that was generated by an IMAP function. The error stack is NOT cleared after this call." ], "imap_list": [ "array imap_list(resource stream_id, string ref, string pattern)", "Read the list of mailboxes" ], "imap_listscan": [ "array imap_listscan(resource stream_id, string ref, string pattern, string content)", "Read list of mailboxes containing a certain string" ], "imap_lsub": [ "array imap_lsub(resource stream_id, string ref, string pattern)", "Return a list of subscribed mailboxes" ], "imap_mail": [ "bool imap_mail(string to, string subject, string message [, string additional_headers [, string cc [, string bcc [, string rpath]]]])", "Send an email message" ], "imap_mail_compose": [ "string imap_mail_compose(array envelope, array body)", "Create a MIME message based on given envelope and body sections" ], "imap_mail_copy": [ "bool imap_mail_copy(resource stream_id, string msglist, string mailbox [, int options])", "Copy specified message to a mailbox" ], "imap_mail_move": [ "bool imap_mail_move(resource stream_id, string sequence, string mailbox [, int options])", "Move specified message to a mailbox" ], "imap_mailboxmsginfo": [ "object imap_mailboxmsginfo(resource stream_id)", "Returns info about the current mailbox" ], "imap_mime_header_decode": [ "array imap_mime_header_decode(string str)", "Decode mime header element in accordance with RFC 2047 and return array of objects containing 'charset' encoding and decoded 'text'" ], "imap_msgno": [ "int imap_msgno(resource stream_id, int unique_msg_id)", "Get the sequence number associated with a UID" ], "imap_mutf7_to_utf8": [ "string imap_mutf7_to_utf8(string in)", "Decode a modified UTF-7 string to UTF-8" ], "imap_num_msg": [ "int imap_num_msg(resource stream_id)", "Gives the number of messages in the current mailbox" ], "imap_num_recent": [ "int imap_num_recent(resource stream_id)", "Gives the number of recent messages in current mailbox" ], "imap_open": [ "resource imap_open(string mailbox, string user, string password [, int options [, int n_retries]])", "Open an IMAP stream to a mailbox" ], "imap_ping": [ "bool imap_ping(resource stream_id)", "Check if the IMAP stream is still active" ], "imap_qprint": [ "string imap_qprint(string text)", "Convert a quoted-printable string to an 8-bit string" ], "imap_renamemailbox": [ "bool imap_renamemailbox(resource stream_id, string old_name, string new_name)", "Rename a mailbox" ], "imap_reopen": [ "bool imap_reopen(resource stream_id, string mailbox [, int options [, int n_retries]])", "Reopen an IMAP stream to a new mailbox" ], "imap_rfc822_parse_adrlist": [ "array imap_rfc822_parse_adrlist(string address_string, string default_host)", "Parses an address string" ], "imap_rfc822_parse_headers": [ "object imap_rfc822_parse_headers(string headers [, string default_host])", "Parse a set of mail headers contained in a string, and return an object similar to imap_headerinfo()" ], "imap_rfc822_write_address": [ "string imap_rfc822_write_address(string mailbox, string host, string personal)", "Returns a properly formatted email address given the mailbox, host, and personal info" ], "imap_savebody": [ "bool imap_savebody(resource stream_id, string|resource file, int msg_no[, string section = \"\"[, int options = 0]])", "Save a specific body section to a file" ], "imap_search": [ "array imap_search(resource stream_id, string criteria [, int options [, string charset]])", "Return a list of messages matching the given criteria" ], "imap_set_quota": [ "bool imap_set_quota(resource stream_id, string qroot, int mailbox_size)", "Will set the quota for qroot mailbox" ], "imap_setacl": [ "bool imap_setacl(resource stream_id, string mailbox, string id, string rights)", "Sets the ACL for a given mailbox" ], "imap_setflag_full": [ "bool imap_setflag_full(resource stream_id, string sequence, string flag [, int options])", "Sets flags on messages" ], "imap_sort": [ "array imap_sort(resource stream_id, int criteria, int reverse [, int options [, string search_criteria [, string charset]]])", "Sort an array of message headers, optionally including only messages that meet specified criteria." ], "imap_status": [ "object imap_status(resource stream_id, string mailbox, int options)", "Get status info from a mailbox" ], "imap_subscribe": [ "bool imap_subscribe(resource stream_id, string mailbox)", "Subscribe to a mailbox" ], "imap_thread": [ "array imap_thread(resource stream_id [, int options])", "Return threaded by REFERENCES tree" ], "imap_timeout": [ "mixed imap_timeout(int timeout_type [, int timeout])", "Set or fetch imap timeout" ], "imap_uid": [ "int imap_uid(resource stream_id, int msg_no)", "Get the unique message id associated with a standard sequential message number" ], "imap_undelete": [ "bool imap_undelete(resource stream_id, int msg_no [, int flags])", "Remove the delete flag from a message" ], "imap_unsubscribe": [ "bool imap_unsubscribe(resource stream_id, string mailbox)", "Unsubscribe from a mailbox" ], "imap_utf7_decode": [ "string imap_utf7_decode(string buf)", "Decode a modified UTF-7 string" ], "imap_utf7_encode": [ "string imap_utf7_encode(string buf)", "Encode a string in modified UTF-7" ], "imap_utf8": [ "string imap_utf8(string mime_encoded_text)", "Convert a mime-encoded text to UTF-8" ], "imap_utf8_to_mutf7": [ "string imap_utf8_to_mutf7(string in)", "Encode a UTF-8 string to modified UTF-7" ], "implode": [ "string implode([string glue,] array pieces)", "Joins array elements placing glue string between items and return one string" ], "import_request_variables": [ "bool import_request_variables(string types [, string prefix])", "Import GET/POST/Cookie variables into the global scope" ], "in_array": [ "bool in_array(mixed needle, array haystack [, bool strict])", "Checks if the given value exists in the array" ], "include": [ "bool include(string path)", "Includes and evaluates the specified file" ], "include_once": [ "bool include_once(string path)", "Includes and evaluates the specified file" ], "inet_ntop": [ "string inet_ntop(string in_addr)", "Converts a packed inet address to a human readable IP address string" ], "inet_pton": [ "string inet_pton(string ip_address)", "Converts a human readable IP address to a packed binary string" ], "ini_get": [ "string ini_get(string varname)", "Get a configuration option" ], "ini_get_all": [ "array ini_get_all([string extension[, bool details = true]])", "Get all configuration options" ], "ini_restore": [ "void ini_restore(string varname)", "Restore the value of a configuration option specified by varname" ], "ini_set": [ "string ini_set(string varname, string newvalue)", "Set a configuration option, returns false on error and the old value of the configuration option on success" ], "interface_exists": [ "bool interface_exists(string classname [, bool autoload])", "Checks if the class exists" ], "intl_error_name": [ "string intl_error_name()", "* Return a string for a given error code. * The string will be the same as the name of the error code constant." ], "intl_get_error_code": [ "int intl_get_error_code()", "* Get code of the last occured error." ], "intl_get_error_message": [ "string intl_get_error_message()", "* Get text description of the last occured error." ], "intl_is_failure": [ "bool intl_is_failure()", "* Check whether the given error code indicates a failure. * Returns true if it does, and false if the code * indicates success or a warning." ], "intval": [ "int intval(mixed var [, int base])", "Get the integer value of a variable using the optional base for the conversion" ], "ip2long": [ "int ip2long(string ip_address)", "Converts a string containing an (IPv4) Internet Protocol dotted address into a proper address" ], "iptcembed": [ "array iptcembed(string iptcdata, string jpeg_file_name [, int spool])", "Embed binary IPTC data into a JPEG image." ], "iptcparse": [ "array iptcparse(string iptcdata)", "Parse binary IPTC-data into associative array" ], "is_a": [ "bool is_a(object object, string class_name)", "Returns true if the object is of this class or has this class as one of its parents" ], "is_array": [ "bool is_array(mixed var)", "Returns true if variable is an array" ], "is_bool": [ "bool is_bool(mixed var)", "Returns true if variable is a boolean" ], "is_callable": [ "bool is_callable(mixed var [, bool syntax_only [, string callable_name]])", "Returns true if var is callable." ], "is_dir": [ "bool is_dir(string filename)", "Returns true if file is directory" ], "is_executable": [ "bool is_executable(string filename)", "Returns true if file is executable" ], "is_file": [ "bool is_file(string filename)", "Returns true if file is a regular file" ], "is_finite": [ "bool is_finite(float val)", "Returns whether argument is finite" ], "is_float": [ "bool is_float(mixed var)", "Returns true if variable is float point" ], "is_infinite": [ "bool is_infinite(float val)", "Returns whether argument is infinite" ], "is_link": [ "bool is_link(string filename)", "Returns true if file is symbolic link" ], "is_long": [ "bool is_long(mixed var)", "Returns true if variable is a long (integer)" ], "is_nan": [ "bool is_nan(float val)", "Returns whether argument is not a number" ], "is_null": [ "bool is_null(mixed var)", "Returns true if variable is null" ], "is_numeric": [ "bool is_numeric(mixed value)", "Returns true if value is a number or a numeric string" ], "is_object": [ "bool is_object(mixed var)", "Returns true if variable is an object" ], "is_readable": [ "bool is_readable(string filename)", "Returns true if file can be read" ], "is_resource": [ "bool is_resource(mixed var)", "Returns true if variable is a resource" ], "is_scalar": [ "bool is_scalar(mixed value)", "Returns true if value is a scalar" ], "is_string": [ "bool is_string(mixed var)", "Returns true if variable is a string" ], "is_subclass_of": [ "bool is_subclass_of(object object, string class_name)", "Returns true if the object has this class as one of its parents" ], "is_uploaded_file": [ "bool is_uploaded_file(string path)", "Check if file was created by rfc1867 upload" ], "is_writable": [ "bool is_writable(string filename)", "Returns true if file can be written" ], "isset": [ "bool isset(mixed var [, mixed var])", "Determine whether a variable is set" ], "iterator_apply": [ "int iterator_apply(Traversable it, mixed function [, mixed params])", "Calls a function for every element in an iterator" ], "iterator_count": [ "int iterator_count(Traversable it)", "Count the elements in an iterator" ], "iterator_to_array": [ "array iterator_to_array(Traversable it [, bool use_keys = true])", "Copy the iterator into an array" ], "jddayofweek": [ "mixed jddayofweek(int juliandaycount [, int mode])", "Returns name or number of day of week from julian day count" ], "jdmonthname": [ "string jdmonthname(int juliandaycount, int mode)", "Returns name of month for julian day count" ], "jdtofrench": [ "string jdtofrench(int juliandaycount)", "Converts a julian day count to a french republic calendar date" ], "jdtogregorian": [ "string jdtogregorian(int juliandaycount)", "Converts a julian day count to a gregorian calendar date" ], "jdtojewish": [ "string jdtojewish(int juliandaycount [, bool hebrew [, int fl]])", "Converts a julian day count to a jewish calendar date" ], "jdtojulian": [ "string jdtojulian(int juliandaycount)", "Convert a julian day count to a julian calendar date" ], "jdtounix": [ "int jdtounix(int jday)", "Convert Julian Day to UNIX timestamp" ], "jewishtojd": [ "int jewishtojd(int month, int day, int year)", "Converts a jewish calendar date to a julian day count" ], "join": [ "string join(array src, string glue)", "An alias for implode" ], "jpeg2wbmp": [ "bool jpeg2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold)", "Convert JPEG image to WBMP image" ], "json_decode": [ "mixed json_decode(string json [, bool assoc [, long depth]])", "Decodes the JSON representation into a PHP value" ], "json_encode": [ "string json_encode(mixed data [, int options])", "Returns the JSON representation of a value" ], "json_last_error": [ "int json_last_error()", "Returns the error code of the last json_decode()." ], "juliantojd": [ "int juliantojd(int month, int day, int year)", "Converts a julian calendar date to julian day count" ], "key": [ "mixed key(array array_arg)", "Return the key of the element currently pointed to by the internal array pointer" ], "krsort": [ "bool krsort(array &array_arg [, int sort_flags])", "Sort an array by key value in reverse order" ], "ksort": [ "bool ksort(array &array_arg [, int sort_flags])", "Sort an array by key" ], "lcfirst": [ "string lcfirst(string str)", "Make a string's first character lowercase" ], "lcg_value": [ "float lcg_value()", "Returns a value from the combined linear congruential generator" ], "lchgrp": [ "bool lchgrp(string filename, mixed group)", "Change symlink group" ], "ldap_8859_to_t61": [ "string ldap_8859_to_t61(string value)", "Translate 8859 characters to t61 characters" ], "ldap_add": [ "bool ldap_add(resource link, string dn, array entry)", "Add entries to LDAP directory" ], "ldap_bind": [ "bool ldap_bind(resource link [, string dn [, string password]])", "Bind to LDAP directory" ], "ldap_compare": [ "bool ldap_compare(resource link, string dn, string attr, string value)", "Determine if an entry has a specific value for one of its attributes" ], "ldap_connect": [ "resource ldap_connect([string host [, int port [, string wallet [, string wallet_passwd [, int authmode]]]]])", "Connect to an LDAP server" ], "ldap_count_entries": [ "int ldap_count_entries(resource link, resource result)", "Count the number of entries in a search result" ], "ldap_delete": [ "bool ldap_delete(resource link, string dn)", "Delete an entry from a directory" ], "ldap_dn2ufn": [ "string ldap_dn2ufn(string dn)", "Convert DN to User Friendly Naming format" ], "ldap_err2str": [ "string ldap_err2str(int errno)", "Convert error number to error string" ], "ldap_errno": [ "int ldap_errno(resource link)", "Get the current ldap error number" ], "ldap_error": [ "string ldap_error(resource link)", "Get the current ldap error string" ], "ldap_explode_dn": [ "array ldap_explode_dn(string dn, int with_attrib)", "Splits DN into its component parts" ], "ldap_first_attribute": [ "string ldap_first_attribute(resource link, resource result_entry)", "Return first attribute" ], "ldap_first_entry": [ "resource ldap_first_entry(resource link, resource result)", "Return first result id" ], "ldap_first_reference": [ "resource ldap_first_reference(resource link, resource result)", "Return first reference" ], "ldap_free_result": [ "bool ldap_free_result(resource result)", "Free result memory" ], "ldap_get_attributes": [ "array ldap_get_attributes(resource link, resource result_entry)", "Get attributes from a search result entry" ], "ldap_get_dn": [ "string ldap_get_dn(resource link, resource result_entry)", "Get the DN of a result entry" ], "ldap_get_entries": [ "array ldap_get_entries(resource link, resource result)", "Get all result entries" ], "ldap_get_option": [ "bool ldap_get_option(resource link, int option, mixed retval)", "Get the current value of various session-wide parameters" ], "ldap_get_values_len": [ "array ldap_get_values_len(resource link, resource result_entry, string attribute)", "Get all values with lengths from a result entry" ], "ldap_list": [ "resource ldap_list(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])", "Single-level search" ], "ldap_mod_add": [ "bool ldap_mod_add(resource link, string dn, array entry)", "Add attribute values to current" ], "ldap_mod_del": [ "bool ldap_mod_del(resource link, string dn, array entry)", "Delete attribute values" ], "ldap_mod_replace": [ "bool ldap_mod_replace(resource link, string dn, array entry)", "Replace attribute values with new ones" ], "ldap_next_attribute": [ "string ldap_next_attribute(resource link, resource result_entry)", "Get the next attribute in result" ], "ldap_next_entry": [ "resource ldap_next_entry(resource link, resource result_entry)", "Get next result entry" ], "ldap_next_reference": [ "resource ldap_next_reference(resource link, resource reference_entry)", "Get next reference" ], "ldap_parse_reference": [ "bool ldap_parse_reference(resource link, resource reference_entry, array referrals)", "Extract information from reference entry" ], "ldap_parse_result": [ "bool ldap_parse_result(resource link, resource result, int errcode, string matcheddn, string errmsg, array referrals)", "Extract information from result" ], "ldap_read": [ "resource ldap_read(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])", "Read an entry" ], "ldap_rename": [ "bool ldap_rename(resource link, string dn, string newrdn, string newparent, bool deleteoldrdn);", "Modify the name of an entry" ], "ldap_sasl_bind": [ "bool ldap_sasl_bind(resource link [, string binddn [, string password [, string sasl_mech [, string sasl_realm [, string sasl_authc_id [, string sasl_authz_id [, string props]]]]]]])", "Bind to LDAP directory using SASL" ], "ldap_search": [ "resource ldap_search(resource|array link, string base_dn, string filter [, array attrs [, int attrsonly [, int sizelimit [, int timelimit [, int deref]]]]])", "Search LDAP tree under base_dn" ], "ldap_set_option": [ "bool ldap_set_option(resource link, int option, mixed newval)", "Set the value of various session-wide parameters" ], "ldap_set_rebind_proc": [ "bool ldap_set_rebind_proc(resource link, string callback)", "Set a callback function to do re-binds on referral chasing." ], "ldap_sort": [ "bool ldap_sort(resource link, resource result, string sortfilter)", "Sort LDAP result entries" ], "ldap_start_tls": [ "bool ldap_start_tls(resource link)", "Start TLS" ], "ldap_t61_to_8859": [ "string ldap_t61_to_8859(string value)", "Translate t61 characters to 8859 characters" ], "ldap_unbind": [ "bool ldap_unbind(resource link)", "Unbind from LDAP directory" ], "leak": [ "void leak(int num_bytes=3)", "Cause an intentional memory leak, for testing/debugging purposes" ], "levenshtein": [ "int levenshtein(string str1, string str2[, int cost_ins, int cost_rep, int cost_del])", "Calculate Levenshtein distance between two strings" ], "libxml_clear_errors": [ "void libxml_clear_errors()", "Clear last error from libxml" ], "libxml_disable_entity_loader": [ "bool libxml_disable_entity_loader([boolean disable])", "Disable/Enable ability to load external entities" ], "libxml_get_errors": [ "object libxml_get_errors()", "Retrieve array of errors" ], "libxml_get_last_error": [ "object libxml_get_last_error()", "Retrieve last error from libxml" ], "libxml_set_streams_context": [ "void libxml_set_streams_context(resource streams_context)", "Set the streams context for the next libxml document load or write" ], "libxml_use_internal_errors": [ "bool libxml_use_internal_errors([boolean use_errors])", "Disable libxml errors and allow user to fetch error information as needed" ], "link": [ "int link(string target, string link)", "Create a hard link" ], "linkinfo": [ "int linkinfo(string filename)", "Returns the st_dev field of the UNIX C stat structure describing the link" ], "litespeed_request_headers": [ "array litespeed_request_headers(void)", "Fetch all HTTP request headers" ], "litespeed_response_headers": [ "array litespeed_response_headers(void)", "Fetch all HTTP response headers" ], "locale_accept_from_http": [ "string locale_accept_from_http(string $http_accept)", null ], "locale_canonicalize": [ "static string locale_canonicalize(Locale $loc, string $locale)", "* @param string $locale The locale string to canonicalize" ], "locale_filter_matches": [ "boolean locale_filter_matches(string $langtag, string $locale[, bool $canonicalize])", "* Checks if a $langtag filter matches with $locale according to RFC 4647's basic filtering algorithm" ], "locale_get_all_variants": [ "static array locale_get_all_variants($locale)", "* gets an array containing the list of variants, or null" ], "locale_get_default": [ "static string locale_get_default( )", "Get default locale" ], "locale_get_keywords": [ "static array locale_get_keywords(string $locale) {", "* return an associative array containing keyword-value * pairs for this locale. The keys are keys to the array (doh!)" ], "locale_get_primary_language": [ "static string locale_get_primary_language($locale)", "* gets the primary language for the $locale" ], "locale_get_region": [ "static string locale_get_region($locale)", "* gets the region for the $locale" ], "locale_get_script": [ "static string locale_get_script($locale)", "* gets the script for the $locale" ], "locale_lookup": [ "string locale_lookup(array $langtag, string $locale[, bool $canonicalize[, string $default = null]])", "* Searchs the items in $langtag for the best match to the language * range" ], "locale_set_default": [ "static string locale_set_default( string $locale )", "Set default locale" ], "localeconv": [ "array localeconv(void)", "Returns numeric formatting information based on the current locale" ], "localtime": [ "array localtime([int timestamp [, bool associative_array]])", "Returns the results of the C system call localtime as an associative array if the associative_array argument is set to 1 other wise it is a regular array" ], "log": [ "float log(float number, [float base])", "Returns the natural logarithm of the number, or the base log if base is specified" ], "log10": [ "float log10(float number)", "Returns the base-10 logarithm of the number" ], "log1p": [ "float log1p(float number)", "Returns log(1 + number), computed in a way that accurate even when the value of number is close to zero" ], "long2ip": [ "string long2ip(int proper_address)", "Converts an (IPv4) Internet network address into a string in Internet standard dotted format" ], "lstat": [ "array lstat(string filename)", "Give information about a file or symbolic link" ], "ltrim": [ "string ltrim(string str [, string character_mask])", "Strips whitespace from the beginning of a string" ], "mail": [ "int mail(string to, string subject, string message [, string additional_headers [, string additional_parameters]])", "Send an email message" ], "max": [ "mixed max(mixed arg1 [, mixed arg2 [, mixed ...]])", "Return the highest value in an array or a series of arguments" ], "mb_check_encoding": [ "bool mb_check_encoding([string var[, string encoding]])", "Check if the string is valid for the specified encoding" ], "mb_convert_case": [ "string mb_convert_case(string sourcestring, int mode [, string encoding])", "Returns a case-folded version of sourcestring" ], "mb_convert_encoding": [ "string mb_convert_encoding(string str, string to-encoding [, mixed from-encoding])", "Returns converted string in desired encoding" ], "mb_convert_kana": [ "string mb_convert_kana(string str [, string option] [, string encoding])", "Conversion between full-width character and half-width character (Japanese)" ], "mb_convert_variables": [ "string mb_convert_variables(string to-encoding, mixed from-encoding, mixed vars [, ...])", "Converts the string resource in variables to desired encoding" ], "mb_decode_mimeheader": [ "string mb_decode_mimeheader(string string)", "Decodes the MIME \"encoded-word\" in the string" ], "mb_decode_numericentity": [ "string mb_decode_numericentity(string string, array convmap [, string encoding])", "Converts HTML numeric entities to character code" ], "mb_detect_encoding": [ "string mb_detect_encoding(string str [, mixed encoding_list [, bool strict]])", "Encodings of the given string is returned (as a string)" ], "mb_detect_order": [ "bool|array mb_detect_order([mixed encoding-list])", "Sets the current detect_order or Return the current detect_order as a array" ], "mb_encode_mimeheader": [ "string mb_encode_mimeheader(string str [, string charset [, string transfer-encoding [, string linefeed [, int indent]]]])", "Converts the string to MIME \"encoded-word\" in the format of =?charset?(B|Q)?encoded_string?=" ], "mb_encode_numericentity": [ "string mb_encode_numericentity(string string, array convmap [, string encoding])", "Converts specified characters to HTML numeric entities" ], "mb_encoding_aliases": [ "array mb_encoding_aliases(string encoding)", "Returns an array of the aliases of a given encoding name" ], "mb_ereg": [ "int mb_ereg(string pattern, string string [, array registers])", "Regular expression match for multibyte string" ], "mb_ereg_match": [ "bool mb_ereg_match(string pattern, string string [,string option])", "Regular expression match for multibyte string" ], "mb_ereg_replace": [ "string mb_ereg_replace(string pattern, string replacement, string string [, string option])", "Replace regular expression for multibyte string" ], "mb_ereg_search": [ "bool mb_ereg_search([string pattern[, string option]])", "Regular expression search for multibyte string" ], "mb_ereg_search_getpos": [ "int mb_ereg_search_getpos(void)", "Get search start position" ], "mb_ereg_search_getregs": [ "array mb_ereg_search_getregs(void)", "Get matched substring of the last time" ], "mb_ereg_search_init": [ "bool mb_ereg_search_init(string string [, string pattern[, string option]])", "Initialize string and regular expression for search." ], "mb_ereg_search_pos": [ "array mb_ereg_search_pos([string pattern[, string option]])", "Regular expression search for multibyte string" ], "mb_ereg_search_regs": [ "array mb_ereg_search_regs([string pattern[, string option]])", "Regular expression search for multibyte string" ], "mb_ereg_search_setpos": [ "bool mb_ereg_search_setpos(int position)", "Set search start position" ], "mb_eregi": [ "int mb_eregi(string pattern, string string [, array registers])", "Case-insensitive regular expression match for multibyte string" ], "mb_eregi_replace": [ "string mb_eregi_replace(string pattern, string replacement, string string)", "Case insensitive replace regular expression for multibyte string" ], "mb_get_info": [ "mixed mb_get_info([string type])", "Returns the current settings of mbstring" ], "mb_http_input": [ "mixed mb_http_input([string type])", "Returns the input encoding" ], "mb_http_output": [ "string mb_http_output([string encoding])", "Sets the current output_encoding or returns the current output_encoding as a string" ], "mb_internal_encoding": [ "string mb_internal_encoding([string encoding])", "Sets the current internal encoding or Returns the current internal encoding as a string" ], "mb_language": [ "string mb_language([string language])", "Sets the current language or Returns the current language as a string" ], "mb_list_encodings": [ "mixed mb_list_encodings()", "Returns an array of all supported entity encodings" ], "mb_output_handler": [ "string mb_output_handler(string contents, int status)", "Returns string in output buffer converted to the http_output encoding" ], "mb_parse_str": [ "bool mb_parse_str(string encoded_string [, array result])", "Parses GET/POST/COOKIE data and sets global variables" ], "mb_preferred_mime_name": [ "string mb_preferred_mime_name(string encoding)", "Return the preferred MIME name (charset) as a string" ], "mb_regex_encoding": [ "string mb_regex_encoding([string encoding])", "Returns the current encoding for regex as a string." ], "mb_regex_set_options": [ "string mb_regex_set_options([string options])", "Set or get the default options for mbregex functions" ], "mb_send_mail": [ "int mb_send_mail(string to, string subject, string message [, string additional_headers [, string additional_parameters]])", "* Sends an email message with MIME scheme" ], "mb_split": [ "array mb_split(string pattern, string string [, int limit])", "split multibyte string into array by regular expression" ], "mb_strcut": [ "string mb_strcut(string str, int start [, int length [, string encoding]])", "Returns part of a string" ], "mb_strimwidth": [ "string mb_strimwidth(string str, int start, int width [, string trimmarker [, string encoding]])", "Trim the string in terminal width" ], "mb_stripos": [ "int mb_stripos(string haystack, string needle [, int offset [, string encoding]])", "Finds position of first occurrence of a string within another, case insensitive" ], "mb_stristr": [ "string mb_stristr(string haystack, string needle[, bool part[, string encoding]])", "Finds first occurrence of a string within another, case insensitive" ], "mb_strlen": [ "int mb_strlen(string str [, string encoding])", "Get character numbers of a string" ], "mb_strpos": [ "int mb_strpos(string haystack, string needle [, int offset [, string encoding]])", "Find position of first occurrence of a string within another" ], "mb_strrchr": [ "string mb_strrchr(string haystack, string needle[, bool part[, string encoding]])", "Finds the last occurrence of a character in a string within another" ], "mb_strrichr": [ "string mb_strrichr(string haystack, string needle[, bool part[, string encoding]])", "Finds the last occurrence of a character in a string within another, case insensitive" ], "mb_strripos": [ "int mb_strripos(string haystack, string needle [, int offset [, string encoding]])", "Finds position of last occurrence of a string within another, case insensitive" ], "mb_strrpos": [ "int mb_strrpos(string haystack, string needle [, int offset [, string encoding]])", "Find position of last occurrence of a string within another" ], "mb_strstr": [ "string mb_strstr(string haystack, string needle[, bool part[, string encoding]])", "Finds first occurrence of a string within another" ], "mb_strtolower": [ "string mb_strtolower(string sourcestring [, string encoding])", "* Returns a lowercased version of sourcestring" ], "mb_strtoupper": [ "string mb_strtoupper(string sourcestring [, string encoding])", "* Returns a uppercased version of sourcestring" ], "mb_strwidth": [ "int mb_strwidth(string str [, string encoding])", "Gets terminal width of a string" ], "mb_substitute_character": [ "mixed mb_substitute_character([mixed substchar])", "Sets the current substitute_character or returns the current substitute_character" ], "mb_substr": [ "string mb_substr(string str, int start [, int length [, string encoding]])", "Returns part of a string" ], "mb_substr_count": [ "int mb_substr_count(string haystack, string needle [, string encoding])", "Count the number of substring occurrences" ], "mcrypt_cbc": [ "string mcrypt_cbc(int cipher, string key, string data, int mode, string iv)", "CBC crypt/decrypt data using key key with cipher cipher starting with iv" ], "mcrypt_cfb": [ "string mcrypt_cfb(int cipher, string key, string data, int mode, string iv)", "CFB crypt/decrypt data using key key with cipher cipher starting with iv" ], "mcrypt_create_iv": [ "string mcrypt_create_iv(int size, int source)", "Create an initialization vector (IV)" ], "mcrypt_decrypt": [ "string mcrypt_decrypt(string cipher, string key, string data, string mode, string iv)", "OFB crypt/decrypt data using key key with cipher cipher starting with iv" ], "mcrypt_ecb": [ "string mcrypt_ecb(int cipher, string key, string data, int mode, string iv)", "ECB crypt/decrypt data using key key with cipher cipher starting with iv" ], "mcrypt_enc_get_algorithms_name": [ "string mcrypt_enc_get_algorithms_name(resource td)", "Returns the name of the algorithm specified by the descriptor td" ], "mcrypt_enc_get_block_size": [ "int mcrypt_enc_get_block_size(resource td)", "Returns the block size of the cipher specified by the descriptor td" ], "mcrypt_enc_get_iv_size": [ "int mcrypt_enc_get_iv_size(resource td)", "Returns the size of the IV in bytes of the algorithm specified by the descriptor td" ], "mcrypt_enc_get_key_size": [ "int mcrypt_enc_get_key_size(resource td)", "Returns the maximum supported key size in bytes of the algorithm specified by the descriptor td" ], "mcrypt_enc_get_modes_name": [ "string mcrypt_enc_get_modes_name(resource td)", "Returns the name of the mode specified by the descriptor td" ], "mcrypt_enc_get_supported_key_sizes": [ "array mcrypt_enc_get_supported_key_sizes(resource td)", "This function decrypts the crypttext" ], "mcrypt_enc_is_block_algorithm": [ "bool mcrypt_enc_is_block_algorithm(resource td)", "Returns TRUE if the alrogithm is a block algorithms" ], "mcrypt_enc_is_block_algorithm_mode": [ "bool mcrypt_enc_is_block_algorithm_mode(resource td)", "Returns TRUE if the mode is for use with block algorithms" ], "mcrypt_enc_is_block_mode": [ "bool mcrypt_enc_is_block_mode(resource td)", "Returns TRUE if the mode outputs blocks" ], "mcrypt_enc_self_test": [ "int mcrypt_enc_self_test(resource td)", "This function runs the self test on the algorithm specified by the descriptor td" ], "mcrypt_encrypt": [ "string mcrypt_encrypt(string cipher, string key, string data, string mode, string iv)", "OFB crypt/decrypt data using key key with cipher cipher starting with iv" ], "mcrypt_generic": [ "string mcrypt_generic(resource td, string data)", "This function encrypts the plaintext" ], "mcrypt_generic_deinit": [ "bool mcrypt_generic_deinit(resource td)", "This function terminates encrypt specified by the descriptor td" ], "mcrypt_generic_init": [ "int mcrypt_generic_init(resource td, string key, string iv)", "This function initializes all buffers for the specific module" ], "mcrypt_get_block_size": [ "int mcrypt_get_block_size(string cipher, string module)", "Get the key size of cipher" ], "mcrypt_get_cipher_name": [ "string mcrypt_get_cipher_name(string cipher)", "Get the key size of cipher" ], "mcrypt_get_iv_size": [ "int mcrypt_get_iv_size(string cipher, string module)", "Get the IV size of cipher (Usually the same as the blocksize)" ], "mcrypt_get_key_size": [ "int mcrypt_get_key_size(string cipher, string module)", "Get the key size of cipher" ], "mcrypt_list_algorithms": [ "array mcrypt_list_algorithms([string lib_dir])", "List all algorithms in \"module_dir\"" ], "mcrypt_list_modes": [ "array mcrypt_list_modes([string lib_dir])", "List all modes \"module_dir\"" ], "mcrypt_module_close": [ "bool mcrypt_module_close(resource td)", "Free the descriptor td" ], "mcrypt_module_get_algo_block_size": [ "int mcrypt_module_get_algo_block_size(string algorithm [, string lib_dir])", "Returns the block size of the algorithm" ], "mcrypt_module_get_algo_key_size": [ "int mcrypt_module_get_algo_key_size(string algorithm [, string lib_dir])", "Returns the maximum supported key size of the algorithm" ], "mcrypt_module_get_supported_key_sizes": [ "array mcrypt_module_get_supported_key_sizes(string algorithm [, string lib_dir])", "This function decrypts the crypttext" ], "mcrypt_module_is_block_algorithm": [ "bool mcrypt_module_is_block_algorithm(string algorithm [, string lib_dir])", "Returns TRUE if the algorithm is a block algorithm" ], "mcrypt_module_is_block_algorithm_mode": [ "bool mcrypt_module_is_block_algorithm_mode(string mode [, string lib_dir])", "Returns TRUE if the mode is for use with block algorithms" ], "mcrypt_module_is_block_mode": [ "bool mcrypt_module_is_block_mode(string mode [, string lib_dir])", "Returns TRUE if the mode outputs blocks of bytes" ], "mcrypt_module_open": [ "resource mcrypt_module_open(string cipher, string cipher_directory, string mode, string mode_directory)", "Opens the module of the algorithm and the mode to be used" ], "mcrypt_module_self_test": [ "bool mcrypt_module_self_test(string algorithm [, string lib_dir])", "Does a self test of the module \"module\"" ], "mcrypt_ofb": [ "string mcrypt_ofb(int cipher, string key, string data, int mode, string iv)", "OFB crypt/decrypt data using key key with cipher cipher starting with iv" ], "md5": [ "string md5(string str, [ bool raw_output])", "Calculate the md5 hash of a string" ], "md5_file": [ "string md5_file(string filename [, bool raw_output])", "Calculate the md5 hash of given filename" ], "mdecrypt_generic": [ "string mdecrypt_generic(resource td, string data)", "This function decrypts the plaintext" ], "memory_get_peak_usage": [ "int memory_get_peak_usage([real_usage])", "Returns the peak allocated by PHP memory" ], "memory_get_usage": [ "int memory_get_usage([real_usage])", "Returns the allocated by PHP memory" ], "metaphone": [ "string metaphone(string text[, int phones])", "Break english phrases down into their phonemes" ], "method_exists": [ "bool method_exists(object object, string method)", "Checks if the class method exists" ], "mhash": [ "string mhash(int hash, string data [, string key])", "Hash data with hash" ], "mhash_count": [ "int mhash_count(void)", "Gets the number of available hashes" ], "mhash_get_block_size": [ "int mhash_get_block_size(int hash)", "Gets the block size of hash" ], "mhash_get_hash_name": [ "string mhash_get_hash_name(int hash)", "Gets the name of hash" ], "mhash_keygen_s2k": [ "string mhash_keygen_s2k(int hash, string input_password, string salt, int bytes)", "Generates a key using hash functions" ], "microtime": [ "mixed microtime([bool get_as_float])", "Returns either a string or a float containing the current time in seconds and microseconds" ], "mime_content_type": [ "string mime_content_type(string filename|resource stream)", "Return content-type for file" ], "min": [ "mixed min(mixed arg1 [, mixed arg2 [, mixed ...]])", "Return the lowest value in an array or a series of arguments" ], "mkdir": [ "bool mkdir(string pathname [, int mode [, bool recursive [, resource context]]])", "Create a directory" ], "mktime": [ "int mktime([int hour [, int min [, int sec [, int mon [, int day [, int year]]]]]])", "Get UNIX timestamp for a date" ], "money_format": [ "string money_format(string format , float value)", "Convert monetary value(s) to string" ], "move_uploaded_file": [ "bool move_uploaded_file(string path, string new_path)", "Move a file if and only if it was created by an upload" ], "msg_get_queue": [ "resource msg_get_queue(int key [, int perms])", "Attach to a message queue" ], "msg_queue_exists": [ "bool msg_queue_exists(int key)", "Check wether a message queue exists" ], "msg_receive": [ "mixed msg_receive(resource queue, int desiredmsgtype, int &msgtype, int maxsize, mixed message [, bool unserialize=true [, int flags=0 [, int errorcode]]])", "Send a message of type msgtype (must be > 0) to a message queue" ], "msg_remove_queue": [ "bool msg_remove_queue(resource queue)", "Destroy the queue" ], "msg_send": [ "bool msg_send(resource queue, int msgtype, mixed message [, bool serialize=true [, bool blocking=true [, int errorcode]]])", "Send a message of type msgtype (must be > 0) to a message queue" ], "msg_set_queue": [ "bool msg_set_queue(resource queue, array data)", "Set information for a message queue" ], "msg_stat_queue": [ "array msg_stat_queue(resource queue)", "Returns information about a message queue" ], "msgfmt_create": [ "MessageFormatter msgfmt_create( string $locale, string $pattern )", "* Create formatter." ], "msgfmt_format": [ "mixed msgfmt_format( MessageFormatter $nf, array $args )", "* Format a message." ], "msgfmt_format_message": [ "mixed msgfmt_format_message( string $locale, string $pattern, array $args )", "* Format a message." ], "msgfmt_get_error_code": [ "int msgfmt_get_error_code( MessageFormatter $nf )", "* Get formatter's last error code." ], "msgfmt_get_error_message": [ "string msgfmt_get_error_message( MessageFormatter $coll )", "* Get text description for formatter's last error code." ], "msgfmt_get_locale": [ "string msgfmt_get_locale(MessageFormatter $mf)", "* Get formatter locale." ], "msgfmt_get_pattern": [ "string msgfmt_get_pattern( MessageFormatter $mf )", "* Get formatter pattern." ], "msgfmt_parse": [ "array msgfmt_parse( MessageFormatter $nf, string $source )", "* Parse a message." ], "msgfmt_set_pattern": [ "bool msgfmt_set_pattern( MessageFormatter $mf, string $pattern )", "* Set formatter pattern." ], "mssql_bind": [ "bool mssql_bind(resource stmt, string param_name, mixed var, int type [, bool is_output [, bool is_null [, int maxlen]]])", "Adds a parameter to a stored procedure or a remote stored procedure" ], "mssql_close": [ "bool mssql_close([resource conn_id])", "Closes a connection to a MS-SQL server" ], "mssql_connect": [ "int mssql_connect([string servername [, string username [, string password [, bool new_link]]]])", "Establishes a connection to a MS-SQL server" ], "mssql_data_seek": [ "bool mssql_data_seek(resource result_id, int offset)", "Moves the internal row pointer of the MS-SQL result associated with the specified result identifier to pointer to the specified row number" ], "mssql_execute": [ "mixed mssql_execute(resource stmt [, bool skip_results = false])", "Executes a stored procedure on a MS-SQL server database" ], "mssql_fetch_array": [ "array mssql_fetch_array(resource result_id [, int result_type])", "Returns an associative array of the current row in the result set specified by result_id" ], "mssql_fetch_assoc": [ "array mssql_fetch_assoc(resource result_id)", "Returns an associative array of the current row in the result set specified by result_id" ], "mssql_fetch_batch": [ "int mssql_fetch_batch(resource result_index)", "Returns the next batch of records" ], "mssql_fetch_field": [ "object mssql_fetch_field(resource result_id [, int offset])", "Gets information about certain fields in a query result" ], "mssql_fetch_object": [ "object mssql_fetch_object(resource result_id)", "Returns a pseudo-object of the current row in the result set specified by result_id" ], "mssql_fetch_row": [ "array mssql_fetch_row(resource result_id)", "Returns an array of the current row in the result set specified by result_id" ], "mssql_field_length": [ "int mssql_field_length(resource result_id [, int offset])", "Get the length of a MS-SQL field" ], "mssql_field_name": [ "string mssql_field_name(resource result_id [, int offset])", "Returns the name of the field given by offset in the result set given by result_id" ], "mssql_field_seek": [ "bool mssql_field_seek(resource result_id, int offset)", "Seeks to the specified field offset" ], "mssql_field_type": [ "string mssql_field_type(resource result_id [, int offset])", "Returns the type of a field" ], "mssql_free_result": [ "bool mssql_free_result(resource result_index)", "Free a MS-SQL result index" ], "mssql_free_statement": [ "bool mssql_free_statement(resource result_index)", "Free a MS-SQL statement index" ], "mssql_get_last_message": [ "string mssql_get_last_message(void)", "Gets the last message from the MS-SQL server" ], "mssql_guid_string": [ "string mssql_guid_string(string binary [,bool short_format])", "Converts a 16 byte binary GUID to a string" ], "mssql_init": [ "int mssql_init(string sp_name [, resource conn_id])", "Initializes a stored procedure or a remote stored procedure" ], "mssql_min_error_severity": [ "void mssql_min_error_severity(int severity)", "Sets the lower error severity" ], "mssql_min_message_severity": [ "void mssql_min_message_severity(int severity)", "Sets the lower message severity" ], "mssql_next_result": [ "bool mssql_next_result(resource result_id)", "Move the internal result pointer to the next result" ], "mssql_num_fields": [ "int mssql_num_fields(resource mssql_result_index)", "Returns the number of fields fetched in from the result id specified" ], "mssql_num_rows": [ "int mssql_num_rows(resource mssql_result_index)", "Returns the number of rows fetched in from the result id specified" ], "mssql_pconnect": [ "int mssql_pconnect([string servername [, string username [, string password [, bool new_link]]]])", "Establishes a persistent connection to a MS-SQL server" ], "mssql_query": [ "resource mssql_query(string query [, resource conn_id [, int batch_size]])", "Perform an SQL query on a MS-SQL server database" ], "mssql_result": [ "string mssql_result(resource result_id, int row, mixed field)", "Returns the contents of one cell from a MS-SQL result set" ], "mssql_rows_affected": [ "int mssql_rows_affected(resource conn_id)", "Returns the number of records affected by the query" ], "mssql_select_db": [ "bool mssql_select_db(string database_name [, resource conn_id])", "Select a MS-SQL database" ], "mt_getrandmax": [ "int mt_getrandmax(void)", "Returns the maximum value a random number from Mersenne Twister can have" ], "mt_rand": [ "int mt_rand([int min, int max])", "Returns a random number from Mersenne Twister" ], "mt_srand": [ "void mt_srand([int seed])", "Seeds Mersenne Twister random number generator" ], "mysql_affected_rows": [ "int mysql_affected_rows([int link_identifier])", "Gets number of affected rows in previous MySQL operation" ], "mysql_client_encoding": [ "string mysql_client_encoding([int link_identifier])", "Returns the default character set for the current connection" ], "mysql_close": [ "bool mysql_close([int link_identifier])", "Close a MySQL connection" ], "mysql_connect": [ "resource mysql_connect([string hostname[:port][:/path/to/socket] [, string username [, string password [, bool new [, int flags]]]]])", "Opens a connection to a MySQL Server" ], "mysql_create_db": [ "bool mysql_create_db(string database_name [, int link_identifier])", "Create a MySQL database" ], "mysql_data_seek": [ "bool mysql_data_seek(resource result, int row_number)", "Move internal result pointer" ], "mysql_db_query": [ "resource mysql_db_query(string database_name, string query [, int link_identifier])", "Sends an SQL query to MySQL" ], "mysql_drop_db": [ "bool mysql_drop_db(string database_name [, int link_identifier])", "Drops (delete) a MySQL database" ], "mysql_errno": [ "int mysql_errno([int link_identifier])", "Returns the number of the error message from previous MySQL operation" ], "mysql_error": [ "string mysql_error([int link_identifier])", "Returns the text of the error message from previous MySQL operation" ], "mysql_escape_string": [ "string mysql_escape_string(string to_be_escaped)", "Escape string for mysql query" ], "mysql_fetch_array": [ "array mysql_fetch_array(resource result [, int result_type])", "Fetch a result row as an array (associative, numeric or both)" ], "mysql_fetch_assoc": [ "array mysql_fetch_assoc(resource result)", "Fetch a result row as an associative array" ], "mysql_fetch_field": [ "object mysql_fetch_field(resource result [, int field_offset])", "Gets column information from a result and return as an object" ], "mysql_fetch_lengths": [ "array mysql_fetch_lengths(resource result)", "Gets max data size of each column in a result" ], "mysql_fetch_object": [ "object mysql_fetch_object(resource result [, string class_name [, NULL|array ctor_params]])", "Fetch a result row as an object" ], "mysql_fetch_row": [ "array mysql_fetch_row(resource result)", "Gets a result row as an enumerated array" ], "mysql_field_flags": [ "string mysql_field_flags(resource result, int field_offset)", "Gets the flags associated with the specified field in a result" ], "mysql_field_len": [ "int mysql_field_len(resource result, int field_offset)", "Returns the length of the specified field" ], "mysql_field_name": [ "string mysql_field_name(resource result, int field_index)", "Gets the name of the specified field in a result" ], "mysql_field_seek": [ "bool mysql_field_seek(resource result, int field_offset)", "Sets result pointer to a specific field offset" ], "mysql_field_table": [ "string mysql_field_table(resource result, int field_offset)", "Gets name of the table the specified field is in" ], "mysql_field_type": [ "string mysql_field_type(resource result, int field_offset)", "Gets the type of the specified field in a result" ], "mysql_free_result": [ "bool mysql_free_result(resource result)", "Free result memory" ], "mysql_get_client_info": [ "string mysql_get_client_info(void)", "Returns a string that represents the client library version" ], "mysql_get_host_info": [ "string mysql_get_host_info([int link_identifier])", "Returns a string describing the type of connection in use, including the server host name" ], "mysql_get_proto_info": [ "int mysql_get_proto_info([int link_identifier])", "Returns the protocol version used by current connection" ], "mysql_get_server_info": [ "string mysql_get_server_info([int link_identifier])", "Returns a string that represents the server version number" ], "mysql_info": [ "string mysql_info([int link_identifier])", "Returns a string containing information about the most recent query" ], "mysql_insert_id": [ "int mysql_insert_id([int link_identifier])", "Gets the ID generated from the previous INSERT operation" ], "mysql_list_dbs": [ "resource mysql_list_dbs([int link_identifier])", "List databases available on a MySQL server" ], "mysql_list_fields": [ "resource mysql_list_fields(string database_name, string table_name [, int link_identifier])", "List MySQL result fields" ], "mysql_list_processes": [ "resource mysql_list_processes([int link_identifier])", "Returns a result set describing the current server threads" ], "mysql_list_tables": [ "resource mysql_list_tables(string database_name [, int link_identifier])", "List tables in a MySQL database" ], "mysql_num_fields": [ "int mysql_num_fields(resource result)", "Gets number of fields in a result" ], "mysql_num_rows": [ "int mysql_num_rows(resource result)", "Gets number of rows in a result" ], "mysql_pconnect": [ "resource mysql_pconnect([string hostname[:port][:/path/to/socket] [, string username [, string password [, int flags]]]])", "Opens a persistent connection to a MySQL Server" ], "mysql_ping": [ "bool mysql_ping([int link_identifier])", "Ping a server connection. If no connection then reconnect." ], "mysql_query": [ "resource mysql_query(string query [, int link_identifier])", "Sends an SQL query to MySQL" ], "mysql_real_escape_string": [ "string mysql_real_escape_string(string to_be_escaped [, int link_identifier])", "Escape special characters in a string for use in a SQL statement, taking into account the current charset of the connection" ], "mysql_result": [ "mixed mysql_result(resource result, int row [, mixed field])", "Gets result data" ], "mysql_select_db": [ "bool mysql_select_db(string database_name [, int link_identifier])", "Selects a MySQL database" ], "mysql_set_charset": [ "bool mysql_set_charset(string csname [, int link_identifier])", "sets client character set" ], "mysql_stat": [ "string mysql_stat([int link_identifier])", "Returns a string containing status information" ], "mysql_thread_id": [ "int mysql_thread_id([int link_identifier])", "Returns the thread id of current connection" ], "mysql_unbuffered_query": [ "resource mysql_unbuffered_query(string query [, int link_identifier])", "Sends an SQL query to MySQL, without fetching and buffering the result rows" ], "mysqli_affected_rows": [ "mixed mysqli_affected_rows(object link)", "Get number of affected rows in previous MySQL operation" ], "mysqli_autocommit": [ "bool mysqli_autocommit(object link, bool mode)", "Turn auto commit on or of" ], "mysqli_cache_stats": [ "array mysqli_cache_stats(void)", "Returns statistics about the zval cache" ], "mysqli_change_user": [ "bool mysqli_change_user(object link, string user, string password, string database)", "Change logged-in user of the active connection" ], "mysqli_character_set_name": [ "string mysqli_character_set_name(object link)", "Returns the name of the character set used for this connection" ], "mysqli_close": [ "bool mysqli_close(object link)", "Close connection" ], "mysqli_commit": [ "bool mysqli_commit(object link)", "Commit outstanding actions and close transaction" ], "mysqli_connect": [ "object mysqli_connect([string hostname [,string username [,string passwd [,string dbname [,int port [,string socket]]]]]])", "Open a connection to a mysql server" ], "mysqli_connect_errno": [ "int mysqli_connect_errno(void)", "Returns the numerical value of the error message from last connect command" ], "mysqli_connect_error": [ "string mysqli_connect_error(void)", "Returns the text of the error message from previous MySQL operation" ], "mysqli_data_seek": [ "bool mysqli_data_seek(object result, int offset)", "Move internal result pointer" ], "mysqli_debug": [ "void mysqli_debug(string debug)", "" ], "mysqli_dump_debug_info": [ "bool mysqli_dump_debug_info(object link)", "" ], "mysqli_embedded_server_end": [ "void mysqli_embedded_server_end(void)", "" ], "mysqli_embedded_server_start": [ "bool mysqli_embedded_server_start(bool start, array arguments, array groups)", "initialize and start embedded server" ], "mysqli_errno": [ "int mysqli_errno(object link)", "Returns the numerical value of the error message from previous MySQL operation" ], "mysqli_error": [ "string mysqli_error(object link)", "Returns the text of the error message from previous MySQL operation" ], "mysqli_fetch_all": [ "mixed mysqli_fetch_all (object result [,int resulttype])", "Fetches all result rows as an associative array, a numeric array, or both" ], "mysqli_fetch_array": [ "mixed mysqli_fetch_array (object result [,int resulttype])", "Fetch a result row as an associative array, a numeric array, or both" ], "mysqli_fetch_assoc": [ "mixed mysqli_fetch_assoc (object result)", "Fetch a result row as an associative array" ], "mysqli_fetch_field": [ "mixed mysqli_fetch_field (object result)", "Get column information from a result and return as an object" ], "mysqli_fetch_field_direct": [ "mixed mysqli_fetch_field_direct (object result, int offset)", "Fetch meta-data for a single field" ], "mysqli_fetch_fields": [ "mixed mysqli_fetch_fields (object result)", "Return array of objects containing field meta-data" ], "mysqli_fetch_lengths": [ "mixed mysqli_fetch_lengths (object result)", "Get the length of each output in a result" ], "mysqli_fetch_object": [ "mixed mysqli_fetch_object (object result [, string class_name [, NULL|array ctor_params]])", "Fetch a result row as an object" ], "mysqli_fetch_row": [ "array mysqli_fetch_row (object result)", "Get a result row as an enumerated array" ], "mysqli_field_count": [ "int mysqli_field_count(object link)", "Fetch the number of fields returned by the last query for the given link" ], "mysqli_field_seek": [ "int mysqli_field_seek(object result, int fieldnr)", "Set result pointer to a specified field offset" ], "mysqli_field_tell": [ "int mysqli_field_tell(object result)", "Get current field offset of result pointer" ], "mysqli_free_result": [ "void mysqli_free_result(object result)", "Free query result memory for the given result handle" ], "mysqli_get_charset": [ "object mysqli_get_charset(object link)", "returns a character set object" ], "mysqli_get_client_info": [ "string mysqli_get_client_info(void)", "Get MySQL client info" ], "mysqli_get_client_stats": [ "array mysqli_get_client_stats(void)", "Returns statistics about the zval cache" ], "mysqli_get_client_version": [ "int mysqli_get_client_version(void)", "Get MySQL client info" ], "mysqli_get_connection_stats": [ "array mysqli_get_connection_stats(void)", "Returns statistics about the zval cache" ], "mysqli_get_host_info": [ "string mysqli_get_host_info (object link)", "Get MySQL host info" ], "mysqli_get_proto_info": [ "int mysqli_get_proto_info(object link)", "Get MySQL protocol information" ], "mysqli_get_server_info": [ "string mysqli_get_server_info(object link)", "Get MySQL server info" ], "mysqli_get_server_version": [ "int mysqli_get_server_version(object link)", "Return the MySQL version for the server referenced by the given link" ], "mysqli_get_warnings": [ "object mysqli_get_warnings(object link) */", "PHP_FUNCTION(mysqli_get_warnings) { MY_MYSQL *mysql; zval *mysql_link; MYSQLI_RESOURCE *mysqli_resource; MYSQLI_WARNING *w; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"O\", &mysql_link, mysqli_link_class_entry) == FAILURE) { return; } MYSQLI_FETCH_RESOURCE(mysql, MY_MYSQL*, &mysql_link, \"mysqli_link\", MYSQLI_STATUS_VALID); if (mysql_warning_count(mysql->mysql)) { w = php_get_warnings(mysql->mysql TSRMLS_CC); } else { RETURN_FALSE; } mysqli_resource = (MYSQLI_RESOURCE *)ecalloc (1, sizeof(MYSQLI_RESOURCE)); mysqli_resource->ptr = mysqli_resource->info = (void *)w; mysqli_resource->status = MYSQLI_STATUS_VALID; MYSQLI_RETURN_RESOURCE(mysqli_resource, mysqli_warning_class_entry); } /* }}}" ], "mysqli_info": [ "string mysqli_info(object link)", "Get information about the most recent query" ], "mysqli_init": [ "resource mysqli_init(void)", "Initialize mysqli and return a resource for use with mysql_real_connect" ], "mysqli_insert_id": [ "mixed mysqli_insert_id(object link)", "Get the ID generated from the previous INSERT operation" ], "mysqli_kill": [ "bool mysqli_kill(object link, int processid)", "Kill a mysql process on the server" ], "mysqli_link_construct": [ "object mysqli_link_construct()", "" ], "mysqli_more_results": [ "bool mysqli_more_results(object link)", "check if there any more query results from a multi query" ], "mysqli_multi_query": [ "bool mysqli_multi_query(object link, string query)", "allows to execute multiple queries" ], "mysqli_next_result": [ "bool mysqli_next_result(object link)", "read next result from multi_query" ], "mysqli_num_fields": [ "int mysqli_num_fields(object result)", "Get number of fields in result" ], "mysqli_num_rows": [ "mixed mysqli_num_rows(object result)", "Get number of rows in result" ], "mysqli_options": [ "bool mysqli_options(object link, int flags, mixed values)", "Set options" ], "mysqli_ping": [ "bool mysqli_ping(object link)", "Ping a server connection or reconnect if there is no connection" ], "mysqli_poll": [ "int mysqli_poll(array read, array write, array error, long sec [, long usec])", "Poll connections" ], "mysqli_prepare": [ "mixed mysqli_prepare(object link, string query)", "Prepare a SQL statement for execution" ], "mysqli_query": [ "mixed mysqli_query(object link, string query [,int resultmode]) */", "PHP_FUNCTION(mysqli_query) { MY_MYSQL *mysql; zval *mysql_link; MYSQLI_RESOURCE *mysqli_resource; MYSQL_RES *result; char *query = NULL; unsigned int query_len; unsigned long resultmode = MYSQLI_STORE_RESULT; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"Os|l\", &mysql_link, mysqli_link_class_entry, &query, &query_len, &resultmode) == FAILURE) { return; } if (!query_len) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Empty query\"); RETURN_FALSE; } if ((resultmode & ~MYSQLI_ASYNC) != MYSQLI_USE_RESULT && (resultmode & ~MYSQLI_ASYNC) != MYSQLI_STORE_RESULT) { php_error_docref(NULL TSRMLS_CC, E_WARNING, \"Invalid value for resultmode\"); RETURN_FALSE; } MYSQLI_FETCH_RESOURCE(mysql, MY_MYSQL*, &mysql_link, \"mysqli_link\", MYSQLI_STATUS_VALID); MYSQLI_DISABLE_MQ; #ifdef MYSQLI_USE_MYSQLND if (resultmode & MYSQLI_ASYNC) { if (mysqli_async_query(mysql->mysql, query, query_len)) { MYSQLI_REPORT_MYSQL_ERROR(mysql->mysql); RETURN_FALSE; } mysql->async_result_fetch_type = resultmode & ~MYSQLI_ASYNC; RETURN_TRUE; } #endif if (mysql_real_query(mysql->mysql, query, query_len)) { MYSQLI_REPORT_MYSQL_ERROR(mysql->mysql); RETURN_FALSE; } if (!mysql_field_count(mysql->mysql)) { /* no result set - not a SELECT" ], "mysqli_real_connect": [ "bool mysqli_real_connect(object link [,string hostname [,string username [,string passwd [,string dbname [,int port [,string socket [,int flags]]]]]]])", "Open a connection to a mysql server" ], "mysqli_real_escape_string": [ "string mysqli_real_escape_string(object link, string escapestr)", "Escapes special characters in a string for use in a SQL statement, taking into account the current charset of the connection" ], "mysqli_real_query": [ "bool mysqli_real_query(object link, string query)", "Binary-safe version of mysql_query()" ], "mysqli_reap_async_query": [ "int mysqli_reap_async_query(object link)", "Poll connections" ], "mysqli_refresh": [ "bool mysqli_refresh(object link, long options)", "Flush tables or caches, or reset replication server information" ], "mysqli_report": [ "bool mysqli_report(int flags)", "sets report level" ], "mysqli_rollback": [ "bool mysqli_rollback(object link)", "Undo actions from current transaction" ], "mysqli_select_db": [ "bool mysqli_select_db(object link, string dbname)", "Select a MySQL database" ], "mysqli_set_charset": [ "bool mysqli_set_charset(object link, string csname)", "sets client character set" ], "mysqli_set_local_infile_default": [ "void mysqli_set_local_infile_default(object link)", "unsets user defined handler for load local infile command" ], "mysqli_set_local_infile_handler": [ "bool mysqli_set_local_infile_handler(object link, callback read_func)", "Set callback functions for LOAD DATA LOCAL INFILE" ], "mysqli_sqlstate": [ "string mysqli_sqlstate(object link)", "Returns the SQLSTATE error from previous MySQL operation" ], "mysqli_ssl_set": [ "bool mysqli_ssl_set(object link ,string key ,string cert ,string ca ,string capath ,string cipher])", "" ], "mysqli_stat": [ "mixed mysqli_stat(object link)", "Get current system status" ], "mysqli_stmt_affected_rows": [ "mixed mysqli_stmt_affected_rows(object stmt)", "Return the number of rows affected in the last query for the given link" ], "mysqli_stmt_attr_get": [ "int mysqli_stmt_attr_get(object stmt, long attr)", "" ], "mysqli_stmt_attr_set": [ "int mysqli_stmt_attr_set(object stmt, long attr, long mode)", "" ], "mysqli_stmt_bind_param": [ "bool mysqli_stmt_bind_param(object stmt, string types, mixed variable [,mixed,....])", "Bind variables to a prepared statement as parameters" ], "mysqli_stmt_bind_result": [ "bool mysqli_stmt_bind_result(object stmt, mixed var, [,mixed, ...])", "Bind variables to a prepared statement for result storage" ], "mysqli_stmt_close": [ "bool mysqli_stmt_close(object stmt)", "Close statement" ], "mysqli_stmt_data_seek": [ "void mysqli_stmt_data_seek(object stmt, int offset)", "Move internal result pointer" ], "mysqli_stmt_errno": [ "int mysqli_stmt_errno(object stmt)", "" ], "mysqli_stmt_error": [ "string mysqli_stmt_error(object stmt)", "" ], "mysqli_stmt_execute": [ "bool mysqli_stmt_execute(object stmt)", "Execute a prepared statement" ], "mysqli_stmt_fetch": [ "mixed mysqli_stmt_fetch(object stmt)", "Fetch results from a prepared statement into the bound variables" ], "mysqli_stmt_field_count": [ "int mysqli_stmt_field_count(object stmt) {", "Return the number of result columns for the given statement" ], "mysqli_stmt_free_result": [ "void mysqli_stmt_free_result(object stmt)", "Free stored result memory for the given statement handle" ], "mysqli_stmt_get_result": [ "object mysqli_stmt_get_result(object link)", "Buffer result set on client" ], "mysqli_stmt_get_warnings": [ "object mysqli_stmt_get_warnings(object link) */", "PHP_FUNCTION(mysqli_stmt_get_warnings) { MY_STMT *stmt; zval *stmt_link; MYSQLI_RESOURCE *mysqli_resource; MYSQLI_WARNING *w; if (zend_parse_method_parameters(ZEND_NUM_ARGS() TSRMLS_CC, getThis(), \"O\", &stmt_link, mysqli_stmt_class_entry) == FAILURE) { return; } MYSQLI_FETCH_RESOURCE(stmt, MY_STMT*, &stmt_link, \"mysqli_stmt\", MYSQLI_STATUS_VALID); if (mysqli_stmt_warning_count(stmt->stmt)) { w = php_get_warnings(mysqli_stmt_get_connection(stmt->stmt) TSRMLS_CC); } else { RETURN_FALSE; } mysqli_resource = (MYSQLI_RESOURCE *)ecalloc (1, sizeof(MYSQLI_RESOURCE)); mysqli_resource->ptr = mysqli_resource->info = (void *)w; mysqli_resource->status = MYSQLI_STATUS_VALID; MYSQLI_RETURN_RESOURCE(mysqli_resource, mysqli_warning_class_entry); } /* }}}" ], "mysqli_stmt_init": [ "mixed mysqli_stmt_init(object link)", "Initialize statement object" ], "mysqli_stmt_insert_id": [ "mixed mysqli_stmt_insert_id(object stmt)", "Get the ID generated from the previous INSERT operation" ], "mysqli_stmt_next_result": [ "bool mysqli_stmt_next_result(object link)", "read next result from multi_query" ], "mysqli_stmt_num_rows": [ "mixed mysqli_stmt_num_rows(object stmt)", "Return the number of rows in statements result set" ], "mysqli_stmt_param_count": [ "int mysqli_stmt_param_count(object stmt)", "Return the number of parameter for the given statement" ], "mysqli_stmt_prepare": [ "bool mysqli_stmt_prepare(object stmt, string query)", "prepare server side statement with query" ], "mysqli_stmt_reset": [ "bool mysqli_stmt_reset(object stmt)", "reset a prepared statement" ], "mysqli_stmt_result_metadata": [ "mixed mysqli_stmt_result_metadata(object stmt)", "return result set from statement" ], "mysqli_stmt_send_long_data": [ "bool mysqli_stmt_send_long_data(object stmt, int param_nr, string data)", "" ], "mysqli_stmt_sqlstate": [ "string mysqli_stmt_sqlstate(object stmt)", "" ], "mysqli_stmt_store_result": [ "bool mysqli_stmt_store_result(stmt)", "" ], "mysqli_store_result": [ "object mysqli_store_result(object link)", "Buffer result set on client" ], "mysqli_thread_id": [ "int mysqli_thread_id(object link)", "Return the current thread ID" ], "mysqli_thread_safe": [ "bool mysqli_thread_safe(void)", "Return whether thread safety is given or not" ], "mysqli_use_result": [ "mixed mysqli_use_result(object link)", "Directly retrieve query results - do not buffer results on client side" ], "mysqli_warning_count": [ "int mysqli_warning_count (object link)", "Return number of warnings from the last query for the given link" ], "natcasesort": [ "void natcasesort(array &array_arg)", "Sort an array using case-insensitive natural sort" ], "natsort": [ "void natsort(array &array_arg)", "Sort an array using natural sort" ], "next": [ "mixed next(array array_arg)", "Move array argument's internal pointer to the next element and return it" ], "ngettext": [ "string ngettext(string MSGID1, string MSGID2, int N)", "Plural version of gettext()" ], "nl2br": [ "string nl2br(string str [, bool is_xhtml])", "Converts newlines to HTML line breaks" ], "nl_langinfo": [ "string nl_langinfo(int item)", "Query language and locale information" ], "normalizer_is_normalize": [ "bool normalizer_is_normalize( string $input [, string $form = FORM_C] )", "* Test if a string is in a given normalization form." ], "normalizer_normalize": [ "string normalizer_normalize( string $input [, string $form = FORM_C] )", "* Normalize a string." ], "nsapi_request_headers": [ "array nsapi_request_headers(void)", "Get all headers from the request" ], "nsapi_response_headers": [ "array nsapi_response_headers(void)", "Get all headers from the response" ], "nsapi_virtual": [ "bool nsapi_virtual(string uri)", "Perform an NSAPI sub-request" ], "number_format": [ "string number_format(float number [, int num_decimal_places [, string dec_seperator, string thousands_seperator]])", "Formats a number with grouped thousands" ], "numfmt_create": [ "NumberFormatter numfmt_create( string $locale, int style[, string $pattern ] )", "* Create number formatter." ], "numfmt_format": [ "mixed numfmt_format( NumberFormatter $nf, mixed $num[, int type] )", "* Format a number." ], "numfmt_format_currency": [ "mixed numfmt_format_currency( NumberFormatter $nf, double $num, string $currency )", "* Format a number as currency." ], "numfmt_get_attribute": [ "mixed numfmt_get_attribute( NumberFormatter $nf, int $attr )", "* Get formatter attribute value." ], "numfmt_get_error_code": [ "int numfmt_get_error_code( NumberFormatter $nf )", "* Get formatter's last error code." ], "numfmt_get_error_message": [ "string numfmt_get_error_message( NumberFormatter $nf )", "* Get text description for formatter's last error code." ], "numfmt_get_locale": [ "string numfmt_get_locale( NumberFormatter $nf[, int type] )", "* Get formatter locale." ], "numfmt_get_pattern": [ "string numfmt_get_pattern( NumberFormatter $nf )", "* Get formatter pattern." ], "numfmt_get_symbol": [ "string numfmt_get_symbol( NumberFormatter $nf, int $attr )", "* Get formatter symbol value." ], "numfmt_get_text_attribute": [ "string numfmt_get_text_attribute( NumberFormatter $nf, int $attr )", "* Get formatter attribute value." ], "numfmt_parse": [ "mixed numfmt_parse( NumberFormatter $nf, string $str[, int $type, int &$position ])", "* Parse a number." ], "numfmt_parse_currency": [ "double numfmt_parse_currency( NumberFormatter $nf, string $str, string $&currency[, int $&position] )", "* Parse a number as currency." ], "numfmt_parse_message": [ "array numfmt_parse_message( string $locale, string $pattern, string $source )", "* Parse a message." ], "numfmt_set_attribute": [ "bool numfmt_set_attribute( NumberFormatter $nf, int $attr, mixed $value )", "* Get formatter attribute value." ], "numfmt_set_pattern": [ "bool numfmt_set_pattern( NumberFormatter $nf, string $pattern )", "* Set formatter pattern." ], "numfmt_set_symbol": [ "bool numfmt_set_symbol( NumberFormatter $nf, int $attr, string $symbol )", "* Set formatter symbol value." ], "numfmt_set_text_attribute": [ "bool numfmt_set_text_attribute( NumberFormatter $nf, int $attr, string $value )", "* Get formatter attribute value." ], "ob_clean": [ "bool ob_clean(void)", "Clean (delete) the current output buffer" ], "ob_end_clean": [ "bool ob_end_clean(void)", "Clean the output buffer, and delete current output buffer" ], "ob_end_flush": [ "bool ob_end_flush(void)", "Flush (send) the output buffer, and delete current output buffer" ], "ob_flush": [ "bool ob_flush(void)", "Flush (send) contents of the output buffer. The last buffer content is sent to next buffer" ], "ob_get_clean": [ "bool ob_get_clean(void)", "Get current buffer contents and delete current output buffer" ], "ob_get_contents": [ "string ob_get_contents(void)", "Return the contents of the output buffer" ], "ob_get_flush": [ "bool ob_get_flush(void)", "Get current buffer contents, flush (send) the output buffer, and delete current output buffer" ], "ob_get_length": [ "int ob_get_length(void)", "Return the length of the output buffer" ], "ob_get_level": [ "int ob_get_level(void)", "Return the nesting level of the output buffer" ], "ob_get_status": [ "false|array ob_get_status([bool full_status])", "Return the status of the active or all output buffers" ], "ob_gzhandler": [ "string ob_gzhandler(string str, int mode)", "Encode str based on accept-encoding setting - designed to be called from ob_start()" ], "ob_iconv_handler": [ "string ob_iconv_handler(string contents, int status)", "Returns str in output buffer converted to the iconv.output_encoding character set" ], "ob_implicit_flush": [ "void ob_implicit_flush([int flag])", "Turn implicit flush on/off and is equivalent to calling flush() after every output call" ], "ob_list_handlers": [ "false|array ob_list_handlers()", "* List all output_buffers in an array" ], "ob_start": [ "bool ob_start([ string|array user_function [, int chunk_size [, bool erase]]])", "Turn on Output Buffering (specifying an optional output handler)." ], "oci_bind_array_by_name": [ "bool oci_bind_array_by_name(resource stmt, string name, array &var, int max_table_length [, int max_item_length [, int type ]])", "Bind a PHP array to an Oracle PL/SQL type by name" ], "oci_bind_by_name": [ "bool oci_bind_by_name(resource stmt, string name, mixed &var, [, int maxlength [, int type]])", "Bind a PHP variable to an Oracle placeholder by name" ], "oci_cancel": [ "bool oci_cancel(resource stmt)", "Cancel reading from a cursor" ], "oci_close": [ "bool oci_close(resource connection)", "Disconnect from database" ], "oci_collection_append": [ "bool oci_collection_append(string value)", "Append an object to the collection" ], "oci_collection_assign": [ "bool oci_collection_assign(object from)", "Assign a collection from another existing collection" ], "oci_collection_element_assign": [ "bool oci_collection_element_assign(int index, string val)", "Assign element val to collection at index ndx" ], "oci_collection_element_get": [ "string oci_collection_element_get(int ndx)", "Retrieve the value at collection index ndx" ], "oci_collection_max": [ "int oci_collection_max()", "Return the max value of a collection. For a varray this is the maximum length of the array" ], "oci_collection_size": [ "int oci_collection_size()", "Return the size of a collection" ], "oci_collection_trim": [ "bool oci_collection_trim(int num)", "Trim num elements from the end of a collection" ], "oci_commit": [ "bool oci_commit(resource connection)", "Commit the current context" ], "oci_connect": [ "resource oci_connect(string user, string pass [, string db [, string charset [, int session_mode ]])", "Connect to an Oracle database and log on. Returns a new session." ], "oci_define_by_name": [ "bool oci_define_by_name(resource stmt, string name, mixed &var [, int type])", "Define a PHP variable to an Oracle column by name" ], "oci_error": [ "array oci_error([resource stmt|connection|global])", "Return the last error of stmt|connection|global. If no error happened returns false." ], "oci_execute": [ "bool oci_execute(resource stmt [, int mode])", "Execute a parsed statement" ], "oci_fetch": [ "bool oci_fetch(resource stmt)", "Prepare a new row of data for reading" ], "oci_fetch_all": [ "int oci_fetch_all(resource stmt, array &output[, int skip[, int maxrows[, int flags]]])", "Fetch all rows of result data into an array" ], "oci_fetch_array": [ "array oci_fetch_array( resource stmt [, int mode ])", "Fetch a result row as an array" ], "oci_fetch_assoc": [ "array oci_fetch_assoc( resource stmt )", "Fetch a result row as an associative array" ], "oci_fetch_object": [ "object oci_fetch_object( resource stmt )", "Fetch a result row as an object" ], "oci_fetch_row": [ "array oci_fetch_row( resource stmt )", "Fetch a result row as an enumerated array" ], "oci_field_is_null": [ "bool oci_field_is_null(resource stmt, int col)", "Tell whether a column is NULL" ], "oci_field_name": [ "string oci_field_name(resource stmt, int col)", "Tell the name of a column" ], "oci_field_precision": [ "int oci_field_precision(resource stmt, int col)", "Tell the precision of a column" ], "oci_field_scale": [ "int oci_field_scale(resource stmt, int col)", "Tell the scale of a column" ], "oci_field_size": [ "int oci_field_size(resource stmt, int col)", "Tell the maximum data size of a column" ], "oci_field_type": [ "mixed oci_field_type(resource stmt, int col)", "Tell the data type of a column" ], "oci_field_type_raw": [ "int oci_field_type_raw(resource stmt, int col)", "Tell the raw oracle data type of a column" ], "oci_free_collection": [ "bool oci_free_collection()", "Deletes collection object" ], "oci_free_descriptor": [ "bool oci_free_descriptor()", "Deletes large object description" ], "oci_free_statement": [ "bool oci_free_statement(resource stmt)", "Free all resources associated with a statement" ], "oci_internal_debug": [ "void oci_internal_debug(int onoff)", "Toggle internal debugging output for the OCI extension" ], "oci_lob_append": [ "bool oci_lob_append( object lob )", "Appends data from a LOB to another LOB" ], "oci_lob_close": [ "bool oci_lob_close()", "Closes lob descriptor" ], "oci_lob_copy": [ "bool oci_lob_copy( object lob_to, object lob_from [, int length ] )", "Copies data from a LOB to another LOB" ], "oci_lob_eof": [ "bool oci_lob_eof()", "Checks if EOF is reached" ], "oci_lob_erase": [ "int oci_lob_erase( [ int offset [, int length ] ] )", "Erases a specified portion of the internal LOB, starting at a specified offset" ], "oci_lob_export": [ "bool oci_lob_export([string filename [, int start [, int length]]])", "Writes a large object into a file" ], "oci_lob_flush": [ "bool oci_lob_flush( [ int flag ] )", "Flushes the LOB buffer" ], "oci_lob_import": [ "bool oci_lob_import( string filename )", "Loads file into a LOB" ], "oci_lob_is_equal": [ "bool oci_lob_is_equal( object lob1, object lob2 )", "Tests to see if two LOB/FILE locators are equal" ], "oci_lob_load": [ "string oci_lob_load()", "Loads a large object" ], "oci_lob_read": [ "string oci_lob_read( int length )", "Reads particular part of a large object" ], "oci_lob_rewind": [ "bool oci_lob_rewind()", "Rewind pointer of a LOB" ], "oci_lob_save": [ "bool oci_lob_save( string data [, int offset ])", "Saves a large object" ], "oci_lob_seek": [ "bool oci_lob_seek( int offset [, int whence ])", "Moves the pointer of a LOB" ], "oci_lob_size": [ "int oci_lob_size()", "Returns size of a large object" ], "oci_lob_tell": [ "int oci_lob_tell()", "Tells LOB pointer position" ], "oci_lob_truncate": [ "bool oci_lob_truncate( [ int length ])", "Truncates a LOB" ], "oci_lob_write": [ "int oci_lob_write( string string [, int length ])", "Writes data to current position of a LOB" ], "oci_lob_write_temporary": [ "bool oci_lob_write_temporary(string var [, int lob_type])", "Writes temporary blob" ], "oci_new_collection": [ "object oci_new_collection(resource connection, string tdo [, string schema])", "Initialize a new collection" ], "oci_new_connect": [ "resource oci_new_connect(string user, string pass [, string db])", "Connect to an Oracle database and log on. Returns a new session." ], "oci_new_cursor": [ "resource oci_new_cursor(resource connection)", "Return a new cursor (Statement-Handle) - use this to bind ref-cursors!" ], "oci_new_descriptor": [ "object oci_new_descriptor(resource connection [, int type])", "Initialize a new empty descriptor LOB/FILE (LOB is default)" ], "oci_num_fields": [ "int oci_num_fields(resource stmt)", "Return the number of result columns in a statement" ], "oci_num_rows": [ "int oci_num_rows(resource stmt)", "Return the row count of an OCI statement" ], "oci_parse": [ "resource oci_parse(resource connection, string query)", "Parse a query and return a statement" ], "oci_password_change": [ "bool oci_password_change(resource connection, string username, string old_password, string new_password)", "Changes the password of an account" ], "oci_pconnect": [ "resource oci_pconnect(string user, string pass [, string db [, string charset ]])", "Connect to an Oracle database using a persistent connection and log on. Returns a new session." ], "oci_result": [ "string oci_result(resource stmt, mixed column)", "Return a single column of result data" ], "oci_rollback": [ "bool oci_rollback(resource connection)", "Rollback the current context" ], "oci_server_version": [ "string oci_server_version(resource connection)", "Return a string containing server version information" ], "oci_set_action": [ "bool oci_set_action(resource connection, string value)", "Sets the action attribute on the connection" ], "oci_set_client_identifier": [ "bool oci_set_client_identifier(resource connection, string value)", "Sets the client identifier attribute on the connection" ], "oci_set_client_info": [ "bool oci_set_client_info(resource connection, string value)", "Sets the client info attribute on the connection" ], "oci_set_edition": [ "bool oci_set_edition(string value)", "Sets the edition attribute for all subsequent connections created" ], "oci_set_module_name": [ "bool oci_set_module_name(resource connection, string value)", "Sets the module attribute on the connection" ], "oci_set_prefetch": [ "bool oci_set_prefetch(resource stmt, int prefetch_rows)", "Sets the number of rows to be prefetched on execute to prefetch_rows for stmt" ], "oci_statement_type": [ "string oci_statement_type(resource stmt)", "Return the query type of an OCI statement" ], "ocifetchinto": [ "int ocifetchinto(resource stmt, array &output [, int mode])", "Fetch a row of result data into an array" ], "ocigetbufferinglob": [ "bool ocigetbufferinglob()", "Returns current state of buffering for a LOB" ], "ocisetbufferinglob": [ "bool ocisetbufferinglob( boolean flag )", "Enables/disables buffering for a LOB" ], "octdec": [ "int octdec(string octal_number)", "Returns the decimal equivalent of an octal string" ], "odbc_autocommit": [ "mixed odbc_autocommit(resource connection_id [, int OnOff])", "Toggle autocommit mode or get status" ], "odbc_binmode": [ "bool odbc_binmode(int result_id, int mode)", "Handle binary column data" ], "odbc_close": [ "void odbc_close(resource connection_id)", "Close an ODBC connection" ], "odbc_close_all": [ "void odbc_close_all(void)", "Close all ODBC connections" ], "odbc_columnprivileges": [ "resource odbc_columnprivileges(resource connection_id, string catalog, string schema, string table, string column)", "Returns a result identifier that can be used to fetch a list of columns and associated privileges for the specified table" ], "odbc_columns": [ "resource odbc_columns(resource connection_id [, string qualifier [, string owner [, string table_name [, string column_name]]]])", "Returns a result identifier that can be used to fetch a list of column names in specified tables" ], "odbc_commit": [ "bool odbc_commit(resource connection_id)", "Commit an ODBC transaction" ], "odbc_connect": [ "resource odbc_connect(string DSN, string user, string password [, int cursor_option])", "Connect to a datasource" ], "odbc_cursor": [ "string odbc_cursor(resource result_id)", "Get cursor name" ], "odbc_data_source": [ "array odbc_data_source(resource connection_id, int fetch_type)", "Return information about the currently connected data source" ], "odbc_error": [ "string odbc_error([resource connection_id])", "Get the last error code" ], "odbc_errormsg": [ "string odbc_errormsg([resource connection_id])", "Get the last error message" ], "odbc_exec": [ "resource odbc_exec(resource connection_id, string query [, int flags])", "Prepare and execute an SQL statement" ], "odbc_execute": [ "bool odbc_execute(resource result_id [, array parameters_array])", "Execute a prepared statement" ], "odbc_fetch_array": [ "array odbc_fetch_array(int result [, int rownumber])", "Fetch a result row as an associative array" ], "odbc_fetch_into": [ "int odbc_fetch_into(resource result_id, array &result_array, [, int rownumber])", "Fetch one result row into an array" ], "odbc_fetch_object": [ "object odbc_fetch_object(int result [, int rownumber])", "Fetch a result row as an object" ], "odbc_fetch_row": [ "bool odbc_fetch_row(resource result_id [, int row_number])", "Fetch a row" ], "odbc_field_len": [ "int odbc_field_len(resource result_id, int field_number)", "Get the length (precision) of a column" ], "odbc_field_name": [ "string odbc_field_name(resource result_id, int field_number)", "Get a column name" ], "odbc_field_num": [ "int odbc_field_num(resource result_id, string field_name)", "Return column number" ], "odbc_field_scale": [ "int odbc_field_scale(resource result_id, int field_number)", "Get the scale of a column" ], "odbc_field_type": [ "string odbc_field_type(resource result_id, int field_number)", "Get the datatype of a column" ], "odbc_foreignkeys": [ "resource odbc_foreignkeys(resource connection_id, string pk_qualifier, string pk_owner, string pk_table, string fk_qualifier, string fk_owner, string fk_table)", "Returns a result identifier to either a list of foreign keys in the specified table or a list of foreign keys in other tables that refer to the primary key in the specified table" ], "odbc_free_result": [ "bool odbc_free_result(resource result_id)", "Free resources associated with a result" ], "odbc_gettypeinfo": [ "resource odbc_gettypeinfo(resource connection_id [, int data_type])", "Returns a result identifier containing information about data types supported by the data source" ], "odbc_longreadlen": [ "bool odbc_longreadlen(int result_id, int length)", "Handle LONG columns" ], "odbc_next_result": [ "bool odbc_next_result(resource result_id)", "Checks if multiple results are avaiable" ], "odbc_num_fields": [ "int odbc_num_fields(resource result_id)", "Get number of columns in a result" ], "odbc_num_rows": [ "int odbc_num_rows(resource result_id)", "Get number of rows in a result" ], "odbc_pconnect": [ "resource odbc_pconnect(string DSN, string user, string password [, int cursor_option])", "Establish a persistent connection to a datasource" ], "odbc_prepare": [ "resource odbc_prepare(resource connection_id, string query)", "Prepares a statement for execution" ], "odbc_primarykeys": [ "resource odbc_primarykeys(resource connection_id, string qualifier, string owner, string table)", "Returns a result identifier listing the column names that comprise the primary key for a table" ], "odbc_procedurecolumns": [ "resource odbc_procedurecolumns(resource connection_id [, string qualifier, string owner, string proc, string column])", "Returns a result identifier containing the list of input and output parameters, as well as the columns that make up the result set for the specified procedures" ], "odbc_procedures": [ "resource odbc_procedures(resource connection_id [, string qualifier, string owner, string name])", "Returns a result identifier containg the list of procedure names in a datasource" ], "odbc_result": [ "mixed odbc_result(resource result_id, mixed field)", "Get result data" ], "odbc_result_all": [ "int odbc_result_all(resource result_id [, string format])", "Print result as HTML table" ], "odbc_rollback": [ "bool odbc_rollback(resource connection_id)", "Rollback a transaction" ], "odbc_setoption": [ "bool odbc_setoption(resource conn_id|result_id, int which, int option, int value)", "Sets connection or statement options" ], "odbc_specialcolumns": [ "resource odbc_specialcolumns(resource connection_id, int type, string qualifier, string owner, string table, int scope, int nullable)", "Returns a result identifier containing either the optimal set of columns that uniquely identifies a row in the table or columns that are automatically updated when any value in the row is updated by a transaction" ], "odbc_statistics": [ "resource odbc_statistics(resource connection_id, string qualifier, string owner, string name, int unique, int accuracy)", "Returns a result identifier that contains statistics about a single table and the indexes associated with the table" ], "odbc_tableprivileges": [ "resource odbc_tableprivileges(resource connection_id, string qualifier, string owner, string name)", "Returns a result identifier containing a list of tables and the privileges associated with each table" ], "odbc_tables": [ "resource odbc_tables(resource connection_id [, string qualifier [, string owner [, string name [, string table_types]]]])", "Call the SQLTables function" ], "opendir": [ "mixed opendir(string path[, resource context])", "Open a directory and return a dir_handle" ], "openlog": [ "bool openlog(string ident, int option, int facility)", "Open connection to system logger" ], "openssl_csr_export": [ "bool openssl_csr_export(resource csr, string &out [, bool notext=true])", "Exports a CSR to file or a var" ], "openssl_csr_export_to_file": [ "bool openssl_csr_export_to_file(resource csr, string outfilename [, bool notext=true])", "Exports a CSR to file" ], "openssl_csr_get_public_key": [ "mixed openssl_csr_get_public_key(mixed csr)", "Returns the subject of a CERT or FALSE on error" ], "openssl_csr_get_subject": [ "mixed openssl_csr_get_subject(mixed csr)", "Returns the subject of a CERT or FALSE on error" ], "openssl_csr_new": [ "bool openssl_csr_new(array dn, resource &privkey [, array configargs [, array extraattribs]])", "Generates a privkey and CSR" ], "openssl_csr_sign": [ "resource openssl_csr_sign(mixed csr, mixed x509, mixed priv_key, long days [, array config_args [, long serial]])", "Signs a cert with another CERT" ], "openssl_decrypt": [ "string openssl_decrypt(string data, string method, string password [, bool raw_input=false])", "Takes raw or base64 encoded string and dectupt it using given method and key" ], "openssl_dh_compute_key": [ "string openssl_dh_compute_key(string pub_key, resource dh_key)", "Computes shared sicret for public value of remote DH key and local DH key" ], "openssl_digest": [ "string openssl_digest(string data, string method [, bool raw_output=false])", "Computes digest hash value for given data using given method, returns raw or binhex encoded string" ], "openssl_encrypt": [ "string openssl_encrypt(string data, string method, string password [, bool raw_output=false])", "Encrypts given data with given method and key, returns raw or base64 encoded string" ], "openssl_error_string": [ "mixed openssl_error_string(void)", "Returns a description of the last error, and alters the index of the error messages. Returns false when the are no more messages" ], "openssl_get_cipher_methods": [ "array openssl_get_cipher_methods([bool aliases = false])", "Return array of available cipher methods" ], "openssl_get_md_methods": [ "array openssl_get_md_methods([bool aliases = false])", "Return array of available digest methods" ], "openssl_open": [ "bool openssl_open(string data, &string opendata, string ekey, mixed privkey)", "Opens data" ], "openssl_pkcs12_export": [ "bool openssl_pkcs12_export(mixed x509, string &out, mixed priv_key, string pass[, array args])", "Creates and exports a PKCS12 to a var" ], "openssl_pkcs12_export_to_file": [ "bool openssl_pkcs12_export_to_file(mixed x509, string filename, mixed priv_key, string pass[, array args])", "Creates and exports a PKCS to file" ], "openssl_pkcs12_read": [ "bool openssl_pkcs12_read(string PKCS12, array &certs, string pass)", "Parses a PKCS12 to an array" ], "openssl_pkcs7_decrypt": [ "bool openssl_pkcs7_decrypt(string infilename, string outfilename, mixed recipcert [, mixed recipkey])", "Decrypts the S/MIME message in the file name infilename and output the results to the file name outfilename. recipcert is a CERT for one of the recipients. recipkey specifies the private key matching recipcert, if recipcert does not include the key" ], "openssl_pkcs7_encrypt": [ "bool openssl_pkcs7_encrypt(string infile, string outfile, mixed recipcerts, array headers [, long flags [, long cipher]])", "Encrypts the message in the file named infile with the certificates in recipcerts and output the result to the file named outfile" ], "openssl_pkcs7_sign": [ "bool openssl_pkcs7_sign(string infile, string outfile, mixed signcert, mixed signkey, array headers [, long flags [, string extracertsfilename]])", "Signs the MIME message in the file named infile with signcert/signkey and output the result to file name outfile. headers lists plain text headers to exclude from the signed portion of the message, and should include to, from and subject as a minimum" ], "openssl_pkcs7_verify": [ "bool openssl_pkcs7_verify(string filename, long flags [, string signerscerts [, array cainfo [, string extracerts [, string content]]]])", "Verifys that the data block is intact, the signer is who they say they are, and returns the CERTs of the signers" ], "openssl_pkey_export": [ "bool openssl_pkey_export(mixed key, &mixed out [, string passphrase [, array config_args]])", "Gets an exportable representation of a key into a string or file" ], "openssl_pkey_export_to_file": [ "bool openssl_pkey_export_to_file(mixed key, string outfilename [, string passphrase, array config_args)", "Gets an exportable representation of a key into a file" ], "openssl_pkey_free": [ "void openssl_pkey_free(int key)", "Frees a key" ], "openssl_pkey_get_details": [ "resource openssl_pkey_get_details(resource key)", "returns an array with the key details (bits, pkey, type)" ], "openssl_pkey_get_private": [ "int openssl_pkey_get_private(string key [, string passphrase])", "Gets private keys" ], "openssl_pkey_get_public": [ "int openssl_pkey_get_public(mixed cert)", "Gets public key from X.509 certificate" ], "openssl_pkey_new": [ "resource openssl_pkey_new([array configargs])", "Generates a new private key" ], "openssl_private_decrypt": [ "bool openssl_private_decrypt(string data, string &decrypted, mixed key [, int padding])", "Decrypts data with private key" ], "openssl_private_encrypt": [ "bool openssl_private_encrypt(string data, string &crypted, mixed key [, int padding])", "Encrypts data with private key" ], "openssl_public_decrypt": [ "bool openssl_public_decrypt(string data, string &crypted, resource key [, int padding])", "Decrypts data with public key" ], "openssl_public_encrypt": [ "bool openssl_public_encrypt(string data, string &crypted, mixed key [, int padding])", "Encrypts data with public key" ], "openssl_random_pseudo_bytes": [ "string openssl_random_pseudo_bytes(integer length [, &bool returned_strong_result])", "Returns a string of the length specified filled with random pseudo bytes" ], "openssl_seal": [ "int openssl_seal(string data, &string sealdata, &array ekeys, array pubkeys)", "Seals data" ], "openssl_sign": [ "bool openssl_sign(string data, &string signature, mixed key[, mixed method])", "Signs data" ], "openssl_verify": [ "int openssl_verify(string data, string signature, mixed key[, mixed method])", "Verifys data" ], "openssl_x509_check_private_key": [ "bool openssl_x509_check_private_key(mixed cert, mixed key)", "Checks if a private key corresponds to a CERT" ], "openssl_x509_checkpurpose": [ "int openssl_x509_checkpurpose(mixed x509cert, int purpose, array cainfo [, string untrustedfile])", "Checks the CERT to see if it can be used for the purpose in purpose. cainfo holds information about trusted CAs" ], "openssl_x509_export": [ "bool openssl_x509_export(mixed x509, string &out [, bool notext = true])", "Exports a CERT to file or a var" ], "openssl_x509_export_to_file": [ "bool openssl_x509_export_to_file(mixed x509, string outfilename [, bool notext = true])", "Exports a CERT to file or a var" ], "openssl_x509_free": [ "void openssl_x509_free(resource x509)", "Frees X.509 certificates" ], "openssl_x509_parse": [ "array openssl_x509_parse(mixed x509 [, bool shortnames=true])", "Returns an array of the fields/values of the CERT" ], "openssl_x509_read": [ "resource openssl_x509_read(mixed cert)", "Reads X.509 certificates" ], "ord": [ "int ord(string character)", "Returns ASCII value of character" ], "output_add_rewrite_var": [ "bool output_add_rewrite_var(string name, string value)", "Add URL rewriter values" ], "output_reset_rewrite_vars": [ "bool output_reset_rewrite_vars(void)", "Reset(clear) URL rewriter values" ], "pack": [ "string pack(string format, mixed arg1 [, mixed arg2 [, mixed ...]])", "Takes one or more arguments and packs them into a binary string according to the format argument" ], "parse_ini_file": [ "array parse_ini_file(string filename [, bool process_sections [, int scanner_mode]])", "Parse configuration file" ], "parse_ini_string": [ "array parse_ini_string(string ini_string [, bool process_sections [, int scanner_mode]])", "Parse configuration string" ], "parse_locale": [ "static array parse_locale($locale)", "* parses a locale-id into an array the different parts of it" ], "parse_str": [ "void parse_str(string encoded_string [, array result])", "Parses GET/POST/COOKIE data and sets global variables" ], "parse_url": [ "mixed parse_url(string url, [int url_component])", "Parse a URL and return its components" ], "passthru": [ "void passthru(string command [, int &return_value])", "Execute an external program and display raw output" ], "pathinfo": [ "array pathinfo(string path[, int options])", "Returns information about a certain string" ], "pclose": [ "int pclose(resource fp)", "Close a file pointer opened by popen()" ], "pcnlt_sigwaitinfo": [ "int pcnlt_sigwaitinfo(array set[, array &siginfo])", "Synchronously wait for queued signals" ], "pcntl_alarm": [ "int pcntl_alarm(int seconds)", "Set an alarm clock for delivery of a signal" ], "pcntl_exec": [ "bool pcntl_exec(string path [, array args [, array envs]])", "Executes specified program in current process space as defined by exec(2)" ], "pcntl_fork": [ "int pcntl_fork(void)", "Forks the currently running process following the same behavior as the UNIX fork() system call" ], "pcntl_getpriority": [ "int pcntl_getpriority([int pid [, int process_identifier]])", "Get the priority of any process" ], "pcntl_setpriority": [ "bool pcntl_setpriority(int priority [, int pid [, int process_identifier]])", "Change the priority of any process" ], "pcntl_signal": [ "bool pcntl_signal(int signo, callback handle [, bool restart_syscalls])", "Assigns a system signal handler to a PHP function" ], "pcntl_signal_dispatch": [ "bool pcntl_signal_dispatch()", "Dispatch signals to signal handlers" ], "pcntl_sigprocmask": [ "bool pcntl_sigprocmask(int how, array set[, array &oldset])", "Examine and change blocked signals" ], "pcntl_sigtimedwait": [ "int pcntl_sigtimedwait(array set[, array &siginfo[, int seconds[, int nanoseconds]]])", "Wait for queued signals" ], "pcntl_wait": [ "int pcntl_wait(int &status)", "Waits on or returns the status of a forked child as defined by the waitpid() system call" ], "pcntl_waitpid": [ "int pcntl_waitpid(int pid, int &status, int options)", "Waits on or returns the status of a forked child as defined by the waitpid() system call" ], "pcntl_wexitstatus": [ "int pcntl_wexitstatus(int status)", "Returns the status code of a child's exit" ], "pcntl_wifexited": [ "bool pcntl_wifexited(int status)", "Returns true if the child status code represents a successful exit" ], "pcntl_wifsignaled": [ "bool pcntl_wifsignaled(int status)", "Returns true if the child status code represents a process that was terminated due to a signal" ], "pcntl_wifstopped": [ "bool pcntl_wifstopped(int status)", "Returns true if the child status code represents a stopped process (WUNTRACED must have been used with waitpid)" ], "pcntl_wstopsig": [ "int pcntl_wstopsig(int status)", "Returns the number of the signal that caused the process to stop who's status code is passed" ], "pcntl_wtermsig": [ "int pcntl_wtermsig(int status)", "Returns the number of the signal that terminated the process who's status code is passed" ], "pdo_drivers": [ "array pdo_drivers()", "Return array of available PDO drivers" ], "pfsockopen": [ "resource pfsockopen(string hostname, int port [, int errno [, string errstr [, float timeout]]])", "Open persistent Internet or Unix domain socket connection" ], "pg_affected_rows": [ "int pg_affected_rows(resource result)", "Returns the number of affected tuples" ], "pg_cancel_query": [ "bool pg_cancel_query(resource connection)", "Cancel request" ], "pg_client_encoding": [ "string pg_client_encoding([resource connection])", "Get the current client encoding" ], "pg_close": [ "bool pg_close([resource connection])", "Close a PostgreSQL connection" ], "pg_connect": [ "resource pg_connect(string connection_string[, int connect_type] | [string host, string port [, string options [, string tty,]]] string database)", "Open a PostgreSQL connection" ], "pg_connection_busy": [ "bool pg_connection_busy(resource connection)", "Get connection is busy or not" ], "pg_connection_reset": [ "bool pg_connection_reset(resource connection)", "Reset connection (reconnect)" ], "pg_connection_status": [ "int pg_connection_status(resource connnection)", "Get connection status" ], "pg_convert": [ "array pg_convert(resource db, string table, array values[, int options])", "Check and convert values for PostgreSQL SQL statement" ], "pg_copy_from": [ "bool pg_copy_from(resource connection, string table_name , array rows [, string delimiter [, string null_as]])", "Copy table from array" ], "pg_copy_to": [ "array pg_copy_to(resource connection, string table_name [, string delimiter [, string null_as]])", "Copy table to array" ], "pg_dbname": [ "string pg_dbname([resource connection])", "Get the database name" ], "pg_delete": [ "mixed pg_delete(resource db, string table, array ids[, int options])", "Delete records has ids (id=>value)" ], "pg_end_copy": [ "bool pg_end_copy([resource connection])", "Sync with backend. Completes the Copy command" ], "pg_escape_bytea": [ "string pg_escape_bytea([resource connection,] string data)", "Escape binary for bytea type" ], "pg_escape_string": [ "string pg_escape_string([resource connection,] string data)", "Escape string for text/char type" ], "pg_execute": [ "resource pg_execute([resource connection,] string stmtname, array params)", "Execute a prepared query" ], "pg_fetch_all": [ "array pg_fetch_all(resource result)", "Fetch all rows into array" ], "pg_fetch_all_columns": [ "array pg_fetch_all_columns(resource result [, int column_number])", "Fetch all rows into array" ], "pg_fetch_array": [ "array pg_fetch_array(resource result [, int row [, int result_type]])", "Fetch a row as an array" ], "pg_fetch_assoc": [ "array pg_fetch_assoc(resource result [, int row])", "Fetch a row as an assoc array" ], "pg_fetch_object": [ "object pg_fetch_object(resource result [, int row [, string class_name [, NULL|array ctor_params]]])", "Fetch a row as an object" ], "pg_fetch_result": [ "mixed pg_fetch_result(resource result, [int row_number,] mixed field_name)", "Returns values from a result identifier" ], "pg_fetch_row": [ "array pg_fetch_row(resource result [, int row [, int result_type]])", "Get a row as an enumerated array" ], "pg_field_is_null": [ "int pg_field_is_null(resource result, [int row,] mixed field_name_or_number)", "Test if a field is NULL" ], "pg_field_name": [ "string pg_field_name(resource result, int field_number)", "Returns the name of the field" ], "pg_field_num": [ "int pg_field_num(resource result, string field_name)", "Returns the field number of the named field" ], "pg_field_prtlen": [ "int pg_field_prtlen(resource result, [int row,] mixed field_name_or_number)", "Returns the printed length" ], "pg_field_size": [ "int pg_field_size(resource result, int field_number)", "Returns the internal size of the field" ], "pg_field_table": [ "mixed pg_field_table(resource result, int field_number[, bool oid_only])", "Returns the name of the table field belongs to, or table's oid if oid_only is true" ], "pg_field_type": [ "string pg_field_type(resource result, int field_number)", "Returns the type name for the given field" ], "pg_field_type_oid": [ "string pg_field_type_oid(resource result, int field_number)", "Returns the type oid for the given field" ], "pg_free_result": [ "bool pg_free_result(resource result)", "Free result memory" ], "pg_get_notify": [ "array pg_get_notify([resource connection[, result_type]])", "Get asynchronous notification" ], "pg_get_pid": [ "int pg_get_pid([resource connection)", "Get backend(server) pid" ], "pg_get_result": [ "resource pg_get_result(resource connection)", "Get asynchronous query result" ], "pg_host": [ "string pg_host([resource connection])", "Returns the host name associated with the connection" ], "pg_insert": [ "mixed pg_insert(resource db, string table, array values[, int options])", "Insert values (filed=>value) to table" ], "pg_last_error": [ "string pg_last_error([resource connection])", "Get the error message string" ], "pg_last_notice": [ "string pg_last_notice(resource connection)", "Returns the last notice set by the backend" ], "pg_last_oid": [ "string pg_last_oid(resource result)", "Returns the last object identifier" ], "pg_lo_close": [ "bool pg_lo_close(resource large_object)", "Close a large object" ], "pg_lo_create": [ "mixed pg_lo_create([resource connection],[mixed large_object_oid])", "Create a large object" ], "pg_lo_export": [ "bool pg_lo_export([resource connection, ] int objoid, string filename)", "Export large object direct to filesystem" ], "pg_lo_import": [ "int pg_lo_import([resource connection, ] string filename [, mixed oid])", "Import large object direct from filesystem" ], "pg_lo_open": [ "resource pg_lo_open([resource connection,] int large_object_oid, string mode)", "Open a large object and return fd" ], "pg_lo_read": [ "string pg_lo_read(resource large_object [, int len])", "Read a large object" ], "pg_lo_read_all": [ "int pg_lo_read_all(resource large_object)", "Read a large object and send straight to browser" ], "pg_lo_seek": [ "bool pg_lo_seek(resource large_object, int offset [, int whence])", "Seeks position of large object" ], "pg_lo_tell": [ "int pg_lo_tell(resource large_object)", "Returns current position of large object" ], "pg_lo_unlink": [ "bool pg_lo_unlink([resource connection,] string large_object_oid)", "Delete a large object" ], "pg_lo_write": [ "int pg_lo_write(resource large_object, string buf [, int len])", "Write a large object" ], "pg_meta_data": [ "array pg_meta_data(resource db, string table)", "Get meta_data" ], "pg_num_fields": [ "int pg_num_fields(resource result)", "Return the number of fields in the result" ], "pg_num_rows": [ "int pg_num_rows(resource result)", "Return the number of rows in the result" ], "pg_options": [ "string pg_options([resource connection])", "Get the options associated with the connection" ], "pg_parameter_status": [ "string|false pg_parameter_status([resource connection,] string param_name)", "Returns the value of a server parameter" ], "pg_pconnect": [ "resource pg_pconnect(string connection_string | [string host, string port [, string options [, string tty,]]] string database)", "Open a persistent PostgreSQL connection" ], "pg_ping": [ "bool pg_ping([resource connection])", "Ping database. If connection is bad, try to reconnect." ], "pg_port": [ "int pg_port([resource connection])", "Return the port number associated with the connection" ], "pg_prepare": [ "resource pg_prepare([resource connection,] string stmtname, string query)", "Prepare a query for future execution" ], "pg_put_line": [ "bool pg_put_line([resource connection,] string query)", "Send null-terminated string to backend server" ], "pg_query": [ "resource pg_query([resource connection,] string query)", "Execute a query" ], "pg_query_params": [ "resource pg_query_params([resource connection,] string query, array params)", "Execute a query" ], "pg_result_error": [ "string pg_result_error(resource result)", "Get error message associated with result" ], "pg_result_error_field": [ "string pg_result_error_field(resource result, int fieldcode)", "Get error message field associated with result" ], "pg_result_seek": [ "bool pg_result_seek(resource result, int offset)", "Set internal row offset" ], "pg_result_status": [ "mixed pg_result_status(resource result[, long result_type])", "Get status of query result" ], "pg_select": [ "mixed pg_select(resource db, string table, array ids[, int options])", "Select records that has ids (id=>value)" ], "pg_send_execute": [ "bool pg_send_execute(resource connection, string stmtname, array params)", "Executes prevriously prepared stmtname asynchronously" ], "pg_send_prepare": [ "bool pg_send_prepare(resource connection, string stmtname, string query)", "Asynchronously prepare a query for future execution" ], "pg_send_query": [ "bool pg_send_query(resource connection, string query)", "Send asynchronous query" ], "pg_send_query_params": [ "bool pg_send_query_params(resource connection, string query, array params)", "Send asynchronous parameterized query" ], "pg_set_client_encoding": [ "int pg_set_client_encoding([resource connection,] string encoding)", "Set client encoding" ], "pg_set_error_verbosity": [ "int pg_set_error_verbosity([resource connection,] int verbosity)", "Set error verbosity" ], "pg_trace": [ "bool pg_trace(string filename [, string mode [, resource connection]])", "Enable tracing a PostgreSQL connection" ], "pg_transaction_status": [ "int pg_transaction_status(resource connnection)", "Get transaction status" ], "pg_tty": [ "string pg_tty([resource connection])", "Return the tty name associated with the connection" ], "pg_unescape_bytea": [ "string pg_unescape_bytea(string data)", "Unescape binary for bytea type" ], "pg_untrace": [ "bool pg_untrace([resource connection])", "Disable tracing of a PostgreSQL connection" ], "pg_update": [ "mixed pg_update(resource db, string table, array fields, array ids[, int options])", "Update table using values (field=>value) and ids (id=>value)" ], "pg_version": [ "array pg_version([resource connection])", "Returns an array with client, protocol and server version (when available)" ], "php_egg_logo_guid": [ "string php_egg_logo_guid(void)", "Return the special ID used to request the PHP logo in phpinfo screens" ], "php_ini_loaded_file": [ "string php_ini_loaded_file(void)", "Return the actual loaded ini filename" ], "php_ini_scanned_files": [ "string php_ini_scanned_files(void)", "Return comma-separated string of .ini files parsed from the additional ini dir" ], "php_logo_guid": [ "string php_logo_guid(void)", "Return the special ID used to request the PHP logo in phpinfo screens" ], "php_real_logo_guid": [ "string php_real_logo_guid(void)", "Return the special ID used to request the PHP logo in phpinfo screens" ], "php_sapi_name": [ "string php_sapi_name(void)", "Return the current SAPI module name" ], "php_snmpv3": [ "void php_snmpv3(INTERNAL_FUNCTION_PARAMETERS, int st)", "* * Generic SNMPv3 object fetcher * From here is passed on the the common internal object fetcher. * * st=SNMP_CMD_GET snmp3_get() - query an agent and return a single value. * st=SNMP_CMD_GETNEXT snmp3_getnext() - query an agent and return the next single value. * st=SNMP_CMD_WALK snmp3_walk() - walk the mib and return a single dimensional array * containing the values. * st=SNMP_CMD_REALWALK snmp3_real_walk() - walk the mib and return an * array of oid,value pairs. * st=SNMP_CMD_SET snmp3_set() - query an agent and set a single value *" ], "php_strip_whitespace": [ "string php_strip_whitespace(string file_name)", "Return source with stripped comments and whitespace" ], "php_uname": [ "string php_uname(void)", "Return information about the system PHP was built on" ], "phpcredits": [ "void phpcredits([int flag])", "Prints the list of people who've contributed to the PHP project" ], "phpinfo": [ "void phpinfo([int what])", "Output a page of useful information about PHP and the current request" ], "phpversion": [ "string phpversion([string extension])", "Return the current PHP version" ], "pi": [ "float pi(void)", "Returns an approximation of pi" ], "png2wbmp": [ "bool png2wbmp (string f_org, string f_dest, int d_height, int d_width, int threshold)", "Convert PNG image to WBMP image" ], "popen": [ "resource popen(string command, string mode)", "Execute a command and open either a read or a write pipe to it" ], "posix_access": [ "bool posix_access(string file [, int mode])", "Determine accessibility of a file (POSIX.1 5.6.3)" ], "posix_ctermid": [ "string posix_ctermid(void)", "Generate terminal path name (POSIX.1, 4.7.1)" ], "posix_get_last_error": [ "int posix_get_last_error(void)", "Retrieve the error number set by the last posix function which failed." ], "posix_getcwd": [ "string posix_getcwd(void)", "Get working directory pathname (POSIX.1, 5.2.2)" ], "posix_getegid": [ "int posix_getegid(void)", "Get the current effective group id (POSIX.1, 4.2.1)" ], "posix_geteuid": [ "int posix_geteuid(void)", "Get the current effective user id (POSIX.1, 4.2.1)" ], "posix_getgid": [ "int posix_getgid(void)", "Get the current group id (POSIX.1, 4.2.1)" ], "posix_getgrgid": [ "array posix_getgrgid(long gid)", "Group database access (POSIX.1, 9.2.1)" ], "posix_getgrnam": [ "array posix_getgrnam(string groupname)", "Group database access (POSIX.1, 9.2.1)" ], "posix_getgroups": [ "array posix_getgroups(void)", "Get supplementary group id's (POSIX.1, 4.2.3)" ], "posix_getlogin": [ "string posix_getlogin(void)", "Get user name (POSIX.1, 4.2.4)" ], "posix_getpgid": [ "int posix_getpgid(void)", "Get the process group id of the specified process (This is not a POSIX function, but a SVR4ism, so we compile conditionally)" ], "posix_getpgrp": [ "int posix_getpgrp(void)", "Get current process group id (POSIX.1, 4.3.1)" ], "posix_getpid": [ "int posix_getpid(void)", "Get the current process id (POSIX.1, 4.1.1)" ], "posix_getppid": [ "int posix_getppid(void)", "Get the parent process id (POSIX.1, 4.1.1)" ], "posix_getpwnam": [ "array posix_getpwnam(string groupname)", "User database access (POSIX.1, 9.2.2)" ], "posix_getpwuid": [ "array posix_getpwuid(long uid)", "User database access (POSIX.1, 9.2.2)" ], "posix_getrlimit": [ "array posix_getrlimit(void)", "Get system resource consumption limits (This is not a POSIX function, but a BSDism and a SVR4ism. We compile conditionally)" ], "posix_getsid": [ "int posix_getsid(void)", "Get process group id of session leader (This is not a POSIX function, but a SVR4ism, so be compile conditionally)" ], "posix_getuid": [ "int posix_getuid(void)", "Get the current user id (POSIX.1, 4.2.1)" ], "posix_initgroups": [ "bool posix_initgroups(string name, int base_group_id)", "Calculate the group access list for the user specified in name." ], "posix_isatty": [ "bool posix_isatty(int fd)", "Determine if filedesc is a tty (POSIX.1, 4.7.1)" ], "posix_kill": [ "bool posix_kill(int pid, int sig)", "Send a signal to a process (POSIX.1, 3.3.2)" ], "posix_mkfifo": [ "bool posix_mkfifo(string pathname, int mode)", "Make a FIFO special file (POSIX.1, 5.4.2)" ], "posix_mknod": [ "bool posix_mknod(string pathname, int mode [, int major [, int minor]])", "Make a special or ordinary file (POSIX.1)" ], "posix_setegid": [ "bool posix_setegid(long uid)", "Set effective group id" ], "posix_seteuid": [ "bool posix_seteuid(long uid)", "Set effective user id" ], "posix_setgid": [ "bool posix_setgid(int uid)", "Set group id (POSIX.1, 4.2.2)" ], "posix_setpgid": [ "bool posix_setpgid(int pid, int pgid)", "Set process group id for job control (POSIX.1, 4.3.3)" ], "posix_setsid": [ "int posix_setsid(void)", "Create session and set process group id (POSIX.1, 4.3.2)" ], "posix_setuid": [ "bool posix_setuid(long uid)", "Set user id (POSIX.1, 4.2.2)" ], "posix_strerror": [ "string posix_strerror(int errno)", "Retrieve the system error message associated with the given errno." ], "posix_times": [ "array posix_times(void)", "Get process times (POSIX.1, 4.5.2)" ], "posix_ttyname": [ "string posix_ttyname(int fd)", "Determine terminal device name (POSIX.1, 4.7.2)" ], "posix_uname": [ "array posix_uname(void)", "Get system name (POSIX.1, 4.4.1)" ], "pow": [ "number pow(number base, number exponent)", "Returns base raised to the power of exponent. Returns integer result when possible" ], "preg_filter": [ "mixed preg_filter(mixed regex, mixed replace, mixed subject [, int limit [, int &count]])", "Perform Perl-style regular expression replacement and only return matches." ], "preg_grep": [ "array preg_grep(string regex, array input [, int flags])", "Searches array and returns entries which match regex" ], "preg_last_error": [ "int preg_last_error()", "Returns the error code of the last regexp execution." ], "preg_match": [ "int preg_match(string pattern, string subject [, array &subpatterns [, int flags [, int offset]]])", "Perform a Perl-style regular expression match" ], "preg_match_all": [ "int preg_match_all(string pattern, string subject, array &subpatterns [, int flags [, int offset]])", "Perform a Perl-style global regular expression match" ], "preg_quote": [ "string preg_quote(string str [, string delim_char])", "Quote regular expression characters plus an optional character" ], "preg_replace": [ "mixed preg_replace(mixed regex, mixed replace, mixed subject [, int limit [, int &count]])", "Perform Perl-style regular expression replacement." ], "preg_replace_callback": [ "mixed preg_replace_callback(mixed regex, mixed callback, mixed subject [, int limit [, int &count]])", "Perform Perl-style regular expression replacement using replacement callback." ], "preg_split": [ "array preg_split(string pattern, string subject [, int limit [, int flags]])", "Split string into an array using a perl-style regular expression as a delimiter" ], "prev": [ "mixed prev(array array_arg)", "Move array argument's internal pointer to the previous element and return it" ], "print": [ "int print(string arg)", "Output a string" ], "print_r": [ "mixed print_r(mixed var [, bool return])", "Prints out or returns information about the specified variable" ], "printf": [ "int printf(string format [, mixed arg1 [, mixed ...]])", "Output a formatted string" ], "proc_close": [ "int proc_close(resource process)", "close a process opened by proc_open" ], "proc_get_status": [ "array proc_get_status(resource process)", "get information about a process opened by proc_open" ], "proc_nice": [ "bool proc_nice(int priority)", "Change the priority of the current process" ], "proc_open": [ "resource proc_open(string command, array descriptorspec, array &pipes [, string cwd [, array env [, array other_options]]])", "Run a process with more control over it's file descriptors" ], "proc_terminate": [ "bool proc_terminate(resource process [, long signal])", "kill a process opened by proc_open" ], "property_exists": [ "bool property_exists(mixed object_or_class, string property_name)", "Checks if the object or class has a property" ], "pspell_add_to_personal": [ "bool pspell_add_to_personal(int pspell, string word)", "Adds a word to a personal list" ], "pspell_add_to_session": [ "bool pspell_add_to_session(int pspell, string word)", "Adds a word to the current session" ], "pspell_check": [ "bool pspell_check(int pspell, string word)", "Returns true if word is valid" ], "pspell_clear_session": [ "bool pspell_clear_session(int pspell)", "Clears the current session" ], "pspell_config_create": [ "int pspell_config_create(string language [, string spelling [, string jargon [, string encoding]]])", "Create a new config to be used later to create a manager" ], "pspell_config_data_dir": [ "bool pspell_config_data_dir(int conf, string directory)", "location of language data files" ], "pspell_config_dict_dir": [ "bool pspell_config_dict_dir(int conf, string directory)", "location of the main word list" ], "pspell_config_ignore": [ "bool pspell_config_ignore(int conf, int ignore)", "Ignore words <= n chars" ], "pspell_config_mode": [ "bool pspell_config_mode(int conf, long mode)", "Select mode for config (PSPELL_FAST, PSPELL_NORMAL or PSPELL_BAD_SPELLERS)" ], "pspell_config_personal": [ "bool pspell_config_personal(int conf, string personal)", "Use a personal dictionary for this config" ], "pspell_config_repl": [ "bool pspell_config_repl(int conf, string repl)", "Use a personal dictionary with replacement pairs for this config" ], "pspell_config_runtogether": [ "bool pspell_config_runtogether(int conf, bool runtogether)", "Consider run-together words as valid components" ], "pspell_config_save_repl": [ "bool pspell_config_save_repl(int conf, bool save)", "Save replacement pairs when personal list is saved for this config" ], "pspell_new": [ "int pspell_new(string language [, string spelling [, string jargon [, string encoding [, int mode]]]])", "Load a dictionary" ], "pspell_new_config": [ "int pspell_new_config(int config)", "Load a dictionary based on the given config" ], "pspell_new_personal": [ "int pspell_new_personal(string personal, string language [, string spelling [, string jargon [, string encoding [, int mode]]]])", "Load a dictionary with a personal wordlist" ], "pspell_save_wordlist": [ "bool pspell_save_wordlist(int pspell)", "Saves the current (personal) wordlist" ], "pspell_store_replacement": [ "bool pspell_store_replacement(int pspell, string misspell, string correct)", "Notify the dictionary of a user-selected replacement" ], "pspell_suggest": [ "array pspell_suggest(int pspell, string word)", "Returns array of suggestions" ], "putenv": [ "bool putenv(string setting)", "Set the value of an environment variable" ], "quoted_printable_decode": [ "string quoted_printable_decode(string str)", "Convert a quoted-printable string to an 8 bit string" ], "quoted_printable_encode": [ "string quoted_printable_encode(string str) */", "PHP_FUNCTION(quoted_printable_encode) { char *str, *new_str; int str_len; size_t new_str_len; if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, \"s\", &str, &str_len) != SUCCESS) { return; } if (!str_len) { RETURN_EMPTY_STRING(); } new_str = (char *)php_quot_print_encode((unsigned char *)str, (size_t)str_len, &new_str_len); RETURN_STRINGL(new_str, new_str_len, 0); } /* }}}" ], "quotemeta": [ "string quotemeta(string str)", "Quotes meta characters" ], "rad2deg": [ "float rad2deg(float number)", "Converts the radian number to the equivalent number in degrees" ], "rand": [ "int rand([int min, int max])", "Returns a random number" ], "range": [ "array range(mixed low, mixed high[, int step])", "Create an array containing the range of integers or characters from low to high (inclusive)" ], "rawurldecode": [ "string rawurldecode(string str)", "Decodes URL-encodes string" ], "rawurlencode": [ "string rawurlencode(string str)", "URL-encodes string" ], "readdir": [ "string readdir([resource dir_handle])", "Read directory entry from dir_handle" ], "readfile": [ "int readfile(string filename [, bool use_include_path[, resource context]])", "Output a file or a URL" ], "readgzfile": [ "int readgzfile(string filename [, int use_include_path])", "Output a .gz-file" ], "readline": [ "string readline([string prompt])", "Reads a line" ], "readline_add_history": [ "bool readline_add_history(string prompt)", "Adds a line to the history" ], "readline_callback_handler_install": [ "void readline_callback_handler_install(string prompt, mixed callback)", "Initializes the readline callback interface and terminal, prints the prompt and returns immediately" ], "readline_callback_handler_remove": [ "bool readline_callback_handler_remove()", "Removes a previously installed callback handler and restores terminal settings" ], "readline_callback_read_char": [ "void readline_callback_read_char()", "Informs the readline callback interface that a character is ready for input" ], "readline_clear_history": [ "bool readline_clear_history(void)", "Clears the history" ], "readline_completion_function": [ "bool readline_completion_function(string funcname)", "Readline completion function?" ], "readline_info": [ "mixed readline_info([string varname [, string newvalue]])", "Gets/sets various internal readline variables." ], "readline_list_history": [ "array readline_list_history(void)", "Lists the history" ], "readline_on_new_line": [ "void readline_on_new_line(void)", "Inform readline that the cursor has moved to a new line" ], "readline_read_history": [ "bool readline_read_history([string filename])", "Reads the history" ], "readline_redisplay": [ "void readline_redisplay(void)", "Ask readline to redraw the display" ], "readline_write_history": [ "bool readline_write_history([string filename])", "Writes the history" ], "readlink": [ "string readlink(string filename)", "Return the target of a symbolic link" ], "realpath": [ "string realpath(string path)", "Return the resolved path" ], "realpath_cache_get": [ "bool realpath_cache_get()", "Get current size of realpath cache" ], "realpath_cache_size": [ "bool realpath_cache_size()", "Get current size of realpath cache" ], "recode_file": [ "bool recode_file(string request, resource input, resource output)", "Recode file input into file output according to request" ], "recode_string": [ "string recode_string(string request, string str)", "Recode string str according to request string" ], "register_shutdown_function": [ "void register_shutdown_function(string function_name)", "Register a user-level function to be called on request termination" ], "register_tick_function": [ "bool register_tick_function(string function_name [, mixed arg [, mixed ... ]])", "Registers a tick callback function" ], "rename": [ "bool rename(string old_name, string new_name[, resource context])", "Rename a file" ], "require": [ "bool require(string path)", "Includes and evaluates the specified file, erroring if the file cannot be included" ], "require_once": [ "bool require_once(string path)", "Includes and evaluates the specified file, erroring if the file cannot be included" ], "reset": [ "mixed reset(array array_arg)", "Set array argument's internal pointer to the first element and return it" ], "restore_error_handler": [ "void restore_error_handler(void)", "Restores the previously defined error handler function" ], "restore_exception_handler": [ "void restore_exception_handler(void)", "Restores the previously defined exception handler function" ], "restore_include_path": [ "void restore_include_path()", "Restore the value of the include_path configuration option" ], "rewind": [ "bool rewind(resource fp)", "Rewind the position of a file pointer" ], "rewinddir": [ "void rewinddir([resource dir_handle])", "Rewind dir_handle back to the start" ], "rmdir": [ "bool rmdir(string dirname[, resource context])", "Remove a directory" ], "round": [ "float round(float number [, int precision [, int mode]])", "Returns the number rounded to specified precision" ], "rsort": [ "bool rsort(array &array_arg [, int sort_flags])", "Sort an array in reverse order" ], "rtrim": [ "string rtrim(string str [, string character_mask])", "Removes trailing whitespace" ], "scandir": [ "array scandir(string dir [, int sorting_order [, resource context]])", "List files & directories inside the specified path" ], "sem_acquire": [ "bool sem_acquire(resource id)", "Acquires the semaphore with the given id, blocking if necessary" ], "sem_get": [ "resource sem_get(int key [, int max_acquire [, int perm [, int auto_release]])", "Return an id for the semaphore with the given key, and allow max_acquire (default 1) processes to acquire it simultaneously" ], "sem_release": [ "bool sem_release(resource id)", "Releases the semaphore with the given id" ], "sem_remove": [ "bool sem_remove(resource id)", "Removes semaphore from Unix systems" ], "serialize": [ "string serialize(mixed variable)", "Returns a string representation of variable (which can later be unserialized)" ], "session_cache_expire": [ "int session_cache_expire([int new_cache_expire])", "Return the current cache expire. If new_cache_expire is given, the current cache_expire is replaced with new_cache_expire" ], "session_cache_limiter": [ "string session_cache_limiter([string new_cache_limiter])", "Return the current cache limiter. If new_cache_limited is given, the current cache_limiter is replaced with new_cache_limiter" ], "session_decode": [ "bool session_decode(string data)", "Deserializes data and reinitializes the variables" ], "session_destroy": [ "bool session_destroy(void)", "Destroy the current session and all data associated with it" ], "session_encode": [ "string session_encode(void)", "Serializes the current setup and returns the serialized representation" ], "session_get_cookie_params": [ "array session_get_cookie_params(void)", "Return the session cookie parameters" ], "session_id": [ "string session_id([string newid])", "Return the current session id. If newid is given, the session id is replaced with newid" ], "session_is_registered": [ "bool session_is_registered(string varname)", "Checks if a variable is registered in session" ], "session_module_name": [ "string session_module_name([string newname])", "Return the current module name used for accessing session data. If newname is given, the module name is replaced with newname" ], "session_name": [ "string session_name([string newname])", "Return the current session name. If newname is given, the session name is replaced with newname" ], "session_regenerate_id": [ "bool session_regenerate_id([bool delete_old_session])", "Update the current session id with a newly generated one. If delete_old_session is set to true, remove the old session." ], "session_register": [ "bool session_register(mixed var_names [, mixed ...])", "Adds varname(s) to the list of variables which are freezed at the session end" ], "session_save_path": [ "string session_save_path([string newname])", "Return the current save path passed to module_name. If newname is given, the save path is replaced with newname" ], "session_set_cookie_params": [ "void session_set_cookie_params(int lifetime [, string path [, string domain [, bool secure[, bool httponly]]]])", "Set session cookie parameters" ], "session_set_save_handler": [ "void session_set_save_handler(string open, string close, string read, string write, string destroy, string gc)", "Sets user-level functions" ], "session_start": [ "bool session_start(void)", "Begin session - reinitializes freezed variables, registers browsers etc" ], "session_unregister": [ "bool session_unregister(string varname)", "Removes varname from the list of variables which are freezed at the session end" ], "session_unset": [ "void session_unset(void)", "Unset all registered variables" ], "session_write_close": [ "void session_write_close(void)", "Write session data and end session" ], "set_error_handler": [ "string set_error_handler(string error_handler [, int error_types])", "Sets a user-defined error handler function. Returns the previously defined error handler, or false on error" ], "set_exception_handler": [ "string set_exception_handler(callable exception_handler)", "Sets a user-defined exception handler function. Returns the previously defined exception handler, or false on error" ], "set_include_path": [ "string set_include_path(string new_include_path)", "Sets the include_path configuration option" ], "set_magic_quotes_runtime": [ "bool set_magic_quotes_runtime(int new_setting)", "Set the current active configuration setting of magic_quotes_runtime and return previous" ], "set_time_limit": [ "bool set_time_limit(int seconds)", "Sets the maximum time a script can run" ], "setcookie": [ "bool setcookie(string name [, string value [, int expires [, string path [, string domain [, bool secure[, bool httponly]]]]]])", "Send a cookie" ], "setlocale": [ "string setlocale(mixed category, string locale [, string ...])", "Set locale information" ], "setrawcookie": [ "bool setrawcookie(string name [, string value [, int expires [, string path [, string domain [, bool secure[, bool httponly]]]]]])", "Send a cookie with no url encoding of the value" ], "settype": [ "bool settype(mixed var, string type)", "Set the type of the variable" ], "sha1": [ "string sha1(string str [, bool raw_output])", "Calculate the sha1 hash of a string" ], "sha1_file": [ "string sha1_file(string filename [, bool raw_output])", "Calculate the sha1 hash of given filename" ], "shell_exec": [ "string shell_exec(string cmd)", "Execute command via shell and return complete output as string" ], "shm_attach": [ "int shm_attach(int key [, int memsize [, int perm]])", "Creates or open a shared memory segment" ], "shm_detach": [ "bool shm_detach(resource shm_identifier)", "Disconnects from shared memory segment" ], "shm_get_var": [ "mixed shm_get_var(resource id, int variable_key)", "Returns a variable from shared memory" ], "shm_has_var": [ "bool shm_has_var(resource id, int variable_key)", "Checks whether a specific entry exists" ], "shm_put_var": [ "bool shm_put_var(resource shm_identifier, int variable_key, mixed variable)", "Inserts or updates a variable in shared memory" ], "shm_remove": [ "bool shm_remove(resource shm_identifier)", "Removes shared memory from Unix systems" ], "shm_remove_var": [ "bool shm_remove_var(resource id, int variable_key)", "Removes variable from shared memory" ], "shmop_close": [ "void shmop_close (int shmid)", "closes a shared memory segment" ], "shmop_delete": [ "bool shmop_delete (int shmid)", "mark segment for deletion" ], "shmop_open": [ "int shmop_open (int key, string flags, int mode, int size)", "gets and attaches a shared memory segment" ], "shmop_read": [ "string shmop_read (int shmid, int start, int count)", "reads from a shm segment" ], "shmop_size": [ "int shmop_size (int shmid)", "returns the shm size" ], "shmop_write": [ "int shmop_write (int shmid, string data, int offset)", "writes to a shared memory segment" ], "shuffle": [ "bool shuffle(array array_arg)", "Randomly shuffle the contents of an array" ], "similar_text": [ "int similar_text(string str1, string str2 [, float percent])", "Calculates the similarity between two strings" ], "simplexml_import_dom": [ "simplemxml_element simplexml_import_dom(domNode node [, string class_name])", "Get a simplexml_element object from dom to allow for processing" ], "simplexml_load_file": [ "simplemxml_element simplexml_load_file(string filename [, string class_name [, int options [, string ns [, bool is_prefix]]]])", "Load a filename and return a simplexml_element object to allow for processing" ], "simplexml_load_string": [ "simplemxml_element simplexml_load_string(string data [, string class_name [, int options [, string ns [, bool is_prefix]]]])", "Load a string and return a simplexml_element object to allow for processing" ], "sin": [ "float sin(float number)", "Returns the sine of the number in radians" ], "sinh": [ "float sinh(float number)", "Returns the hyperbolic sine of the number, defined as (exp(number) - exp(-number))/2" ], "sleep": [ "void sleep(int seconds)", "Delay for a given number of seconds" ], "smfi_addheader": [ "bool smfi_addheader(string headerf, string headerv)", "Adds a header to the current message." ], "smfi_addrcpt": [ "bool smfi_addrcpt(string rcpt)", "Add a recipient to the message envelope." ], "smfi_chgheader": [ "bool smfi_chgheader(string headerf, string headerv)", "Changes a header's value for the current message." ], "smfi_delrcpt": [ "bool smfi_delrcpt(string rcpt)", "Removes the named recipient from the current message's envelope." ], "smfi_getsymval": [ "string smfi_getsymval(string macro)", "Returns the value of the given macro or NULL if the macro is not defined." ], "smfi_replacebody": [ "bool smfi_replacebody(string body)", "Replaces the body of the current message. If called more than once, subsequent calls result in data being appended to the new body." ], "smfi_setflags": [ "void smfi_setflags(long flags)", "Sets the flags describing the actions the filter may take." ], "smfi_setreply": [ "bool smfi_setreply(string rcode, string xcode, string message)", "Directly set the SMTP error reply code for this connection. This code will be used on subsequent error replies resulting from actions taken by this filter." ], "smfi_settimeout": [ "void smfi_settimeout(long timeout)", "Sets the number of seconds libmilter will wait for an MTA connection before timing out a socket." ], "snmp2_get": [ "string snmp2_get(string host, string community, string object_id [, int timeout [, int retries]])", "Fetch a SNMP object" ], "snmp2_getnext": [ "string snmp2_getnext(string host, string community, string object_id [, int timeout [, int retries]])", "Fetch a SNMP object" ], "snmp2_real_walk": [ "array snmp2_real_walk(string host, string community, string object_id [, int timeout [, int retries]])", "Return all objects including their respective object id withing the specified one" ], "snmp2_set": [ "int snmp2_set(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]])", "Set the value of a SNMP object" ], "snmp2_walk": [ "array snmp2_walk(string host, string community, string object_id [, int timeout [, int retries]])", "Return all objects under the specified object id" ], "snmp3_get": [ "int snmp3_get(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]])", "Fetch the value of a SNMP object" ], "snmp3_getnext": [ "int snmp3_getnext(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]])", "Fetch the value of a SNMP object" ], "snmp3_real_walk": [ "int snmp3_real_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]])", "Fetch the value of a SNMP object" ], "snmp3_set": [ "int snmp3_set(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id, string type, mixed value [, int timeout [, int retries]])", "Fetch the value of a SNMP object" ], "snmp3_walk": [ "int snmp3_walk(string host, string sec_name, string sec_level, string auth_protocol, string auth_passphrase, string priv_protocol, string priv_passphrase, string object_id [, int timeout [, int retries]])", "Fetch the value of a SNMP object" ], "snmp_get_quick_print": [ "bool snmp_get_quick_print(void)", "Return the current status of quick_print" ], "snmp_get_valueretrieval": [ "int snmp_get_valueretrieval()", "Return the method how the SNMP values will be returned" ], "snmp_read_mib": [ "int snmp_read_mib(string filename)", "Reads and parses a MIB file into the active MIB tree." ], "snmp_set_enum_print": [ "void snmp_set_enum_print(int enum_print)", "Return all values that are enums with their enum value instead of the raw integer" ], "snmp_set_oid_output_format": [ "void snmp_set_oid_output_format(int oid_format)", "Set the OID output format." ], "snmp_set_quick_print": [ "void snmp_set_quick_print(int quick_print)", "Return all objects including their respective object id withing the specified one" ], "snmp_set_valueretrieval": [ "void snmp_set_valueretrieval(int method)", "Specify the method how the SNMP values will be returned" ], "snmpget": [ "string snmpget(string host, string community, string object_id [, int timeout [, int retries]])", "Fetch a SNMP object" ], "snmpgetnext": [ "string snmpgetnext(string host, string community, string object_id [, int timeout [, int retries]])", "Fetch a SNMP object" ], "snmprealwalk": [ "array snmprealwalk(string host, string community, string object_id [, int timeout [, int retries]])", "Return all objects including their respective object id withing the specified one" ], "snmpset": [ "int snmpset(string host, string community, string object_id, string type, mixed value [, int timeout [, int retries]])", "Set the value of a SNMP object" ], "snmpwalk": [ "array snmpwalk(string host, string community, string object_id [, int timeout [, int retries]])", "Return all objects under the specified object id" ], "socket_accept": [ "resource socket_accept(resource socket)", "Accepts a connection on the listening socket fd" ], "socket_bind": [ "bool socket_bind(resource socket, string addr [, int port])", "Binds an open socket to a listening port, port is only specified in AF_INET family." ], "socket_clear_error": [ "void socket_clear_error([resource socket])", "Clears the error on the socket or the last error code." ], "socket_close": [ "void socket_close(resource socket)", "Closes a file descriptor" ], "socket_connect": [ "bool socket_connect(resource socket, string addr [, int port])", "Opens a connection to addr:port on the socket specified by socket" ], "socket_create": [ "resource socket_create(int domain, int type, int protocol)", "Creates an endpoint for communication in the domain specified by domain, of type specified by type" ], "socket_create_listen": [ "resource socket_create_listen(int port[, int backlog])", "Opens a socket on port to accept connections" ], "socket_create_pair": [ "bool socket_create_pair(int domain, int type, int protocol, array &fd)", "Creates a pair of indistinguishable sockets and stores them in fds." ], "socket_get_option": [ "mixed socket_get_option(resource socket, int level, int optname)", "Gets socket options for the socket" ], "socket_getpeername": [ "bool socket_getpeername(resource socket, string &addr[, int &port])", "Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type." ], "socket_getsockname": [ "bool socket_getsockname(resource socket, string &addr[, int &port])", "Queries the remote side of the given socket which may either result in host/port or in a UNIX filesystem path, dependent on its type." ], "socket_last_error": [ "int socket_last_error([resource socket])", "Returns the last socket error (either the last used or the provided socket resource)" ], "socket_listen": [ "bool socket_listen(resource socket[, int backlog])", "Sets the maximum number of connections allowed to be waited for on the socket specified by fd" ], "socket_read": [ "string socket_read(resource socket, int length [, int type])", "Reads a maximum of length bytes from socket" ], "socket_recv": [ "int socket_recv(resource socket, string &buf, int len, int flags)", "Receives data from a connected socket" ], "socket_recvfrom": [ "int socket_recvfrom(resource socket, string &buf, int len, int flags, string &name [, int &port])", "Receives data from a socket, connected or not" ], "socket_select": [ "int socket_select(array &read_fds, array &write_fds, array &except_fds, int tv_sec[, int tv_usec])", "Runs the select() system call on the sets mentioned with a timeout specified by tv_sec and tv_usec" ], "socket_send": [ "int socket_send(resource socket, string buf, int len, int flags)", "Sends data to a connected socket" ], "socket_sendto": [ "int socket_sendto(resource socket, string buf, int len, int flags, string addr [, int port])", "Sends a message to a socket, whether it is connected or not" ], "socket_set_block": [ "bool socket_set_block(resource socket)", "Sets blocking mode on a socket resource" ], "socket_set_nonblock": [ "bool socket_set_nonblock(resource socket)", "Sets nonblocking mode on a socket resource" ], "socket_set_option": [ "bool socket_set_option(resource socket, int level, int optname, int|array optval)", "Sets socket options for the socket" ], "socket_shutdown": [ "bool socket_shutdown(resource socket[, int how])", "Shuts down a socket for receiving, sending, or both." ], "socket_strerror": [ "string socket_strerror(int errno)", "Returns a string describing an error" ], "socket_write": [ "int socket_write(resource socket, string buf[, int length])", "Writes the buffer to the socket resource, length is optional" ], "solid_fetch_prev": [ "bool solid_fetch_prev(resource result_id)", "" ], "sort": [ "bool sort(array &array_arg [, int sort_flags])", "Sort an array" ], "soundex": [ "string soundex(string str)", "Calculate the soundex key of a string" ], "spl_autoload": [ "void spl_autoload(string class_name [, string file_extensions])", "Default implementation for __autoload()" ], "spl_autoload_call": [ "void spl_autoload_call(string class_name)", "Try all registerd autoload function to load the requested class" ], "spl_autoload_extensions": [ "string spl_autoload_extensions([string file_extensions])", "Register and return default file extensions for spl_autoload" ], "spl_autoload_functions": [ "false|array spl_autoload_functions()", "Return all registered __autoload() functionns" ], "spl_autoload_register": [ "bool spl_autoload_register([mixed autoload_function = \"spl_autoload\" [, throw = true [, prepend]]])", "Register given function as __autoload() implementation" ], "spl_autoload_unregister": [ "bool spl_autoload_unregister(mixed autoload_function)", "Unregister given function as __autoload() implementation" ], "spl_classes": [ "array spl_classes()", "Return an array containing the names of all clsses and interfaces defined in SPL" ], "spl_object_hash": [ "string spl_object_hash(object obj)", "Return hash id for given object" ], "split": [ "array split(string pattern, string string [, int limit])", "Split string into array by regular expression" ], "spliti": [ "array spliti(string pattern, string string [, int limit])", "Split string into array by regular expression case-insensitive" ], "sprintf": [ "string sprintf(string format [, mixed arg1 [, mixed ...]])", "Return a formatted string" ], "sql_regcase": [ "string sql_regcase(string string)", "Make regular expression for case insensitive match" ], "sqlite_array_query": [ "array sqlite_array_query(resource db, string query [ , int result_type [, bool decode_binary]])", "Executes a query against a given database and returns an array of arrays." ], "sqlite_busy_timeout": [ "void sqlite_busy_timeout(resource db, int ms)", "Set busy timeout duration. If ms <= 0, all busy handlers are disabled." ], "sqlite_changes": [ "int sqlite_changes(resource db)", "Returns the number of rows that were changed by the most recent SQL statement." ], "sqlite_close": [ "void sqlite_close(resource db)", "Closes an open sqlite database." ], "sqlite_column": [ "mixed sqlite_column(resource result, mixed index_or_name [, bool decode_binary])", "Fetches a column from the current row of a result set." ], "sqlite_create_aggregate": [ "bool sqlite_create_aggregate(resource db, string funcname, mixed step_func, mixed finalize_func[, long num_args])", "Registers an aggregate function for queries." ], "sqlite_create_function": [ "bool sqlite_create_function(resource db, string funcname, mixed callback[, long num_args])", "Registers a \"regular\" function for queries." ], "sqlite_current": [ "array sqlite_current(resource result [, int result_type [, bool decode_binary]])", "Fetches the current row from a result set as an array." ], "sqlite_error_string": [ "string sqlite_error_string(int error_code)", "Returns the textual description of an error code." ], "sqlite_escape_string": [ "string sqlite_escape_string(string item)", "Escapes a string for use as a query parameter." ], "sqlite_exec": [ "boolean sqlite_exec(string query, resource db[, string &error_message])", "Executes a result-less query against a given database" ], "sqlite_factory": [ "object sqlite_factory(string filename [, int mode [, string &error_message]])", "Opens a SQLite database and creates an object for it. Will create the database if it does not exist." ], "sqlite_fetch_all": [ "array sqlite_fetch_all(resource result [, int result_type [, bool decode_binary]])", "Fetches all rows from a result set as an array of arrays." ], "sqlite_fetch_array": [ "array sqlite_fetch_array(resource result [, int result_type [, bool decode_binary]])", "Fetches the next row from a result set as an array." ], "sqlite_fetch_column_types": [ "resource sqlite_fetch_column_types(string table_name, resource db [, int result_type])", "Return an array of column types from a particular table." ], "sqlite_fetch_object": [ "object sqlite_fetch_object(resource result [, string class_name [, NULL|array ctor_params [, bool decode_binary]]])", "Fetches the next row from a result set as an object." ], "sqlite_fetch_single": [ "string sqlite_fetch_single(resource result [, bool decode_binary])", "Fetches the first column of a result set as a string." ], "sqlite_field_name": [ "string sqlite_field_name(resource result, int field_index)", "Returns the name of a particular field of a result set." ], "sqlite_has_prev": [ "bool sqlite_has_prev(resource result)", "* Returns whether a previous row is available." ], "sqlite_key": [ "int sqlite_key(resource result)", "Return the current row index of a buffered result." ], "sqlite_last_error": [ "int sqlite_last_error(resource db)", "Returns the error code of the last error for a database." ], "sqlite_last_insert_rowid": [ "int sqlite_last_insert_rowid(resource db)", "Returns the rowid of the most recently inserted row." ], "sqlite_libencoding": [ "string sqlite_libencoding()", "Returns the encoding (iso8859 or UTF-8) of the linked SQLite library." ], "sqlite_libversion": [ "string sqlite_libversion()", "Returns the version of the linked SQLite library." ], "sqlite_next": [ "bool sqlite_next(resource result)", "Seek to the next row number of a result set." ], "sqlite_num_fields": [ "int sqlite_num_fields(resource result)", "Returns the number of fields in a result set." ], "sqlite_num_rows": [ "int sqlite_num_rows(resource result)", "Returns the number of rows in a buffered result set." ], "sqlite_open": [ "resource sqlite_open(string filename [, int mode [, string &error_message]])", "Opens a SQLite database. Will create the database if it does not exist." ], "sqlite_popen": [ "resource sqlite_popen(string filename [, int mode [, string &error_message]])", "Opens a persistent handle to a SQLite database. Will create the database if it does not exist." ], "sqlite_prev": [ "bool sqlite_prev(resource result)", "* Seek to the previous row number of a result set." ], "sqlite_query": [ "resource sqlite_query(string query, resource db [, int result_type [, string &error_message]])", "Executes a query against a given database and returns a result handle." ], "sqlite_rewind": [ "bool sqlite_rewind(resource result)", "Seek to the first row number of a buffered result set." ], "sqlite_seek": [ "bool sqlite_seek(resource result, int row)", "Seek to a particular row number of a buffered result set." ], "sqlite_single_query": [ "array sqlite_single_query(resource db, string query [, bool first_row_only [, bool decode_binary]])", "Executes a query and returns either an array for one single column or the value of the first row." ], "sqlite_udf_decode_binary": [ "string sqlite_udf_decode_binary(string data)", "Decode binary encoding on a string parameter passed to an UDF." ], "sqlite_udf_encode_binary": [ "string sqlite_udf_encode_binary(string data)", "Apply binary encoding (if required) to a string to return from an UDF." ], "sqlite_unbuffered_query": [ "resource sqlite_unbuffered_query(string query, resource db [ , int result_type [, string &error_message]])", "Executes a query that does not prefetch and buffer all data." ], "sqlite_valid": [ "bool sqlite_valid(resource result)", "Returns whether more rows are available." ], "sqrt": [ "float sqrt(float number)", "Returns the square root of the number" ], "srand": [ "void srand([int seed])", "Seeds random number generator" ], "sscanf": [ "mixed sscanf(string str, string format [, string ...])", "Implements an ANSI C compatible sscanf" ], "stat": [ "array stat(string filename)", "Give information about a file" ], "str_getcsv": [ "array str_getcsv(string input[, string delimiter[, string enclosure[, string escape]]])", "Parse a CSV string into an array" ], "str_ireplace": [ "mixed str_ireplace(mixed search, mixed replace, mixed subject [, int &replace_count])", "Replaces all occurrences of search in haystack with replace / case-insensitive" ], "str_pad": [ "string str_pad(string input, int pad_length [, string pad_string [, int pad_type]])", "Returns input string padded on the left or right to specified length with pad_string" ], "str_repeat": [ "string str_repeat(string input, int mult)", "Returns the input string repeat mult times" ], "str_replace": [ "mixed str_replace(mixed search, mixed replace, mixed subject [, int &replace_count])", "Replaces all occurrences of search in haystack with replace" ], "str_rot13": [ "string str_rot13(string str)", "Perform the rot13 transform on a string" ], "str_shuffle": [ "void str_shuffle(string str)", "Shuffles string. One permutation of all possible is created" ], "str_split": [ "array str_split(string str [, int split_length])", "Convert a string to an array. If split_length is specified, break the string down into chunks each split_length characters long." ], "str_word_count": [ "mixed str_word_count(string str, [int format [, string charlist]])", "Counts the number of words inside a string. If format of 1 is specified, then the function will return an array containing all the words found inside the string. If format of 2 is specified, then the function will return an associated array where the position of the word is the key and the word itself is the value. For the purpose of this function, 'word' is defined as a locale dependent string containing alphabetic characters, which also may contain, but not start with \"'\" and \"-\" characters." ], "strcasecmp": [ "int strcasecmp(string str1, string str2)", "Binary safe case-insensitive string comparison" ], "strchr": [ "string strchr(string haystack, string needle)", "An alias for strstr" ], "strcmp": [ "int strcmp(string str1, string str2)", "Binary safe string comparison" ], "strcoll": [ "int strcoll(string str1, string str2)", "Compares two strings using the current locale" ], "strcspn": [ "int strcspn(string str, string mask [, start [, len]])", "Finds length of initial segment consisting entirely of characters not found in mask. If start or/and length is provide works like strcspn(substr($s,$start,$len),$bad_chars)" ], "stream_bucket_append": [ "void stream_bucket_append(resource brigade, resource bucket)", "Append bucket to brigade" ], "stream_bucket_make_writeable": [ "object stream_bucket_make_writeable(resource brigade)", "Return a bucket object from the brigade for operating on" ], "stream_bucket_new": [ "resource stream_bucket_new(resource stream, string buffer)", "Create a new bucket for use on the current stream" ], "stream_bucket_prepend": [ "void stream_bucket_prepend(resource brigade, resource bucket)", "Prepend bucket to brigade" ], "stream_context_create": [ "resource stream_context_create([array options[, array params]])", "Create a file context and optionally set parameters" ], "stream_context_get_default": [ "resource stream_context_get_default([array options])", "Get a handle on the default file/stream context and optionally set parameters" ], "stream_context_get_options": [ "array stream_context_get_options(resource context|resource stream)", "Retrieve options for a stream/wrapper/context" ], "stream_context_get_params": [ "array stream_context_get_params(resource context|resource stream)", "Get parameters of a file context" ], "stream_context_set_default": [ "resource stream_context_set_default(array options)", "Set default file/stream context, returns the context as a resource" ], "stream_context_set_option": [ "bool stream_context_set_option(resource context|resource stream, string wrappername, string optionname, mixed value)", "Set an option for a wrapper" ], "stream_context_set_params": [ "bool stream_context_set_params(resource context|resource stream, array options)", "Set parameters for a file context" ], "stream_copy_to_stream": [ "long stream_copy_to_stream(resource source, resource dest [, long maxlen [, long pos]])", "Reads up to maxlen bytes from source stream and writes them to dest stream." ], "stream_filter_append": [ "resource stream_filter_append(resource stream, string filtername[, int read_write[, string filterparams]])", "Append a filter to a stream" ], "stream_filter_prepend": [ "resource stream_filter_prepend(resource stream, string filtername[, int read_write[, string filterparams]])", "Prepend a filter to a stream" ], "stream_filter_register": [ "bool stream_filter_register(string filtername, string classname)", "Registers a custom filter handler class" ], "stream_filter_remove": [ "bool stream_filter_remove(resource stream_filter)", "Flushes any data in the filter's internal buffer, removes it from the chain, and frees the resource" ], "stream_get_contents": [ "string stream_get_contents(resource source [, long maxlen [, long offset]])", "Reads all remaining bytes (or up to maxlen bytes) from a stream and returns them as a string." ], "stream_get_filters": [ "array stream_get_filters(void)", "Returns a list of registered filters" ], "stream_get_line": [ "string stream_get_line(resource stream, int maxlen [, string ending])", "Read up to maxlen bytes from a stream or until the ending string is found" ], "stream_get_meta_data": [ "array stream_get_meta_data(resource fp)", "Retrieves header/meta data from streams/file pointers" ], "stream_get_transports": [ "array stream_get_transports()", "Retrieves list of registered socket transports" ], "stream_get_wrappers": [ "array stream_get_wrappers()", "Retrieves list of registered stream wrappers" ], "stream_is_local": [ "bool stream_is_local(resource stream|string url)", "" ], "stream_resolve_include_path": [ "string stream_resolve_include_path(string filename)", "Determine what file will be opened by calls to fopen() with a relative path" ], "stream_select": [ "int stream_select(array &read_streams, array &write_streams, array &except_streams, int tv_sec[, int tv_usec])", "Runs the select() system call on the sets of streams with a timeout specified by tv_sec and tv_usec" ], "stream_set_blocking": [ "bool stream_set_blocking(resource socket, int mode)", "Set blocking/non-blocking mode on a socket or stream" ], "stream_set_timeout": [ "bool stream_set_timeout(resource stream, int seconds [, int microseconds])", "Set timeout on stream read to seconds + microseonds" ], "stream_set_write_buffer": [ "int stream_set_write_buffer(resource fp, int buffer)", "Set file write buffer" ], "stream_socket_accept": [ "resource stream_socket_accept(resource serverstream, [ double timeout [, string &peername ]])", "Accept a client connection from a server socket" ], "stream_socket_client": [ "resource stream_socket_client(string remoteaddress [, long &errcode [, string &errstring [, double timeout [, long flags [, resource context]]]]])", "Open a client connection to a remote address" ], "stream_socket_enable_crypto": [ "int stream_socket_enable_crypto(resource stream, bool enable [, int cryptokind [, resource sessionstream]])", "Enable or disable a specific kind of crypto on the stream" ], "stream_socket_get_name": [ "string stream_socket_get_name(resource stream, bool want_peer)", "Returns either the locally bound or remote name for a socket stream" ], "stream_socket_pair": [ "array stream_socket_pair(int domain, int type, int protocol)", "Creates a pair of connected, indistinguishable socket streams" ], "stream_socket_recvfrom": [ "string stream_socket_recvfrom(resource stream, long amount [, long flags [, string &remote_addr]])", "Receives data from a socket stream" ], "stream_socket_sendto": [ "long stream_socket_sendto(resouce stream, string data [, long flags [, string target_addr]])", "Send data to a socket stream. If target_addr is specified it must be in dotted quad (or [ipv6]) format" ], "stream_socket_server": [ "resource stream_socket_server(string localaddress [, long &errcode [, string &errstring [, long flags [, resource context]]]])", "Create a server socket bound to localaddress" ], "stream_socket_shutdown": [ "int stream_socket_shutdown(resource stream, int how)", "causes all or part of a full-duplex connection on the socket associated with stream to be shut down. If how is SHUT_RD, further receptions will be disallowed. If how is SHUT_WR, further transmissions will be disallowed. If how is SHUT_RDWR, further receptions and transmissions will be disallowed." ], "stream_supports_lock": [ "bool stream_supports_lock(resource stream)", "Tells wether the stream supports locking through flock()." ], "stream_wrapper_register": [ "bool stream_wrapper_register(string protocol, string classname[, integer flags])", "Registers a custom URL protocol handler class" ], "stream_wrapper_restore": [ "bool stream_wrapper_restore(string protocol)", "Restore the original protocol handler, overriding if necessary" ], "stream_wrapper_unregister": [ "bool stream_wrapper_unregister(string protocol)", "Unregister a wrapper for the life of the current request." ], "strftime": [ "string strftime(string format [, int timestamp])", "Format a local time/date according to locale settings" ], "strip_tags": [ "string strip_tags(string str [, string allowable_tags])", "Strips HTML and PHP tags from a string" ], "stripcslashes": [ "string stripcslashes(string str)", "Strips backslashes from a string. Uses C-style conventions" ], "stripos": [ "int stripos(string haystack, string needle [, int offset])", "Finds position of first occurrence of a string within another, case insensitive" ], "stripslashes": [ "string stripslashes(string str)", "Strips backslashes from a string" ], "stristr": [ "string stristr(string haystack, string needle[, bool part])", "Finds first occurrence of a string within another, case insensitive" ], "strlen": [ "int strlen(string str)", "Get string length" ], "strnatcasecmp": [ "int strnatcasecmp(string s1, string s2)", "Returns the result of case-insensitive string comparison using 'natural' algorithm" ], "strnatcmp": [ "int strnatcmp(string s1, string s2)", "Returns the result of string comparison using 'natural' algorithm" ], "strncasecmp": [ "int strncasecmp(string str1, string str2, int len)", "Binary safe string comparison" ], "strncmp": [ "int strncmp(string str1, string str2, int len)", "Binary safe string comparison" ], "strpbrk": [ "array strpbrk(string haystack, string char_list)", "Search a string for any of a set of characters" ], "strpos": [ "int strpos(string haystack, string needle [, int offset])", "Finds position of first occurrence of a string within another" ], "strptime": [ "string strptime(string timestamp, string format)", "Parse a time/date generated with strftime()" ], "strrchr": [ "string strrchr(string haystack, string needle)", "Finds the last occurrence of a character in a string within another" ], "strrev": [ "string strrev(string str)", "Reverse a string" ], "strripos": [ "int strripos(string haystack, string needle [, int offset])", "Finds position of last occurrence of a string within another string" ], "strrpos": [ "int strrpos(string haystack, string needle [, int offset])", "Finds position of last occurrence of a string within another string" ], "strspn": [ "int strspn(string str, string mask [, start [, len]])", "Finds length of initial segment consisting entirely of characters found in mask. If start or/and length is provided works like strspn(substr($s,$start,$len),$good_chars)" ], "strstr": [ "string strstr(string haystack, string needle[, bool part])", "Finds first occurrence of a string within another" ], "strtok": [ "string strtok([string str,] string token)", "Tokenize a string" ], "strtolower": [ "string strtolower(string str)", "Makes a string lowercase" ], "strtotime": [ "int strtotime(string time [, int now ])", "Convert string representation of date and time to a timestamp" ], "strtoupper": [ "string strtoupper(string str)", "Makes a string uppercase" ], "strtr": [ "string strtr(string str, string from[, string to])", "Translates characters in str using given translation tables" ], "strval": [ "string strval(mixed var)", "Get the string value of a variable" ], "substr": [ "string substr(string str, int start [, int length])", "Returns part of a string" ], "substr_compare": [ "int substr_compare(string main_str, string str, int offset [, int length [, bool case_sensitivity]])", "Binary safe optionally case insensitive comparison of 2 strings from an offset, up to length characters" ], "substr_count": [ "int substr_count(string haystack, string needle [, int offset [, int length]])", "Returns the number of times a substring occurs in the string" ], "substr_replace": [ "mixed substr_replace(mixed str, mixed repl, mixed start [, mixed length])", "Replaces part of a string with another string" ], "sybase_affected_rows": [ "int sybase_affected_rows([resource link_id])", "Get number of affected rows in last query" ], "sybase_close": [ "bool sybase_close([resource link_id])", "Close Sybase connection" ], "sybase_connect": [ "int sybase_connect([string host [, string user [, string password [, string charset [, string appname [, bool new]]]]]])", "Open Sybase server connection" ], "sybase_data_seek": [ "bool sybase_data_seek(resource result, int offset)", "Move internal row pointer" ], "sybase_deadlock_retry_count": [ "void sybase_deadlock_retry_count(int retry_count)", "Sets deadlock retry count" ], "sybase_fetch_array": [ "array sybase_fetch_array(resource result)", "Fetch row as array" ], "sybase_fetch_assoc": [ "array sybase_fetch_assoc(resource result)", "Fetch row as array without numberic indices" ], "sybase_fetch_field": [ "object sybase_fetch_field(resource result [, int offset])", "Get field information" ], "sybase_fetch_object": [ "object sybase_fetch_object(resource result [, mixed object])", "Fetch row as object" ], "sybase_fetch_row": [ "array sybase_fetch_row(resource result)", "Get row as enumerated array" ], "sybase_field_seek": [ "bool sybase_field_seek(resource result, int offset)", "Set field offset" ], "sybase_free_result": [ "bool sybase_free_result(resource result)", "Free result memory" ], "sybase_get_last_message": [ "string sybase_get_last_message(void)", "Returns the last message from server (over min_message_severity)" ], "sybase_min_client_severity": [ "void sybase_min_client_severity(int severity)", "Sets minimum client severity" ], "sybase_min_server_severity": [ "void sybase_min_server_severity(int severity)", "Sets minimum server severity" ], "sybase_num_fields": [ "int sybase_num_fields(resource result)", "Get number of fields in result" ], "sybase_num_rows": [ "int sybase_num_rows(resource result)", "Get number of rows in result" ], "sybase_pconnect": [ "int sybase_pconnect([string host [, string user [, string password [, string charset [, string appname]]]]])", "Open persistent Sybase connection" ], "sybase_query": [ "int sybase_query(string query [, resource link_id])", "Send Sybase query" ], "sybase_result": [ "string sybase_result(resource result, int row, mixed field)", "Get result data" ], "sybase_select_db": [ "bool sybase_select_db(string database [, resource link_id])", "Select Sybase database" ], "sybase_set_message_handler": [ "bool sybase_set_message_handler(mixed error_func [, resource connection])", "Set the error handler, to be called when a server message is raised. If error_func is NULL the handler will be deleted" ], "sybase_unbuffered_query": [ "int sybase_unbuffered_query(string query [, resource link_id])", "Send Sybase query" ], "symlink": [ "int symlink(string target, string link)", "Create a symbolic link" ], "sys_get_temp_dir": [ "string sys_get_temp_dir()", "Returns directory path used for temporary files" ], "sys_getloadavg": [ "array sys_getloadavg()", "" ], "syslog": [ "bool syslog(int priority, string message)", "Generate a system log message" ], "system": [ "int system(string command [, int &return_value])", "Execute an external program and display output" ], "tan": [ "float tan(float number)", "Returns the tangent of the number in radians" ], "tanh": [ "float tanh(float number)", "Returns the hyperbolic tangent of the number, defined as sinh(number)/cosh(number)" ], "tempnam": [ "string tempnam(string dir, string prefix)", "Create a unique filename in a directory" ], "textdomain": [ "string textdomain(string domain)", "Set the textdomain to \"domain\". Returns the current domain" ], "tidy_access_count": [ "int tidy_access_count()", "Returns the Number of Tidy accessibility warnings encountered for specified document." ], "tidy_clean_repair": [ "boolean tidy_clean_repair()", "Execute configured cleanup and repair operations on parsed markup" ], "tidy_config_count": [ "int tidy_config_count()", "Returns the Number of Tidy configuration errors encountered for specified document." ], "tidy_diagnose": [ "boolean tidy_diagnose()", "Run configured diagnostics on parsed and repaired markup." ], "tidy_error_count": [ "int tidy_error_count()", "Returns the Number of Tidy errors encountered for specified document." ], "tidy_get_body": [ "TidyNode tidy_get_body(resource tidy)", "Returns a TidyNode Object starting from the <BODY> tag of the tidy parse tree" ], "tidy_get_config": [ "array tidy_get_config()", "Get current Tidy configuarion" ], "tidy_get_error_buffer": [ "string tidy_get_error_buffer([boolean detailed])", "Return warnings and errors which occured parsing the specified document" ], "tidy_get_head": [ "TidyNode tidy_get_head()", "Returns a TidyNode Object starting from the <HEAD> tag of the tidy parse tree" ], "tidy_get_html": [ "TidyNode tidy_get_html()", "Returns a TidyNode Object starting from the <HTML> tag of the tidy parse tree" ], "tidy_get_html_ver": [ "int tidy_get_html_ver()", "Get the Detected HTML version for the specified document." ], "tidy_get_opt_doc": [ "string tidy_get_opt_doc(tidy resource, string optname)", "Returns the documentation for the given option name" ], "tidy_get_output": [ "string tidy_get_output()", "Return a string representing the parsed tidy markup" ], "tidy_get_release": [ "string tidy_get_release()", "Get release date (version) for Tidy library" ], "tidy_get_root": [ "TidyNode tidy_get_root()", "Returns a TidyNode Object representing the root of the tidy parse tree" ], "tidy_get_status": [ "int tidy_get_status()", "Get status of specfied document." ], "tidy_getopt": [ "mixed tidy_getopt(string option)", "Returns the value of the specified configuration option for the tidy document." ], "tidy_is_xhtml": [ "boolean tidy_is_xhtml()", "Indicates if the document is a XHTML document." ], "tidy_is_xml": [ "boolean tidy_is_xml()", "Indicates if the document is a generic (non HTML/XHTML) XML document." ], "tidy_parse_file": [ "boolean tidy_parse_file(string file [, mixed config_options [, string encoding [, bool use_include_path]]])", "Parse markup in file or URI" ], "tidy_parse_string": [ "bool tidy_parse_string(string input [, mixed config_options [, string encoding]])", "Parse a document stored in a string" ], "tidy_repair_file": [ "boolean tidy_repair_file(string filename [, mixed config_file [, string encoding [, bool use_include_path]]])", "Repair a file using an optionally provided configuration file" ], "tidy_repair_string": [ "boolean tidy_repair_string(string data [, mixed config_file [, string encoding]])", "Repair a string using an optionally provided configuration file" ], "tidy_warning_count": [ "int tidy_warning_count()", "Returns the Number of Tidy warnings encountered for specified document." ], "time": [ "int time(void)", "Return current UNIX timestamp" ], "time_nanosleep": [ "mixed time_nanosleep(long seconds, long nanoseconds)", "Delay for a number of seconds and nano seconds" ], "time_sleep_until": [ "mixed time_sleep_until(float timestamp)", "Make the script sleep until the specified time" ], "timezone_abbreviations_list": [ "array timezone_abbreviations_list()", "Returns associative array containing dst, offset and the timezone name" ], "timezone_identifiers_list": [ "array timezone_identifiers_list([long what[, string country]])", "Returns numerically index array with all timezone identifiers." ], "timezone_location_get": [ "array timezone_location_get()", "Returns location information for a timezone, including country code, latitude/longitude and comments" ], "timezone_name_from_abbr": [ "string timezone_name_from_abbr(string abbr[, long gmtOffset[, long isdst]])", "Returns the timezone name from abbrevation" ], "timezone_name_get": [ "string timezone_name_get(DateTimeZone object)", "Returns the name of the timezone." ], "timezone_offset_get": [ "long timezone_offset_get(DateTimeZone object, DateTime object)", "Returns the timezone offset." ], "timezone_open": [ "DateTimeZone timezone_open(string timezone)", "Returns new DateTimeZone object" ], "timezone_transitions_get": [ "array timezone_transitions_get(DateTimeZone object [, long timestamp_begin [, long timestamp_end ]])", "Returns numerically indexed array containing associative array for all transitions in the specified range for the timezone." ], "timezone_version_get": [ "array timezone_version_get()", "Returns the Olson database version number." ], "tmpfile": [ "resource tmpfile(void)", "Create a temporary file that will be deleted automatically after use" ], "token_get_all": [ "array token_get_all(string source)", "" ], "token_name": [ "string token_name(int type)", "" ], "touch": [ "bool touch(string filename [, int time [, int atime]])", "Set modification time of file" ], "trigger_error": [ "void trigger_error(string messsage [, int error_type])", "Generates a user-level error/warning/notice message" ], "trim": [ "string trim(string str [, string character_mask])", "Strips whitespace from the beginning and end of a string" ], "uasort": [ "bool uasort(array array_arg, string cmp_function)", "Sort an array with a user-defined comparison function and maintain index association" ], "ucfirst": [ "string ucfirst(string str)", "Make a string's first character lowercase" ], "ucwords": [ "string ucwords(string str)", "Uppercase the first character of every word in a string" ], "uksort": [ "bool uksort(array array_arg, string cmp_function)", "Sort an array by keys using a user-defined comparison function" ], "umask": [ "int umask([int mask])", "Return or change the umask" ], "uniqid": [ "string uniqid([string prefix [, bool more_entropy]])", "Generates a unique ID" ], "unixtojd": [ "int unixtojd([int timestamp])", "Convert UNIX timestamp to Julian Day" ], "unlink": [ "bool unlink(string filename[, context context])", "Delete a file" ], "unpack": [ "array unpack(string format, string input)", "Unpack binary string into named array elements according to format argument" ], "unregister_tick_function": [ "void unregister_tick_function(string function_name)", "Unregisters a tick callback function" ], "unserialize": [ "mixed unserialize(string variable_representation)", "Takes a string representation of variable and recreates it" ], "unset": [ "void unset (mixed var [, mixed var])", "Unset a given variable" ], "urldecode": [ "string urldecode(string str)", "Decodes URL-encoded string" ], "urlencode": [ "string urlencode(string str)", "URL-encodes string" ], "usleep": [ "void usleep(int micro_seconds)", "Delay for a given number of micro seconds" ], "usort": [ "bool usort(array array_arg, string cmp_function)", "Sort an array by values using a user-defined comparison function" ], "utf8_decode": [ "string utf8_decode(string data)", "Converts a UTF-8 encoded string to ISO-8859-1" ], "utf8_encode": [ "string utf8_encode(string data)", "Encodes an ISO-8859-1 string to UTF-8" ], "var_dump": [ "void var_dump(mixed var)", "Dumps a string representation of variable to output" ], "var_export": [ "mixed var_export(mixed var [, bool return])", "Outputs or returns a string representation of a variable" ], "variant_abs": [ "mixed variant_abs(mixed left)", "Returns the absolute value of a variant" ], "variant_add": [ "mixed variant_add(mixed left, mixed right)", "\"Adds\" two variant values together and returns the result" ], "variant_and": [ "mixed variant_and(mixed left, mixed right)", "performs a bitwise AND operation between two variants and returns the result" ], "variant_cast": [ "object variant_cast(object variant, int type)", "Convert a variant into a new variant object of another type" ], "variant_cat": [ "mixed variant_cat(mixed left, mixed right)", "concatenates two variant values together and returns the result" ], "variant_cmp": [ "int variant_cmp(mixed left, mixed right [, int lcid [, int flags]])", "Compares two variants" ], "variant_date_from_timestamp": [ "object variant_date_from_timestamp(int timestamp)", "Returns a variant date representation of a unix timestamp" ], "variant_date_to_timestamp": [ "int variant_date_to_timestamp(object variant)", "Converts a variant date/time value to unix timestamp" ], "variant_div": [ "mixed variant_div(mixed left, mixed right)", "Returns the result from dividing two variants" ], "variant_eqv": [ "mixed variant_eqv(mixed left, mixed right)", "Performs a bitwise equivalence on two variants" ], "variant_fix": [ "mixed variant_fix(mixed left)", "Returns the integer part ? of a variant" ], "variant_get_type": [ "int variant_get_type(object variant)", "Returns the VT_XXX type code for a variant" ], "variant_idiv": [ "mixed variant_idiv(mixed left, mixed right)", "Converts variants to integers and then returns the result from dividing them" ], "variant_imp": [ "mixed variant_imp(mixed left, mixed right)", "Performs a bitwise implication on two variants" ], "variant_int": [ "mixed variant_int(mixed left)", "Returns the integer portion of a variant" ], "variant_mod": [ "mixed variant_mod(mixed left, mixed right)", "Divides two variants and returns only the remainder" ], "variant_mul": [ "mixed variant_mul(mixed left, mixed right)", "multiplies the values of the two variants and returns the result" ], "variant_neg": [ "mixed variant_neg(mixed left)", "Performs logical negation on a variant" ], "variant_not": [ "mixed variant_not(mixed left)", "Performs bitwise not negation on a variant" ], "variant_or": [ "mixed variant_or(mixed left, mixed right)", "Performs a logical disjunction on two variants" ], "variant_pow": [ "mixed variant_pow(mixed left, mixed right)", "Returns the result of performing the power function with two variants" ], "variant_round": [ "mixed variant_round(mixed left, int decimals)", "Rounds a variant to the specified number of decimal places" ], "variant_set": [ "void variant_set(object variant, mixed value)", "Assigns a new value for a variant object" ], "variant_set_type": [ "void variant_set_type(object variant, int type)", "Convert a variant into another type. Variant is modified \"in-place\"" ], "variant_sub": [ "mixed variant_sub(mixed left, mixed right)", "subtracts the value of the right variant from the left variant value and returns the result" ], "variant_xor": [ "mixed variant_xor(mixed left, mixed right)", "Performs a logical exclusion on two variants" ], "version_compare": [ "int version_compare(string ver1, string ver2 [, string oper])", "Compares two \"PHP-standardized\" version number strings" ], "vfprintf": [ "int vfprintf(resource stream, string format, array args)", "Output a formatted string into a stream" ], "virtual": [ "bool virtual(string filename)", "Perform an Apache sub-request" ], "vprintf": [ "int vprintf(string format, array args)", "Output a formatted string" ], "vsprintf": [ "string vsprintf(string format, array args)", "Return a formatted string" ], "wddx_add_vars": [ "int wddx_add_vars(resource packet_id, mixed var_names [, mixed ...])", "Serializes given variables and adds them to packet given by packet_id" ], "wddx_deserialize": [ "mixed wddx_deserialize(mixed packet)", "Deserializes given packet and returns a PHP value" ], "wddx_packet_end": [ "string wddx_packet_end(resource packet_id)", "Ends specified WDDX packet and returns the string containing the packet" ], "wddx_packet_start": [ "resource wddx_packet_start([string comment])", "Starts a WDDX packet with optional comment and returns the packet id" ], "wddx_serialize_value": [ "string wddx_serialize_value(mixed var [, string comment])", "Creates a new packet and serializes the given value" ], "wddx_serialize_vars": [ "string wddx_serialize_vars(mixed var_name [, mixed ...])", "Creates a new packet and serializes given variables into a struct" ], "wordwrap": [ "string wordwrap(string str [, int width [, string break [, boolean cut]]])", "Wraps buffer to selected number of characters using string break char" ], "xml_error_string": [ "string xml_error_string(int code)", "Get XML parser error string" ], "xml_get_current_byte_index": [ "int xml_get_current_byte_index(resource parser)", "Get current byte index for an XML parser" ], "xml_get_current_column_number": [ "int xml_get_current_column_number(resource parser)", "Get current column number for an XML parser" ], "xml_get_current_line_number": [ "int xml_get_current_line_number(resource parser)", "Get current line number for an XML parser" ], "xml_get_error_code": [ "int xml_get_error_code(resource parser)", "Get XML parser error code" ], "xml_parse": [ "int xml_parse(resource parser, string data [, int isFinal])", "Start parsing an XML document" ], "xml_parse_into_struct": [ "int xml_parse_into_struct(resource parser, string data, array &values [, array &index ])", "Parsing a XML document" ], "xml_parser_create": [ "resource xml_parser_create([string encoding])", "Create an XML parser" ], "xml_parser_create_ns": [ "resource xml_parser_create_ns([string encoding [, string sep]])", "Create an XML parser" ], "xml_parser_free": [ "int xml_parser_free(resource parser)", "Free an XML parser" ], "xml_parser_get_option": [ "int xml_parser_get_option(resource parser, int option)", "Get options from an XML parser" ], "xml_parser_set_option": [ "int xml_parser_set_option(resource parser, int option, mixed value)", "Set options in an XML parser" ], "xml_set_character_data_handler": [ "int xml_set_character_data_handler(resource parser, string hdl)", "Set up character data handler" ], "xml_set_default_handler": [ "int xml_set_default_handler(resource parser, string hdl)", "Set up default handler" ], "xml_set_element_handler": [ "int xml_set_element_handler(resource parser, string shdl, string ehdl)", "Set up start and end element handlers" ], "xml_set_end_namespace_decl_handler": [ "int xml_set_end_namespace_decl_handler(resource parser, string hdl)", "Set up character data handler" ], "xml_set_external_entity_ref_handler": [ "int xml_set_external_entity_ref_handler(resource parser, string hdl)", "Set up external entity reference handler" ], "xml_set_notation_decl_handler": [ "int xml_set_notation_decl_handler(resource parser, string hdl)", "Set up notation declaration handler" ], "xml_set_object": [ "int xml_set_object(resource parser, object &obj)", "Set up object which should be used for callbacks" ], "xml_set_processing_instruction_handler": [ "int xml_set_processing_instruction_handler(resource parser, string hdl)", "Set up processing instruction (PI) handler" ], "xml_set_start_namespace_decl_handler": [ "int xml_set_start_namespace_decl_handler(resource parser, string hdl)", "Set up character data handler" ], "xml_set_unparsed_entity_decl_handler": [ "int xml_set_unparsed_entity_decl_handler(resource parser, string hdl)", "Set up unparsed entity declaration handler" ], "xmlrpc_decode": [ "array xmlrpc_decode(string xml [, string encoding])", "Decodes XML into native PHP types" ], "xmlrpc_decode_request": [ "array xmlrpc_decode_request(string xml, string& method [, string encoding])", "Decodes XML into native PHP types" ], "xmlrpc_encode": [ "string xmlrpc_encode(mixed value)", "Generates XML for a PHP value" ], "xmlrpc_encode_request": [ "string xmlrpc_encode_request(string method, mixed params [, array output_options])", "Generates XML for a method request" ], "xmlrpc_get_type": [ "string xmlrpc_get_type(mixed value)", "Gets xmlrpc type for a PHP value. Especially useful for base64 and datetime strings" ], "xmlrpc_is_fault": [ "bool xmlrpc_is_fault(array)", "Determines if an array value represents an XMLRPC fault." ], "xmlrpc_parse_method_descriptions": [ "array xmlrpc_parse_method_descriptions(string xml)", "Decodes XML into a list of method descriptions" ], "xmlrpc_server_add_introspection_data": [ "int xmlrpc_server_add_introspection_data(resource server, array desc)", "Adds introspection documentation" ], "xmlrpc_server_call_method": [ "mixed xmlrpc_server_call_method(resource server, string xml, mixed user_data [, array output_options])", "Parses XML requests and call methods" ], "xmlrpc_server_create": [ "resource xmlrpc_server_create(void)", "Creates an xmlrpc server" ], "xmlrpc_server_destroy": [ "int xmlrpc_server_destroy(resource server)", "Destroys server resources" ], "xmlrpc_server_register_introspection_callback": [ "bool xmlrpc_server_register_introspection_callback(resource server, string function)", "Register a PHP function to generate documentation" ], "xmlrpc_server_register_method": [ "bool xmlrpc_server_register_method(resource server, string method_name, string function)", "Register a PHP function to handle method matching method_name" ], "xmlrpc_set_type": [ "bool xmlrpc_set_type(string value, string type)", "Sets xmlrpc type, base64 or datetime, for a PHP string value" ], "xmlwriter_end_attribute": [ "bool xmlwriter_end_attribute(resource xmlwriter)", "End attribute - returns FALSE on error" ], "xmlwriter_end_cdata": [ "bool xmlwriter_end_cdata(resource xmlwriter)", "End current CDATA - returns FALSE on error" ], "xmlwriter_end_comment": [ "bool xmlwriter_end_comment(resource xmlwriter)", "Create end comment - returns FALSE on error" ], "xmlwriter_end_document": [ "bool xmlwriter_end_document(resource xmlwriter)", "End current document - returns FALSE on error" ], "xmlwriter_end_dtd": [ "bool xmlwriter_end_dtd(resource xmlwriter)", "End current DTD - returns FALSE on error" ], "xmlwriter_end_dtd_attlist": [ "bool xmlwriter_end_dtd_attlist(resource xmlwriter)", "End current DTD AttList - returns FALSE on error" ], "xmlwriter_end_dtd_element": [ "bool xmlwriter_end_dtd_element(resource xmlwriter)", "End current DTD element - returns FALSE on error" ], "xmlwriter_end_dtd_entity": [ "bool xmlwriter_end_dtd_entity(resource xmlwriter)", "End current DTD Entity - returns FALSE on error" ], "xmlwriter_end_element": [ "bool xmlwriter_end_element(resource xmlwriter)", "End current element - returns FALSE on error" ], "xmlwriter_end_pi": [ "bool xmlwriter_end_pi(resource xmlwriter)", "End current PI - returns FALSE on error" ], "xmlwriter_flush": [ "mixed xmlwriter_flush(resource xmlwriter [,bool empty])", "Output current buffer" ], "xmlwriter_full_end_element": [ "bool xmlwriter_full_end_element(resource xmlwriter)", "End current element - returns FALSE on error" ], "xmlwriter_open_memory": [ "resource xmlwriter_open_memory()", "Create new xmlwriter using memory for string output" ], "xmlwriter_open_uri": [ "resource xmlwriter_open_uri(resource xmlwriter, string source)", "Create new xmlwriter using source uri for output" ], "xmlwriter_output_memory": [ "string xmlwriter_output_memory(resource xmlwriter [,bool flush])", "Output current buffer as string" ], "xmlwriter_set_indent": [ "bool xmlwriter_set_indent(resource xmlwriter, bool indent)", "Toggle indentation on/off - returns FALSE on error" ], "xmlwriter_set_indent_string": [ "bool xmlwriter_set_indent_string(resource xmlwriter, string indentString)", "Set string used for indenting - returns FALSE on error" ], "xmlwriter_start_attribute": [ "bool xmlwriter_start_attribute(resource xmlwriter, string name)", "Create start attribute - returns FALSE on error" ], "xmlwriter_start_attribute_ns": [ "bool xmlwriter_start_attribute_ns(resource xmlwriter, string prefix, string name, string uri)", "Create start namespaced attribute - returns FALSE on error" ], "xmlwriter_start_cdata": [ "bool xmlwriter_start_cdata(resource xmlwriter)", "Create start CDATA tag - returns FALSE on error" ], "xmlwriter_start_comment": [ "bool xmlwriter_start_comment(resource xmlwriter)", "Create start comment - returns FALSE on error" ], "xmlwriter_start_document": [ "bool xmlwriter_start_document(resource xmlwriter, string version, string encoding, string standalone)", "Create document tag - returns FALSE on error" ], "xmlwriter_start_dtd": [ "bool xmlwriter_start_dtd(resource xmlwriter, string name, string pubid, string sysid)", "Create start DTD tag - returns FALSE on error" ], "xmlwriter_start_dtd_attlist": [ "bool xmlwriter_start_dtd_attlist(resource xmlwriter, string name)", "Create start DTD AttList - returns FALSE on error" ], "xmlwriter_start_dtd_element": [ "bool xmlwriter_start_dtd_element(resource xmlwriter, string name)", "Create start DTD element - returns FALSE on error" ], "xmlwriter_start_dtd_entity": [ "bool xmlwriter_start_dtd_entity(resource xmlwriter, string name, bool isparam)", "Create start DTD Entity - returns FALSE on error" ], "xmlwriter_start_element": [ "bool xmlwriter_start_element(resource xmlwriter, string name)", "Create start element tag - returns FALSE on error" ], "xmlwriter_start_element_ns": [ "bool xmlwriter_start_element_ns(resource xmlwriter, string prefix, string name, string uri)", "Create start namespaced element tag - returns FALSE on error" ], "xmlwriter_start_pi": [ "bool xmlwriter_start_pi(resource xmlwriter, string target)", "Create start PI tag - returns FALSE on error" ], "xmlwriter_text": [ "bool xmlwriter_text(resource xmlwriter, string content)", "Write text - returns FALSE on error" ], "xmlwriter_write_attribute": [ "bool xmlwriter_write_attribute(resource xmlwriter, string name, string content)", "Write full attribute - returns FALSE on error" ], "xmlwriter_write_attribute_ns": [ "bool xmlwriter_write_attribute_ns(resource xmlwriter, string prefix, string name, string uri, string content)", "Write full namespaced attribute - returns FALSE on error" ], "xmlwriter_write_cdata": [ "bool xmlwriter_write_cdata(resource xmlwriter, string content)", "Write full CDATA tag - returns FALSE on error" ], "xmlwriter_write_comment": [ "bool xmlwriter_write_comment(resource xmlwriter, string content)", "Write full comment tag - returns FALSE on error" ], "xmlwriter_write_dtd": [ "bool xmlwriter_write_dtd(resource xmlwriter, string name, string pubid, string sysid, string subset)", "Write full DTD tag - returns FALSE on error" ], "xmlwriter_write_dtd_attlist": [ "bool xmlwriter_write_dtd_attlist(resource xmlwriter, string name, string content)", "Write full DTD AttList tag - returns FALSE on error" ], "xmlwriter_write_dtd_element": [ "bool xmlwriter_write_dtd_element(resource xmlwriter, string name, string content)", "Write full DTD element tag - returns FALSE on error" ], "xmlwriter_write_dtd_entity": [ "bool xmlwriter_write_dtd_entity(resource xmlwriter, string name, string content [, int pe [, string pubid [, string sysid [, string ndataid]]]])", "Write full DTD Entity tag - returns FALSE on error" ], "xmlwriter_write_element": [ "bool xmlwriter_write_element(resource xmlwriter, string name[, string content])", "Write full element tag - returns FALSE on error" ], "xmlwriter_write_element_ns": [ "bool xmlwriter_write_element_ns(resource xmlwriter, string prefix, string name, string uri[, string content])", "Write full namesapced element tag - returns FALSE on error" ], "xmlwriter_write_pi": [ "bool xmlwriter_write_pi(resource xmlwriter, string target, string content)", "Write full PI tag - returns FALSE on error" ], "xmlwriter_write_raw": [ "bool xmlwriter_write_raw(resource xmlwriter, string content)", "Write text - returns FALSE on error" ], "xsl_xsltprocessor_get_parameter": [ "string xsl_xsltprocessor_get_parameter(string namespace, string name);", "" ], "xsl_xsltprocessor_has_exslt_support": [ "bool xsl_xsltprocessor_has_exslt_support();", "" ], "xsl_xsltprocessor_import_stylesheet": [ "void xsl_xsltprocessor_import_stylesheet(domdocument doc);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html# Since:" ], "xsl_xsltprocessor_register_php_functions": [ "void xsl_xsltprocessor_register_php_functions([mixed $restrict]);", "" ], "xsl_xsltprocessor_remove_parameter": [ "bool xsl_xsltprocessor_remove_parameter(string namespace, string name);", "" ], "xsl_xsltprocessor_set_parameter": [ "bool xsl_xsltprocessor_set_parameter(string namespace, mixed name [, string value]);", "" ], "xsl_xsltprocessor_set_profiling": [ "bool xsl_xsltprocessor_set_profiling(string filename) */", "PHP_FUNCTION(xsl_xsltprocessor_set_profiling) { zval *id; xsl_object *intern; char *filename = NULL; int filename_len; DOM_GET_THIS(id); if (zend_parse_parameters_ex(ZEND_PARSE_PARAMS_QUIET, ZEND_NUM_ARGS() TSRMLS_CC, \"s!\", &filename, &filename_len) == SUCCESS) { intern = (xsl_object *)zend_object_store_get_object(id TSRMLS_CC); if (intern->profiling) { efree(intern->profiling); } if (filename != NULL) { intern->profiling = estrndup(filename,filename_len); } else { intern->profiling = NULL; } RETURN_TRUE; } else { WRONG_PARAM_COUNT; } } /* }}} end xsl_xsltprocessor_set_profiling" ], "xsl_xsltprocessor_transform_to_doc": [ "domdocument xsl_xsltprocessor_transform_to_doc(domnode doc);", "URL: http://www.w3.org/TR/2003/WD-DOM-Level-3-Core-20030226/DOM3-Core.html# Since:" ], "xsl_xsltprocessor_transform_to_uri": [ "int xsl_xsltprocessor_transform_to_uri(domdocument doc, string uri);", "" ], "xsl_xsltprocessor_transform_to_xml": [ "string xsl_xsltprocessor_transform_to_xml(domdocument doc);", "" ], "zend_logo_guid": [ "string zend_logo_guid(void)", "Return the special ID used to request the Zend logo in phpinfo screens" ], "zend_version": [ "string zend_version(void)", "Get the version of the Zend Engine" ], "zip_close": [ "void zip_close(resource zip)", "Close a Zip archive" ], "zip_entry_close": [ "void zip_entry_close(resource zip_ent)", "Close a zip entry" ], "zip_entry_compressedsize": [ "int zip_entry_compressedsize(resource zip_entry)", "Return the compressed size of a ZZip entry" ], "zip_entry_compressionmethod": [ "string zip_entry_compressionmethod(resource zip_entry)", "Return a string containing the compression method used on a particular entry" ], "zip_entry_filesize": [ "int zip_entry_filesize(resource zip_entry)", "Return the actual filesize of a ZZip entry" ], "zip_entry_name": [ "string zip_entry_name(resource zip_entry)", "Return the name given a ZZip entry" ], "zip_entry_open": [ "bool zip_entry_open(resource zip_dp, resource zip_entry [, string mode])", "Open a Zip File, pointed by the resource entry" ], "zip_entry_read": [ "mixed zip_entry_read(resource zip_entry [, int len])", "Read from an open directory entry" ], "zip_open": [ "resource zip_open(string filename)", "Create new zip using source uri for output" ], "zip_read": [ "resource zip_read(resource zip)", "Returns the next file in the archive" ], "zlib_get_coding_type": [ "string zlib_get_coding_type(void)", "Returns the coding type used for output compression" ] }; var variableMap = { "$_COOKIE": { type: "array" }, "$_ENV": { type: "array" }, "$_FILES": { type: "array" }, "$_GET": { type: "array" }, "$_POST": { type: "array" }, "$_REQUEST": { type: "array" }, "$_SERVER": { type: "array", value: { "DOCUMENT_ROOT": 1, "GATEWAY_INTERFACE": 1, "HTTP_ACCEPT": 1, "HTTP_ACCEPT_CHARSET": 1, "HTTP_ACCEPT_ENCODING": 1 , "HTTP_ACCEPT_LANGUAGE": 1, "HTTP_CONNECTION": 1, "HTTP_HOST": 1, "HTTP_REFERER": 1, "HTTP_USER_AGENT": 1, "PATH_TRANSLATED": 1, "PHP_SELF": 1, "QUERY_STRING": 1, "REMOTE_ADDR": 1, "REMOTE_PORT": 1, "REQUEST_METHOD": 1, "REQUEST_URI": 1, "SCRIPT_FILENAME": 1, "SCRIPT_NAME": 1, "SERVER_ADMIN": 1, "SERVER_NAME": 1, "SERVER_PORT": 1, "SERVER_PROTOCOL": 1, "SERVER_SIGNATURE": 1, "SERVER_SOFTWARE": 1 } }, "$_SESSION": { type: "array" }, "$GLOBALS": { type: "array" } }; function is(token, type) { return token.type.lastIndexOf(type) > -1; } var PhpCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (token.type==='identifier') return this.getFunctionCompletions(state, session, pos, prefix); if (is(token, "variable")) return this.getVariableCompletions(state, session, pos, prefix); var line = session.getLine(pos.row).substr(0, pos.column); if (token.type==='string' && /(\$[\w]*)\[["']([^'"]*)$/i.test(line)) return this.getArrayKeyCompletions(state, session, pos, prefix); return []; }; this.getFunctionCompletions = function(state, session, pos, prefix) { var functions = Object.keys(functionMap); return functions.map(function(func){ return { caption: func, snippet: func + '($0)', meta: "php function", score: Number.MAX_VALUE, docHTML: functionMap[func][1] }; }); }; this.getVariableCompletions = function(state, session, pos, prefix) { var variables = Object.keys(variableMap); return variables.map(function(variable){ return { caption: variable, value: variable, meta: "php variable", score: Number.MAX_VALUE }; }); }; this.getArrayKeyCompletions = function(state, session, pos, prefix) { var line = session.getLine(pos.row).substr(0, pos.column); var variable = line.match(/(\$[\w]*)\[["']([^'"]*)$/i)[1]; if (!variableMap[variable]) { return []; } var keys = []; if (variableMap[variable].type==='array' && variableMap[variable].value) keys = Object.keys(variableMap[variable].value); return keys.map(function(key) { return { caption: key, value: key, meta: "php array key", score: Number.MAX_VALUE }; }); }; }).call(PhpCompletions.prototype); exports.PhpCompletions = PhpCompletions; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_completions",["require","exports","module"], function(require, exports, module) { "use strict"; var propertyMap = { "background": {"#$0": 1}, "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, "background-image": {"url('/$0')": 1}, "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, "background-attachment": {"scroll": 1, "fixed": 1}, "background-size": {"cover": 1, "contain": 1}, "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, "border-color": {"#$0": 1}, "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, "border-collapse": {"collapse": 1, "separate": 1}, "bottom": {"px": 1, "em": 1, "%": 1}, "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, "empty-cells": {"show": 1, "hide": 1}, "float": {"left": 1, "right": 1, "none": 1}, "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, "font-size": {"px": 1, "em": 1, "%": 1}, "font-weight": {"bold": 1, "normal": 1}, "font-style": {"italic": 1, "normal": 1}, "font-variant": {"normal": 1, "small-caps": 1}, "height": {"px": 1, "em": 1, "%": 1}, "left": {"px": 1, "em": 1, "%": 1}, "letter-spacing": {"normal": 1}, "line-height": {"normal": 1}, "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, "margin": {"px": 1, "em": 1, "%": 1}, "margin-right": {"px": 1, "em": 1, "%": 1}, "margin-left": {"px": 1, "em": 1, "%": 1}, "margin-top": {"px": 1, "em": 1, "%": 1}, "margin-bottom": {"px": 1, "em": 1, "%": 1}, "max-height": {"px": 1, "em": 1, "%": 1}, "max-width": {"px": 1, "em": 1, "%": 1}, "min-height": {"px": 1, "em": 1, "%": 1}, "min-width": {"px": 1, "em": 1, "%": 1}, "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "padding": {"px": 1, "em": 1, "%": 1}, "padding-top": {"px": 1, "em": 1, "%": 1}, "padding-right": {"px": 1, "em": 1, "%": 1}, "padding-bottom": {"px": 1, "em": 1, "%": 1}, "padding-left": {"px": 1, "em": 1, "%": 1}, "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, "right": {"px": 1, "em": 1, "%": 1}, "table-layout": {"fixed": 1, "auto": 1}, "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, "top": {"px": 1, "em": 1, "%": 1}, "vertical-align": {"top": 1, "bottom": 1}, "visibility": {"hidden": 1, "visible": 1}, "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, "width": {"px": 1, "em": 1, "%": 1}, "word-spacing": {"normal": 1}, "filter": {"alpha(opacity=$0100)": 1}, "text-shadow": {"$02px 2px 2px #777": 1}, "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, "-moz-border-radius": 1, "-moz-border-radius-topright": 1, "-moz-border-radius-bottomright": 1, "-moz-border-radius-topleft": 1, "-moz-border-radius-bottomleft": 1, "-webkit-border-radius": 1, "-webkit-border-top-right-radius": 1, "-webkit-border-top-left-radius": 1, "-webkit-border-bottom-right-radius": 1, "-webkit-border-bottom-left-radius": 1, "-moz-box-shadow": 1, "-webkit-box-shadow": 1, "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } }; var CssCompletions = function() { }; (function() { this.completionsDefined = false; this.defineCompletions = function() { if (document) { var style = document.createElement('c').style; for (var i in style) { if (typeof style[i] !== 'string') continue; var name = i.replace(/[A-Z]/g, function(x) { return '-' + x.toLowerCase(); }); if (!propertyMap.hasOwnProperty(name)) propertyMap[name] = 1; } } this.completionsDefined = true; } this.getCompletions = function(state, session, pos, prefix) { if (!this.completionsDefined) { this.defineCompletions(); } var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (state==='ruleset'){ var line = session.getLine(pos.row).substr(0, pos.column); if (/:[^;]+$/.test(line)) { /([\w\-]+):[^:]*$/.test(line); return this.getPropertyValueCompletions(state, session, pos, prefix); } else { return this.getPropertyCompletions(state, session, pos, prefix); } } return []; }; this.getPropertyCompletions = function(state, session, pos, prefix) { var properties = Object.keys(propertyMap); return properties.map(function(property){ return { caption: property, snippet: property + ': $0', meta: "property", score: Number.MAX_VALUE }; }); }; this.getPropertyValueCompletions = function(state, session, pos, prefix) { var line = session.getLine(pos.row).substr(0, pos.column); var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; if (!property) return []; var values = []; if (property in propertyMap && typeof propertyMap[property] === "object") { values = Object.keys(propertyMap[property]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "property value", score: Number.MAX_VALUE }; }); }; }).call(CssCompletions.prototype); exports.CssCompletions = CssCompletions; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssCompletions = require("./css_completions").CssCompletions; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.$completer = new CssCompletions(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": {"manifest": 1}, "head": {}, "title": {}, "base": {"href": 1, "target": 1}, "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, "noscript": {"href": 1}, "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, "section": {}, "nav": {}, "article": {"pubdate": 1}, "aside": {}, "h1": {}, "h2": {}, "h3": {}, "h4": {}, "h5": {}, "h6": {}, "header": {}, "footer": {}, "address": {}, "main": {}, "p": {}, "hr": {}, "pre": {}, "blockquote": {"cite": 1}, "ol": {"start": 1, "reversed": 1}, "ul": {}, "li": {"value": 1}, "dl": {}, "dt": {}, "dd": {}, "figure": {}, "figcaption": {}, "div": {}, "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, "em": {}, "strong": {}, "small": {}, "s": {}, "cite": {}, "q": {"cite": 1}, "dfn": {}, "abbr": {}, "data": {}, "time": {"datetime": 1}, "code": {}, "var": {}, "samp": {}, "kbd": {}, "sub": {}, "sup": {}, "i": {}, "b": {}, "u": {}, "mark": {}, "ruby": {}, "rt": {}, "rp": {}, "bdi": {}, "bdo": {}, "span": {}, "br": {}, "wbr": {}, "ins": {"cite": 1, "datetime": 1}, "del": {"cite": 1, "datetime": 1}, "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, "param": {"name": 1, "value": 1}, "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, "source": {"src": 1, "type": 1, "media": 1}, "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, "canvas": {"width": 1, "height": 1}, "map": {"name": 1}, "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, "svg": {}, "math": {}, "table": {"summary": 1}, "caption": {}, "colgroup": {"span": 1}, "col": {"span": 1}, "tbody": {}, "thead": {}, "tfoot": {}, "tr": {}, "td": {"headers": 1, "rowspan": 1, "colspan": 1}, "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, "fieldset": {"disabled": 1, "form": 1, "name": 1}, "legend": {}, "label": {"form": 1, "for": 1}, "input": { "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, "datalist": {}, "optgroup": {"disabled": 1, "label": 1}, "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, "output": {"for": 1, "form": 1, "name": 1}, "progress": {"value": 1, "max": 1}, "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, "details": {"open": 1}, "summary": {}, "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, "menu": {"type": 1, "label": 1}, "dialog": {"open": 1} }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } function findAttributeName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "attribute-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompletions(state, session, pos, prefix); if (is(token, "attribute-value")) return this.getAttributeValueCompletions(state, session, pos, prefix); var line = session.getLine(pos.row).substr(0, pos.column); if (/&[A-z]*$/i.test(line)) return this.getHTMLEntityCompletions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(Object.keys(attributeMap[tagName])); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; this.getAttributeValueCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); var attributeName = findAttributeName(session, pos); if (!tagName) return []; var values = []; if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { values = Object.keys(attributeMap[tagName][attributeName]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "attribute value", score: Number.MAX_VALUE }; }); }; this.getHTMLEntityCompletions = function(state, session, pos, prefix) { var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; return values.map(function(value){ return { caption: value, snippet: value, meta: "html entity", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/php",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/php_highlight_rules","ace/mode/php_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/php_completions","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/unicode","ace/mode/html","ace/mode/javascript","ace/mode/css"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var PhpHighlightRules = require("./php_highlight_rules").PhpHighlightRules; var PhpLangHighlightRules = require("./php_highlight_rules").PhpLangHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var PhpCompletions = require("./php_completions").PhpCompletions; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var unicode = require("../unicode"); var HtmlMode = require("./html").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var PhpMode = function(opts) { this.HighlightRules = PhpLangHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.$completer = new PhpCompletions(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(PhpMode, TextMode); (function() { this.tokenRe = new RegExp("^[" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "_]+", "g" ); this.nonTokenRe = new RegExp("^(?:[^" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "_]|\\s])+", "g" ); this.lineCommentStart = ["//", "#"]; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[:]\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState != "doc-start") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.$id = "ace/mode/php-inline"; }).call(PhpMode.prototype); var Mode = function(opts) { if (opts && opts.inline) { var mode = new PhpMode(); mode.createWorker = this.createWorker; mode.inlinePhp = true; return mode; } HtmlMode.call(this); this.HighlightRules = PhpHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode, "php-": PhpMode }); this.foldingRules.subModes["php-"] = new CStyleFoldMode(); }; oop.inherits(Mode, HtmlMode); (function() { this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/php_worker", "PhpWorker"); worker.attachToDocument(session.getDocument()); if (this.inlinePhp) worker.call("setOptions", [{inline: true}]); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/php"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace/worker-html.js
11,606
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } var cons = obj.constructor; if (cons === RegExp) return obj; copy = cons(); for (var key in obj) { copy[key] = deepCopy(obj[key]); } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); }; } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, [\'\', \'\']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!range instanceof Range) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/html/saxparser",["require","exports","module"], function(require, exports, module) { module.exports = (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({ 1:[function(_dereq_,module,exports){ function isScopeMarker(node) { if (node.namespaceURI === "http://www.w3.org/1999/xhtml") { return node.localName === "applet" || node.localName === "caption" || node.localName === "marquee" || node.localName === "object" || node.localName === "table" || node.localName === "td" || node.localName === "th"; } if (node.namespaceURI === "http://www.w3.org/1998/Math/MathML") { return node.localName === "mi" || node.localName === "mo" || node.localName === "mn" || node.localName === "ms" || node.localName === "mtext" || node.localName === "annotation-xml"; } if (node.namespaceURI === "http://www.w3.org/2000/svg") { return node.localName === "foreignObject" || node.localName === "desc" || node.localName === "title"; } } function isListItemScopeMarker(node) { return isScopeMarker(node) || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'ol') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'ul'); } function isTableScopeMarker(node) { return (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'table') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'html'); } function isTableBodyScopeMarker(node) { return (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'tbody') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'tfoot') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'thead') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'html'); } function isTableRowScopeMarker(node) { return (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'tr') || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'html'); } function isButtonScopeMarker(node) { return isScopeMarker(node) || (node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'button'); } function isSelectScopeMarker(node) { return !(node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'optgroup') && !(node.namespaceURI === "http://www.w3.org/1999/xhtml" && node.localName === 'option'); } function ElementStack() { this.elements = []; this.rootNode = null; this.headElement = null; this.bodyElement = null; } ElementStack.prototype._inScope = function(localName, isMarker) { for (var i = this.elements.length - 1; i >= 0; i--) { var node = this.elements[i]; if (node.localName === localName) return true; if (isMarker(node)) return false; } }; ElementStack.prototype.push = function(item) { this.elements.push(item); }; ElementStack.prototype.pushHtmlElement = function(item) { this.rootNode = item.node; this.push(item); }; ElementStack.prototype.pushHeadElement = function(item) { this.headElement = item.node; this.push(item); }; ElementStack.prototype.pushBodyElement = function(item) { this.bodyElement = item.node; this.push(item); }; ElementStack.prototype.pop = function() { return this.elements.pop(); }; ElementStack.prototype.remove = function(item) { this.elements.splice(this.elements.indexOf(item), 1); }; ElementStack.prototype.popUntilPopped = function(localName) { var element; do { element = this.pop(); } while (element.localName != localName); }; ElementStack.prototype.popUntilTableScopeMarker = function() { while (!isTableScopeMarker(this.top)) this.pop(); }; ElementStack.prototype.popUntilTableBodyScopeMarker = function() { while (!isTableBodyScopeMarker(this.top)) this.pop(); }; ElementStack.prototype.popUntilTableRowScopeMarker = function() { while (!isTableRowScopeMarker(this.top)) this.pop(); }; ElementStack.prototype.item = function(index) { return this.elements[index]; }; ElementStack.prototype.contains = function(element) { return this.elements.indexOf(element) !== -1; }; ElementStack.prototype.inScope = function(localName) { return this._inScope(localName, isScopeMarker); }; ElementStack.prototype.inListItemScope = function(localName) { return this._inScope(localName, isListItemScopeMarker); }; ElementStack.prototype.inTableScope = function(localName) { return this._inScope(localName, isTableScopeMarker); }; ElementStack.prototype.inButtonScope = function(localName) { return this._inScope(localName, isButtonScopeMarker); }; ElementStack.prototype.inSelectScope = function(localName) { return this._inScope(localName, isSelectScopeMarker); }; ElementStack.prototype.hasNumberedHeaderElementInScope = function() { for (var i = this.elements.length - 1; i >= 0; i--) { var node = this.elements[i]; if (node.isNumberedHeader()) return true; if (isScopeMarker(node)) return false; } }; ElementStack.prototype.furthestBlockForFormattingElement = function(element) { var furthestBlock = null; for (var i = this.elements.length - 1; i >= 0; i--) { var node = this.elements[i]; if (node.node === element) break; if (node.isSpecial()) furthestBlock = node; } return furthestBlock; }; ElementStack.prototype.findIndex = function(localName) { for (var i = this.elements.length - 1; i >= 0; i--) { if (this.elements[i].localName == localName) return i; } return -1; }; ElementStack.prototype.remove_openElements_until = function(callback) { var finished = false; var element; while (!finished) { element = this.elements.pop(); finished = callback(element); } return element; }; Object.defineProperty(ElementStack.prototype, 'top', { get: function() { return this.elements[this.elements.length - 1]; } }); Object.defineProperty(ElementStack.prototype, 'length', { get: function() { return this.elements.length; } }); exports.ElementStack = ElementStack; }, {}], 2:[function(_dereq_,module,exports){ var entities = _dereq_('html5-entities'); var InputStream = _dereq_('./InputStream').InputStream; var namedEntityPrefixes = {}; Object.keys(entities).forEach(function (entityKey) { for (var i = 0; i < entityKey.length; i++) { namedEntityPrefixes[entityKey.substring(0, i + 1)] = true; } }); function isAlphaNumeric(c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'); } function isHexDigit(c) { return (c >= '0' && c <= '9') || (c >= 'a' && c <= 'f') || (c >= 'A' && c <= 'F'); } function isDecimalDigit(c) { return (c >= '0' && c <= '9'); } var EntityParser = {}; EntityParser.consumeEntity = function(buffer, tokenizer, additionalAllowedCharacter) { var decodedCharacter = ''; var consumedCharacters = ''; var ch = buffer.char(); if (ch === InputStream.EOF) return false; consumedCharacters += ch; if (ch == '\t' || ch == '\n' || ch == '\v' || ch == ' ' || ch == '<' || ch == '&') { buffer.unget(consumedCharacters); return false; } if (additionalAllowedCharacter === ch) { buffer.unget(consumedCharacters); return false; } if (ch == '#') { ch = buffer.shift(1); if (ch === InputStream.EOF) { tokenizer._parseError("expected-numeric-entity-but-got-eof"); buffer.unget(consumedCharacters); return false; } consumedCharacters += ch; var radix = 10; var isDigit = isDecimalDigit; if (ch == 'x' || ch == 'X') { radix = 16; isDigit = isHexDigit; ch = buffer.shift(1); if (ch === InputStream.EOF) { tokenizer._parseError("expected-numeric-entity-but-got-eof"); buffer.unget(consumedCharacters); return false; } consumedCharacters += ch; } if (isDigit(ch)) { var code = ''; while (ch !== InputStream.EOF && isDigit(ch)) { code += ch; ch = buffer.char(); } code = parseInt(code, radix); var replacement = this.replaceEntityNumbers(code); if (replacement) { tokenizer._parseError("invalid-numeric-entity-replaced"); code = replacement; } if (code > 0xFFFF && code <= 0x10FFFF) { code -= 0x10000; var first = ((0xffc00 & code) >> 10) + 0xD800; var second = (0x3ff & code) + 0xDC00; decodedCharacter = String.fromCharCode(first, second); } else decodedCharacter = String.fromCharCode(code); if (ch !== ';') { tokenizer._parseError("numeric-entity-without-semicolon"); buffer.unget(ch); } return decodedCharacter; } buffer.unget(consumedCharacters); tokenizer._parseError("expected-numeric-entity"); return false; } if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')) { var mostRecentMatch = ''; while (namedEntityPrefixes[consumedCharacters]) { if (entities[consumedCharacters]) { mostRecentMatch = consumedCharacters; } if (ch == ';') break; ch = buffer.char(); if (ch === InputStream.EOF) break; consumedCharacters += ch; } if (!mostRecentMatch) { tokenizer._parseError("expected-named-entity"); buffer.unget(consumedCharacters); return false; } decodedCharacter = entities[mostRecentMatch]; if (ch === ';' || !additionalAllowedCharacter || !(isAlphaNumeric(ch) || ch === '=')) { if (consumedCharacters.length > mostRecentMatch.length) { buffer.unget(consumedCharacters.substring(mostRecentMatch.length)); } if (ch !== ';') { tokenizer._parseError("named-entity-without-semicolon"); } return decodedCharacter; } buffer.unget(consumedCharacters); return false; } }; EntityParser.replaceEntityNumbers = function(c) { switch(c) { case 0x00: return 0xFFFD; // REPLACEMENT CHARACTER case 0x13: return 0x0010; // Carriage return case 0x80: return 0x20AC; // EURO SIGN case 0x81: return 0x0081; // <control> case 0x82: return 0x201A; // SINGLE LOW-9 QUOTATION MARK case 0x83: return 0x0192; // LATIN SMALL LETTER F WITH HOOK case 0x84: return 0x201E; // DOUBLE LOW-9 QUOTATION MARK case 0x85: return 0x2026; // HORIZONTAL ELLIPSIS case 0x86: return 0x2020; // DAGGER case 0x87: return 0x2021; // DOUBLE DAGGER case 0x88: return 0x02C6; // MODIFIER LETTER CIRCUMFLEX ACCENT case 0x89: return 0x2030; // PER MILLE SIGN case 0x8A: return 0x0160; // LATIN CAPITAL LETTER S WITH CARON case 0x8B: return 0x2039; // SINGLE LEFT-POINTING ANGLE QUOTATION MARK case 0x8C: return 0x0152; // LATIN CAPITAL LIGATURE OE case 0x8D: return 0x008D; // <control> case 0x8E: return 0x017D; // LATIN CAPITAL LETTER Z WITH CARON case 0x8F: return 0x008F; // <control> case 0x90: return 0x0090; // <control> case 0x91: return 0x2018; // LEFT SINGLE QUOTATION MARK case 0x92: return 0x2019; // RIGHT SINGLE QUOTATION MARK case 0x93: return 0x201C; // LEFT DOUBLE QUOTATION MARK case 0x94: return 0x201D; // RIGHT DOUBLE QUOTATION MARK case 0x95: return 0x2022; // BULLET case 0x96: return 0x2013; // EN DASH case 0x97: return 0x2014; // EM DASH case 0x98: return 0x02DC; // SMALL TILDE case 0x99: return 0x2122; // TRADE MARK SIGN case 0x9A: return 0x0161; // LATIN SMALL LETTER S WITH CARON case 0x9B: return 0x203A; // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK case 0x9C: return 0x0153; // LATIN SMALL LIGATURE OE case 0x9D: return 0x009D; // <control> case 0x9E: return 0x017E; // LATIN SMALL LETTER Z WITH CARON case 0x9F: return 0x0178; // LATIN CAPITAL LETTER Y WITH DIAERESIS default: if ((c >= 0xD800 && c <= 0xDFFF) || c > 0x10FFFF) { return 0xFFFD; } else if ((c >= 0x0001 && c <= 0x0008) || (c >= 0x000E && c <= 0x001F) || (c >= 0x007F && c <= 0x009F) || (c >= 0xFDD0 && c <= 0xFDEF) || c == 0x000B || c == 0xFFFE || c == 0x1FFFE || c == 0x2FFFFE || c == 0x2FFFF || c == 0x3FFFE || c == 0x3FFFF || c == 0x4FFFE || c == 0x4FFFF || c == 0x5FFFE || c == 0x5FFFF || c == 0x6FFFE || c == 0x6FFFF || c == 0x7FFFE || c == 0x7FFFF || c == 0x8FFFE || c == 0x8FFFF || c == 0x9FFFE || c == 0x9FFFF || c == 0xAFFFE || c == 0xAFFFF || c == 0xBFFFE || c == 0xBFFFF || c == 0xCFFFE || c == 0xCFFFF || c == 0xDFFFE || c == 0xDFFFF || c == 0xEFFFE || c == 0xEFFFF || c == 0xFFFFE || c == 0xFFFFF || c == 0x10FFFE || c == 0x10FFFF) { return c; } } }; exports.EntityParser = EntityParser; }, {"./InputStream":3,"html5-entities":12}], 3:[function(_dereq_,module,exports){ function InputStream() { this.data = ''; this.start = 0; this.committed = 0; this.eof = false; this.lastLocation = {line: 0, column: 0}; } InputStream.EOF = -1; InputStream.DRAIN = -2; InputStream.prototype = { slice: function() { if(this.start >= this.data.length) { if(!this.eof) throw InputStream.DRAIN; return InputStream.EOF; } return this.data.slice(this.start, this.data.length); }, char: function() { if(!this.eof && this.start >= this.data.length - 1) throw InputStream.DRAIN; if(this.start >= this.data.length) { return InputStream.EOF; } var ch = this.data[this.start++]; if (ch === '\r') ch = '\n'; return ch; }, advance: function(amount) { this.start += amount; if(this.start >= this.data.length) { if(!this.eof) throw InputStream.DRAIN; return InputStream.EOF; } else { if(this.committed > this.data.length / 2) { this.lastLocation = this.location(); this.data = this.data.slice(this.committed); this.start = this.start - this.committed; this.committed = 0; } } }, matchWhile: function(re) { if(this.eof && this.start >= this.data.length ) return ''; var r = new RegExp("^"+re+"+"); var m = r.exec(this.slice()); if(m) { if(!this.eof && m[0].length == this.data.length - this.start) throw InputStream.DRAIN; this.advance(m[0].length); return m[0]; } else { return ''; } }, matchUntil: function(re) { var m, s; s = this.slice(); if(s === InputStream.EOF) { return ''; } else if(m = new RegExp(re + (this.eof ? "|$" : "")).exec(s)) { var t = this.data.slice(this.start, this.start + m.index); this.advance(m.index); return t.replace(/\r/g, '\n').replace(/\n{2,}/g, '\n'); } else { throw InputStream.DRAIN; } }, append: function(data) { this.data += data; }, shift: function(n) { if(!this.eof && this.start + n >= this.data.length) throw InputStream.DRAIN; if(this.eof && this.start >= this.data.length) return InputStream.EOF; var d = this.data.slice(this.start, this.start + n).toString(); this.advance(Math.min(n, this.data.length - this.start)); return d; }, peek: function(n) { if(!this.eof && this.start + n >= this.data.length) throw InputStream.DRAIN; if(this.eof && this.start >= this.data.length) return InputStream.EOF; return this.data.slice(this.start, Math.min(this.start + n, this.data.length)).toString(); }, length: function() { return this.data.length - this.start - 1; }, unget: function(d) { if(d === InputStream.EOF) return; this.start -= (d.length); }, undo: function() { this.start = this.committed; }, commit: function() { this.committed = this.start; }, location: function() { var lastLine = this.lastLocation.line; var lastColumn = this.lastLocation.column; var read = this.data.slice(0, this.committed); var newlines = read.match(/\n/g); var line = newlines ? lastLine + newlines.length : lastLine; var column = newlines ? read.length - read.lastIndexOf('\n') - 1 : lastColumn + read.length; return {line: line, column: column}; } }; exports.InputStream = InputStream; }, {}], 4:[function(_dereq_,module,exports){ var SpecialElements = { "http://www.w3.org/1999/xhtml": [ 'address', 'applet', 'area', 'article', 'aside', 'base', 'basefont', 'bgsound', 'blockquote', 'body', 'br', 'button', 'caption', 'center', 'col', 'colgroup', 'dd', 'details', 'dir', 'div', 'dl', 'dt', 'embed', 'fieldset', 'figcaption', 'figure', 'footer', 'form', 'frame', 'frameset', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'iframe', 'img', 'input', 'isindex', 'li', 'link', 'listing', 'main', 'marquee', 'menu', 'menuitem', 'meta', 'nav', 'noembed', 'noframes', 'noscript', 'object', 'ol', 'p', 'param', 'plaintext', 'pre', 'script', 'section', 'select', 'source', 'style', 'summary', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th', 'thead', 'title', 'tr', 'track', 'ul', 'wbr', 'xmp' ], "http://www.w3.org/1998/Math/MathML": [ 'mi', 'mo', 'mn', 'ms', 'mtext', 'annotation-xml' ], "http://www.w3.org/2000/svg": [ 'foreignObject', 'desc', 'title' ] }; function StackItem(namespaceURI, localName, attributes, node) { this.localName = localName; this.namespaceURI = namespaceURI; this.attributes = attributes; this.node = node; } StackItem.prototype.isSpecial = function() { return this.namespaceURI in SpecialElements && SpecialElements[this.namespaceURI].indexOf(this.localName) > -1; }; StackItem.prototype.isFosterParenting = function() { if (this.namespaceURI === "http://www.w3.org/1999/xhtml") { return this.localName === 'table' || this.localName === 'tbody' || this.localName === 'tfoot' || this.localName === 'thead' || this.localName === 'tr'; } return false; }; StackItem.prototype.isNumberedHeader = function() { if (this.namespaceURI === "http://www.w3.org/1999/xhtml") { return this.localName === 'h1' || this.localName === 'h2' || this.localName === 'h3' || this.localName === 'h4' || this.localName === 'h5' || this.localName === 'h6'; } return false; }; StackItem.prototype.isForeign = function() { return this.namespaceURI != "http://www.w3.org/1999/xhtml"; }; function getAttribute(item, name) { for (var i = 0; i < item.attributes.length; i++) { if (item.attributes[i].nodeName == name) return item.attributes[i].nodeValue; } return null; } StackItem.prototype.isHtmlIntegrationPoint = function() { if (this.namespaceURI === "http://www.w3.org/1998/Math/MathML") { if (this.localName !== "annotation-xml") return false; var encoding = getAttribute(this, 'encoding'); if (!encoding) return false; encoding = encoding.toLowerCase(); return encoding === "text/html" || encoding === "application/xhtml+xml"; } if (this.namespaceURI === "http://www.w3.org/2000/svg") { return this.localName === "foreignObject" || this.localName === "desc" || this.localName === "title"; } return false; }; StackItem.prototype.isMathMLTextIntegrationPoint = function() { if (this.namespaceURI === "http://www.w3.org/1998/Math/MathML") { return this.localName === "mi" || this.localName === "mo" || this.localName === "mn" || this.localName === "ms" || this.localName === "mtext"; } return false; }; exports.StackItem = StackItem; }, {}], 5:[function(_dereq_,module,exports){ var InputStream = _dereq_('./InputStream').InputStream; var EntityParser = _dereq_('./EntityParser').EntityParser; function isWhitespace(c){ return c === " " || c === "\n" || c === "\t" || c === "\r" || c === "\f"; } function isAlpha(c) { return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'); } function Tokenizer(tokenHandler) { this._tokenHandler = tokenHandler; this._state = Tokenizer.DATA; this._inputStream = new InputStream(); this._currentToken = null; this._temporaryBuffer = ''; this._additionalAllowedCharacter = ''; } Tokenizer.prototype._parseError = function(code, args) { this._tokenHandler.parseError(code, args); }; Tokenizer.prototype._emitToken = function(token) { if (token.type === 'StartTag') { for (var i = 1; i < token.data.length; i++) { if (!token.data[i].nodeName) token.data.splice(i--, 1); } } else if (token.type === 'EndTag') { if (token.selfClosing) { this._parseError('self-closing-flag-on-end-tag'); } if (token.data.length !== 0) { this._parseError('attributes-in-end-tag'); } } this._tokenHandler.processToken(token); if (token.type === 'StartTag' && token.selfClosing && !this._tokenHandler.isSelfClosingFlagAcknowledged()) { this._parseError('non-void-element-with-trailing-solidus', {name: token.name}); } }; Tokenizer.prototype._emitCurrentToken = function() { this._state = Tokenizer.DATA; this._emitToken(this._currentToken); }; Tokenizer.prototype._currentAttribute = function() { return this._currentToken.data[this._currentToken.data.length - 1]; }; Tokenizer.prototype.setState = function(state) { this._state = state; }; Tokenizer.prototype.tokenize = function(source) { Tokenizer.DATA = data_state; Tokenizer.RCDATA = rcdata_state; Tokenizer.RAWTEXT = rawtext_state; Tokenizer.SCRIPT_DATA = script_data_state; Tokenizer.PLAINTEXT = plaintext_state; this._state = Tokenizer.DATA; this._inputStream.append(source); this._tokenHandler.startTokenization(this); this._inputStream.eof = true; var tokenizer = this; while (this._state.call(this, this._inputStream)); function data_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === '&') { tokenizer.setState(character_reference_in_data_state); } else if (data === '<') { tokenizer.setState(tag_open_state); } else if (data === '\u0000') { tokenizer._emitToken({type: 'Characters', data: data}); buffer.commit(); } else { var chars = buffer.matchUntil("&|<|\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); buffer.commit(); } return true; } function character_reference_in_data_state(buffer) { var character = EntityParser.consumeEntity(buffer, tokenizer); tokenizer.setState(data_state); tokenizer._emitToken({type: 'Characters', data: character || '&'}); return true; } function rcdata_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === '&') { tokenizer.setState(character_reference_in_rcdata_state); } else if (data === '<') { tokenizer.setState(rcdata_less_than_sign_state); } else if (data === "\u0000") { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil("&|<|\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); buffer.commit(); } return true; } function character_reference_in_rcdata_state(buffer) { var character = EntityParser.consumeEntity(buffer, tokenizer); tokenizer.setState(rcdata_state); tokenizer._emitToken({type: 'Characters', data: character || '&'}); return true; } function rawtext_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === '<') { tokenizer.setState(rawtext_less_than_sign_state); } else if (data === "\u0000") { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil("<|\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); } return true; } function plaintext_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === "\u0000") { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil("\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); } return true; } function script_data_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._emitToken({type: 'EOF', data: null}); return false; } else if (data === '<') { tokenizer.setState(script_data_less_than_sign_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil("<|\u0000"); tokenizer._emitToken({type: 'Characters', data: data + chars}); } return true; } function rcdata_less_than_sign_state(buffer) { var data = buffer.char(); if (data === "/") { this._temporaryBuffer = ''; tokenizer.setState(rcdata_end_tag_open_state); } else { tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(rcdata_state); } return true; } function rcdata_end_tag_open_state(buffer) { var data = buffer.char(); if (isAlpha(data)) { this._temporaryBuffer += data; tokenizer.setState(rcdata_end_tag_name_state); } else { tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(rcdata_state); } return true; } function rcdata_end_tag_name_state(buffer) { var appropriate = tokenizer._currentToken && (tokenizer._currentToken.name === this._temporaryBuffer.toLowerCase()); var data = buffer.char(); if (isWhitespace(data) && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer.setState(before_attribute_name_state); } else if (data === '/' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer.setState(self_closing_tag_state); } else if (data === '>' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else if (isAlpha(data)) { this._temporaryBuffer += data; buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: '</' + this._temporaryBuffer}); buffer.unget(data); tokenizer.setState(rcdata_state); } return true; } function rawtext_less_than_sign_state(buffer) { var data = buffer.char(); if (data === "/") { this._temporaryBuffer = ''; tokenizer.setState(rawtext_end_tag_open_state); } else { tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(rawtext_state); } return true; } function rawtext_end_tag_open_state(buffer) { var data = buffer.char(); if (isAlpha(data)) { this._temporaryBuffer += data; tokenizer.setState(rawtext_end_tag_name_state); } else { tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(rawtext_state); } return true; } function rawtext_end_tag_name_state(buffer) { var appropriate = tokenizer._currentToken && (tokenizer._currentToken.name === this._temporaryBuffer.toLowerCase()); var data = buffer.char(); if (isWhitespace(data) && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer.setState(before_attribute_name_state); } else if (data === '/' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer.setState(self_closing_tag_state); } else if (data === '>' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: this._temporaryBuffer, data: [], selfClosing: false}; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else if (isAlpha(data)) { this._temporaryBuffer += data; buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: '</' + this._temporaryBuffer}); buffer.unget(data); tokenizer.setState(rawtext_state); } return true; } function script_data_less_than_sign_state(buffer) { var data = buffer.char(); if (data === "/") { this._temporaryBuffer = ''; tokenizer.setState(script_data_end_tag_open_state); } else if (data === '!') { tokenizer._emitToken({type: 'Characters', data: '<!'}); tokenizer.setState(script_data_escape_start_state); } else { tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_end_tag_open_state(buffer) { var data = buffer.char(); if (isAlpha(data)) { this._temporaryBuffer += data; tokenizer.setState(script_data_end_tag_name_state); } else { tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_end_tag_name_state(buffer) { var appropriate = tokenizer._currentToken && (tokenizer._currentToken.name === this._temporaryBuffer.toLowerCase()); var data = buffer.char(); if (isWhitespace(data) && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(before_attribute_name_state); } else if (data === '/' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(self_closing_tag_state); } else if (data === '>' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer._emitCurrentToken(); } else if (isAlpha(data)) { this._temporaryBuffer += data; buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: '</' + this._temporaryBuffer}); buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_escape_start_state(buffer) { var data = buffer.char(); if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_escape_start_dash_state); } else { buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_escape_start_dash_state(buffer) { var data = buffer.char(); if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_escaped_dash_dash_state); } else { buffer.unget(data); tokenizer.setState(script_data_state); } return true; } function script_data_escaped_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_escaped_dash_state); } else if (data === '<') { tokenizer.setState(script_data_escaped_less_then_sign_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { var chars = buffer.matchUntil('<|-|\u0000'); tokenizer._emitToken({type: 'Characters', data: data + chars}); } return true; } function script_data_escaped_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_escaped_dash_dash_state); } else if (data === '<') { tokenizer.setState(script_data_escaped_less_then_sign_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); tokenizer.setState(script_data_escaped_state); } else { tokenizer._emitToken({type: 'Characters', data: data}); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_escaped_dash_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-script'); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '<') { tokenizer.setState(script_data_escaped_less_then_sign_state); } else if (data === '>') { tokenizer._emitToken({type: 'Characters', data: '>'}); tokenizer.setState(script_data_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); tokenizer.setState(script_data_escaped_state); } else { tokenizer._emitToken({type: 'Characters', data: data}); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_escaped_less_then_sign_state(buffer) { var data = buffer.char(); if (data === '/') { this._temporaryBuffer = ''; tokenizer.setState(script_data_escaped_end_tag_open_state); } else if (isAlpha(data)) { tokenizer._emitToken({type: 'Characters', data: '<' + data}); this._temporaryBuffer = data; tokenizer.setState(script_data_double_escape_start_state); } else { tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_escaped_end_tag_open_state(buffer) { var data = buffer.char(); if (isAlpha(data)) { this._temporaryBuffer = data; tokenizer.setState(script_data_escaped_end_tag_name_state); } else { tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_escaped_end_tag_name_state(buffer) { var appropriate = tokenizer._currentToken && (tokenizer._currentToken.name === this._temporaryBuffer.toLowerCase()); var data = buffer.char(); if (isWhitespace(data) && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(before_attribute_name_state); } else if (data === '/' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(self_closing_tag_state); } else if (data === '>' && appropriate) { tokenizer._currentToken = {type: 'EndTag', name: 'script', data: [], selfClosing: false}; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isAlpha(data)) { this._temporaryBuffer += data; buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: '</' + this._temporaryBuffer}); buffer.unget(data); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_double_escape_start_state(buffer) { var data = buffer.char(); if (isWhitespace(data) || data === '/' || data === '>') { tokenizer._emitToken({type: 'Characters', data: data}); if (this._temporaryBuffer.toLowerCase() === 'script') tokenizer.setState(script_data_double_escaped_state); else tokenizer.setState(script_data_escaped_state); } else if (isAlpha(data)) { tokenizer._emitToken({type: 'Characters', data: data}); this._temporaryBuffer += data; buffer.commit(); } else { buffer.unget(data); tokenizer.setState(script_data_escaped_state); } return true; } function script_data_double_escaped_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-script'); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_double_escaped_dash_state); } else if (data === '<') { tokenizer._emitToken({type: 'Characters', data: '<'}); tokenizer.setState(script_data_double_escaped_less_than_sign_state); } else if (data === '\u0000') { tokenizer._parseError('invalid-codepoint'); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); buffer.commit(); } else { tokenizer._emitToken({type: 'Characters', data: data}); buffer.commit(); } return true; } function script_data_double_escaped_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-script'); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); tokenizer.setState(script_data_double_escaped_dash_dash_state); } else if (data === '<') { tokenizer._emitToken({type: 'Characters', data: '<'}); tokenizer.setState(script_data_double_escaped_less_than_sign_state); } else if (data === '\u0000') { tokenizer._parseError('invalid-codepoint'); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); tokenizer.setState(script_data_double_escaped_state); } else { tokenizer._emitToken({type: 'Characters', data: data}); tokenizer.setState(script_data_double_escaped_state); } return true; } function script_data_double_escaped_dash_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-script'); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._emitToken({type: 'Characters', data: '-'}); buffer.commit(); } else if (data === '<') { tokenizer._emitToken({type: 'Characters', data: '<'}); tokenizer.setState(script_data_double_escaped_less_than_sign_state); } else if (data === '>') { tokenizer._emitToken({type: 'Characters', data: '>'}); tokenizer.setState(script_data_state); } else if (data === '\u0000') { tokenizer._parseError('invalid-codepoint'); tokenizer._emitToken({type: 'Characters', data: '\uFFFD'}); tokenizer.setState(script_data_double_escaped_state); } else { tokenizer._emitToken({type: 'Characters', data: data}); tokenizer.setState(script_data_double_escaped_state); } return true; } function script_data_double_escaped_less_than_sign_state(buffer) { var data = buffer.char(); if (data === '/') { tokenizer._emitToken({type: 'Characters', data: '/'}); this._temporaryBuffer = ''; tokenizer.setState(script_data_double_escape_end_state); } else { buffer.unget(data); tokenizer.setState(script_data_double_escaped_state); } return true; } function script_data_double_escape_end_state(buffer) { var data = buffer.char(); if (isWhitespace(data) || data === '/' || data === '>') { tokenizer._emitToken({type: 'Characters', data: data}); if (this._temporaryBuffer.toLowerCase() === 'script') tokenizer.setState(script_data_escaped_state); else tokenizer.setState(script_data_double_escaped_state); } else if (isAlpha(data)) { tokenizer._emitToken({type: 'Characters', data: data}); this._temporaryBuffer += data; buffer.commit(); } else { buffer.unget(data); tokenizer.setState(script_data_double_escaped_state); } return true; } function tag_open_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("bare-less-than-sign-at-eof"); tokenizer._emitToken({type: 'Characters', data: '<'}); buffer.unget(data); tokenizer.setState(data_state); } else if (isAlpha(data)) { tokenizer._currentToken = {type: 'StartTag', name: data.toLowerCase(), data: []}; tokenizer.setState(tag_name_state); } else if (data === '!') { tokenizer.setState(markup_declaration_open_state); } else if (data === '/') { tokenizer.setState(close_tag_open_state); } else if (data === '>') { tokenizer._parseError("expected-tag-name-but-got-right-bracket"); tokenizer._emitToken({type: 'Characters', data: "<>"}); tokenizer.setState(data_state); } else if (data === '?') { tokenizer._parseError("expected-tag-name-but-got-question-mark"); buffer.unget(data); tokenizer.setState(bogus_comment_state); } else { tokenizer._parseError("expected-tag-name"); tokenizer._emitToken({type: 'Characters', data: "<"}); buffer.unget(data); tokenizer.setState(data_state); } return true; } function close_tag_open_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-closing-tag-but-got-eof"); tokenizer._emitToken({type: 'Characters', data: '</'}); buffer.unget(data); tokenizer.setState(data_state); } else if (isAlpha(data)) { tokenizer._currentToken = {type: 'EndTag', name: data.toLowerCase(), data: []}; tokenizer.setState(tag_name_state); } else if (data === '>') { tokenizer._parseError("expected-closing-tag-but-got-right-bracket"); tokenizer.setState(data_state); } else { tokenizer._parseError("expected-closing-tag-but-got-char", {data: data}); // param 1 is datavars: buffer.unget(data); tokenizer.setState(bogus_comment_state); } return true; } function tag_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError('eof-in-tag-name'); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(before_attribute_name_state); } else if (isAlpha(data)) { tokenizer._currentToken.name += data.toLowerCase(); } else if (data === '>') { tokenizer._emitCurrentToken(); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.name += "\uFFFD"; } else { tokenizer._currentToken.name += data; } buffer.commit(); return true; } function before_attribute_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-attribute-name-but-got-eof"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { return true; } else if (isAlpha(data)) { tokenizer._currentToken.data.push({nodeName: data.toLowerCase(), nodeValue: ""}); tokenizer.setState(attribute_name_state); } else if (data === '>') { tokenizer._emitCurrentToken(); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else if (data === "'" || data === '"' || data === '=' || data === '<') { tokenizer._parseError("invalid-character-in-attribute-name"); tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data.push({nodeName: "\uFFFD", nodeValue: ""}); } else { tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } return true; } function attribute_name_state(buffer) { var data = buffer.char(); var leavingThisState = true; var shouldEmit = false; if (data === InputStream.EOF) { tokenizer._parseError("eof-in-attribute-name"); buffer.unget(data); tokenizer.setState(data_state); shouldEmit = true; } else if (data === '=') { tokenizer.setState(before_attribute_value_state); } else if (isAlpha(data)) { tokenizer._currentAttribute().nodeName += data.toLowerCase(); leavingThisState = false; } else if (data === '>') { shouldEmit = true; } else if (isWhitespace(data)) { tokenizer.setState(after_attribute_name_state); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else if (data === "'" || data === '"') { tokenizer._parseError("invalid-character-in-attribute-name"); tokenizer._currentAttribute().nodeName += data; leavingThisState = false; } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeName += "\uFFFD"; } else { tokenizer._currentAttribute().nodeName += data; leavingThisState = false; } if (leavingThisState) { var attributes = tokenizer._currentToken.data; var currentAttribute = attributes[attributes.length - 1]; for (var i = attributes.length - 2; i >= 0; i--) { if (currentAttribute.nodeName === attributes[i].nodeName) { tokenizer._parseError("duplicate-attribute", {name: currentAttribute.nodeName}); currentAttribute.nodeName = null; break; } } if (shouldEmit) tokenizer._emitCurrentToken(); } else { buffer.commit(); } return true; } function after_attribute_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-end-of-tag-but-got-eof"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { return true; } else if (data === '=') { tokenizer.setState(before_attribute_value_state); } else if (data === '>') { tokenizer._emitCurrentToken(); } else if (isAlpha(data)) { tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else if (data === "'" || data === '"' || data === '<') { tokenizer._parseError("invalid-character-after-attribute-name"); tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data.push({nodeName: "\uFFFD", nodeValue: ""}); } else { tokenizer._currentToken.data.push({nodeName: data, nodeValue: ""}); tokenizer.setState(attribute_name_state); } return true; } function before_attribute_value_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-attribute-value-but-got-eof"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { return true; } else if (data === '"') { tokenizer.setState(attribute_value_double_quoted_state); } else if (data === '&') { tokenizer.setState(attribute_value_unquoted_state); buffer.unget(data); } else if (data === "'") { tokenizer.setState(attribute_value_single_quoted_state); } else if (data === '>') { tokenizer._parseError("expected-attribute-value-but-got-right-bracket"); tokenizer._emitCurrentToken(); } else if (data === '=' || data === '<' || data === '`') { tokenizer._parseError("unexpected-character-in-unquoted-attribute-value"); tokenizer._currentAttribute().nodeValue += data; tokenizer.setState(attribute_value_unquoted_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeValue += "\uFFFD"; } else { tokenizer._currentAttribute().nodeValue += data; tokenizer.setState(attribute_value_unquoted_state); } return true; } function attribute_value_double_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-attribute-value-double-quote"); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '"') { tokenizer.setState(after_attribute_value_state); } else if (data === '&') { this._additionalAllowedCharacter = '"'; tokenizer.setState(character_reference_in_attribute_value_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeValue += "\uFFFD"; } else { var s = buffer.matchUntil('[\0"&]'); data = data + s; tokenizer._currentAttribute().nodeValue += data; } return true; } function attribute_value_single_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-attribute-value-single-quote"); buffer.unget(data); tokenizer.setState(data_state); } else if (data === "'") { tokenizer.setState(after_attribute_value_state); } else if (data === '&') { this._additionalAllowedCharacter = "'"; tokenizer.setState(character_reference_in_attribute_value_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeValue += "\uFFFD"; } else { tokenizer._currentAttribute().nodeValue += data + buffer.matchUntil("\u0000|['&]"); } return true; } function attribute_value_unquoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-after-attribute-value"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(before_attribute_name_state); } else if (data === '&') { this._additionalAllowedCharacter = ">"; tokenizer.setState(character_reference_in_attribute_value_state); } else if (data === '>') { tokenizer._emitCurrentToken(); } else if (data === '"' || data === "'" || data === '=' || data === '`' || data === '<') { tokenizer._parseError("unexpected-character-in-unquoted-attribute-value"); tokenizer._currentAttribute().nodeValue += data; buffer.commit(); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentAttribute().nodeValue += "\uFFFD"; } else { var o = buffer.matchUntil("\u0000|["+ "\t\n\v\f\x20\r" + "&<>\"'=`" +"]"); if (o === InputStream.EOF) { tokenizer._parseError("eof-in-attribute-value-no-quotes"); tokenizer._emitCurrentToken(); } buffer.commit(); tokenizer._currentAttribute().nodeValue += data + o; } return true; } function character_reference_in_attribute_value_state(buffer) { var character = EntityParser.consumeEntity(buffer, tokenizer, this._additionalAllowedCharacter); this._currentAttribute().nodeValue += character || '&'; if (this._additionalAllowedCharacter === '"') tokenizer.setState(attribute_value_double_quoted_state); else if (this._additionalAllowedCharacter === '\'') tokenizer.setState(attribute_value_single_quoted_state); else if (this._additionalAllowedCharacter === '>') tokenizer.setState(attribute_value_unquoted_state); return true; } function after_attribute_value_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-after-attribute-value"); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(before_attribute_name_state); } else if (data === '>') { tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (data === '/') { tokenizer.setState(self_closing_tag_state); } else { tokenizer._parseError("unexpected-character-after-attribute-value"); buffer.unget(data); tokenizer.setState(before_attribute_name_state); } return true; } function self_closing_tag_state(buffer) { var c = buffer.char(); if (c === InputStream.EOF) { tokenizer._parseError("unexpected-eof-after-solidus-in-tag"); buffer.unget(c); tokenizer.setState(data_state); } else if (c === '>') { tokenizer._currentToken.selfClosing = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._parseError("unexpected-character-after-solidus-in-tag"); buffer.unget(c); tokenizer.setState(before_attribute_name_state); } return true; } function bogus_comment_state(buffer) { var data = buffer.matchUntil('>'); data = data.replace(/\u0000/g, "\uFFFD"); buffer.char(); tokenizer._emitToken({type: 'Comment', data: data}); tokenizer.setState(data_state); return true; } function markup_declaration_open_state(buffer) { var chars = buffer.shift(2); if (chars === '--') { tokenizer._currentToken = {type: 'Comment', data: ''}; tokenizer.setState(comment_start_state); } else { var newchars = buffer.shift(5); if (newchars === InputStream.EOF || chars === InputStream.EOF) { tokenizer._parseError("expected-dashes-or-doctype"); tokenizer.setState(bogus_comment_state); buffer.unget(chars); return true; } chars += newchars; if (chars.toUpperCase() === 'DOCTYPE') { tokenizer._currentToken = {type: 'Doctype', name: '', publicId: null, systemId: null, forceQuirks: false}; tokenizer.setState(doctype_state); } else if (tokenizer._tokenHandler.isCdataSectionAllowed() && chars === '[CDATA[') { tokenizer.setState(cdata_section_state); } else { tokenizer._parseError("expected-dashes-or-doctype"); buffer.unget(chars); tokenizer.setState(bogus_comment_state); } } return true; } function cdata_section_state(buffer) { var data = buffer.matchUntil(']]>'); buffer.shift(3); if (data) { tokenizer._emitToken({type: 'Characters', data: data}); } tokenizer.setState(data_state); return true; } function comment_start_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer.setState(comment_start_dash_state); } else if (data === '>') { tokenizer._parseError("incorrect-comment"); tokenizer._emitToken(tokenizer._currentToken); tokenizer.setState(data_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "\uFFFD"; } else { tokenizer._currentToken.data += data; tokenizer.setState(comment_state); } return true; } function comment_start_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer.setState(comment_end_state); } else if (data === '>') { tokenizer._parseError("incorrect-comment"); tokenizer._emitToken(tokenizer._currentToken); tokenizer.setState(data_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "\uFFFD"; } else { tokenizer._currentToken.data += '-' + data; tokenizer.setState(comment_state); } return true; } function comment_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer.setState(comment_end_dash_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "\uFFFD"; } else { tokenizer._currentToken.data += data; buffer.commit(); } return true; } function comment_end_dash_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment-end-dash"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '-') { tokenizer.setState(comment_end_state); } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "-\uFFFD"; tokenizer.setState(comment_state); } else { tokenizer._currentToken.data += '-' + data + buffer.matchUntil('\u0000|-'); buffer.char(); } return true; } function comment_end_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment-double-dash"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '>') { tokenizer._emitToken(tokenizer._currentToken); tokenizer.setState(data_state); } else if (data === '!') { tokenizer._parseError("unexpected-bang-after-double-dash-in-comment"); tokenizer.setState(comment_end_bang_state); } else if (data === '-') { tokenizer._parseError("unexpected-dash-after-double-dash-in-comment"); tokenizer._currentToken.data += data; } else if (data === '\u0000') { tokenizer._parseError("invalid-codepoint"); tokenizer._currentToken.data += "--\uFFFD"; tokenizer.setState(comment_state); } else { tokenizer._parseError("unexpected-char-in-comment"); tokenizer._currentToken.data += '--' + data; tokenizer.setState(comment_state); } return true; } function comment_end_bang_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-comment-end-bang-state"); tokenizer._emitToken(tokenizer._currentToken); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '>') { tokenizer._emitToken(tokenizer._currentToken); tokenizer.setState(data_state); } else if (data === '-') { tokenizer._currentToken.data += '--!'; tokenizer.setState(comment_end_dash_state); } else { tokenizer._currentToken.data += '--!' + data; tokenizer.setState(comment_state); } return true; } function doctype_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-doctype-name-but-got-eof"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { tokenizer.setState(before_doctype_name_state); } else { tokenizer._parseError("need-space-after-doctype"); buffer.unget(data); tokenizer.setState(before_doctype_name_state); } return true; } function before_doctype_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("expected-doctype-name-but-got-eof"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { } else if (data === '>') { tokenizer._parseError("expected-doctype-name-but-got-right-bracket"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { if (isAlpha(data)) data = data.toLowerCase(); tokenizer._currentToken.name = data; tokenizer.setState(doctype_name_state); } return true; } function doctype_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer._parseError("eof-in-doctype-name"); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { tokenizer.setState(after_doctype_name_state); } else if (data === '>') { tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { if (isAlpha(data)) data = data.toLowerCase(); tokenizer._currentToken.name += data; buffer.commit(); } return true; } function after_doctype_name_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer._parseError("eof-in-doctype"); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { } else if (data === '>') { tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { if (['p', 'P'].indexOf(data) > -1) { var expected = [['u', 'U'], ['b', 'B'], ['l', 'L'], ['i', 'I'], ['c', 'C']]; var matched = expected.every(function(expected){ data = buffer.char(); return expected.indexOf(data) > -1; }); if (matched) { tokenizer.setState(after_doctype_public_keyword_state); return true; } } else if (['s', 'S'].indexOf(data) > -1) { var expected = [['y', 'Y'], ['s', 'S'], ['t', 'T'], ['e', 'E'], ['m', 'M']]; var matched = expected.every(function(expected){ data = buffer.char(); return expected.indexOf(data) > -1; }); if (matched) { tokenizer.setState(after_doctype_system_keyword_state); return true; } } buffer.unget(data); tokenizer._currentToken.forceQuirks = true; if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._parseError("expected-space-or-right-bracket-in-doctype", {data: data}); tokenizer.setState(bogus_doctype_state); } } return true; } function after_doctype_public_keyword_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { tokenizer.setState(before_doctype_public_identifier_state); } else if (data === "'" || data === '"') { tokenizer._parseError("unexpected-char-in-doctype"); buffer.unget(data); tokenizer.setState(before_doctype_public_identifier_state); } else { buffer.unget(data); tokenizer.setState(before_doctype_public_identifier_state); } return true; } function before_doctype_public_identifier_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (isWhitespace(data)) { } else if (data === '"') { tokenizer._currentToken.publicId = ''; tokenizer.setState(doctype_public_identifier_double_quoted_state); } else if (data === "'") { tokenizer._currentToken.publicId = ''; tokenizer.setState(doctype_public_identifier_single_quoted_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(bogus_doctype_state); } return true; } function doctype_public_identifier_double_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (data === '"') { tokenizer.setState(after_doctype_public_identifier_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._currentToken.publicId += data; } return true; } function doctype_public_identifier_single_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; buffer.unget(data); tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (data === "'") { tokenizer.setState(after_doctype_public_identifier_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else { tokenizer._currentToken.publicId += data; } return true; } function after_doctype_public_identifier_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(between_doctype_public_and_system_identifiers_state); } else if (data === '>') { tokenizer.setState(data_state); tokenizer._emitCurrentToken(); } else if (data === '"') { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_double_quoted_state); } else if (data === "'") { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_single_quoted_state); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(bogus_doctype_state); } return true; } function between_doctype_public_and_system_identifiers_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { } else if (data === '>') { tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else if (data === '"') { tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_double_quoted_state); } else if (data === "'") { tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_single_quoted_state); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(bogus_doctype_state); } return true; } function after_doctype_system_keyword_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { tokenizer.setState(before_doctype_system_identifier_state); } else if (data === "'" || data === '"') { tokenizer._parseError("unexpected-char-in-doctype"); buffer.unget(data); tokenizer.setState(before_doctype_system_identifier_state); } else { buffer.unget(data); tokenizer.setState(before_doctype_system_identifier_state); } return true; } function before_doctype_system_identifier_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { } else if (data === '"') { tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_double_quoted_state); } else if (data === "'") { tokenizer._currentToken.systemId = ''; tokenizer.setState(doctype_system_identifier_single_quoted_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer.setState(bogus_doctype_state); } return true; } function doctype_system_identifier_double_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (data === '"') { tokenizer.setState(after_doctype_system_identifier_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else { tokenizer._currentToken.systemId += data; } return true; } function doctype_system_identifier_single_quoted_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (data === "'") { tokenizer.setState(after_doctype_system_identifier_state); } else if (data === '>') { tokenizer._parseError("unexpected-end-of-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else { tokenizer._currentToken.systemId += data; } return true; } function after_doctype_system_identifier_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { tokenizer._parseError("eof-in-doctype"); tokenizer._currentToken.forceQuirks = true; tokenizer._emitCurrentToken(); buffer.unget(data); tokenizer.setState(data_state); } else if (isWhitespace(data)) { } else if (data === '>') { tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else { tokenizer._parseError("unexpected-char-in-doctype"); tokenizer.setState(bogus_doctype_state); } return true; } function bogus_doctype_state(buffer) { var data = buffer.char(); if (data === InputStream.EOF) { buffer.unget(data); tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } else if (data === '>') { tokenizer._emitCurrentToken(); tokenizer.setState(data_state); } return true; } }; Object.defineProperty(Tokenizer.prototype, 'lineNumber', { get: function() { return this._inputStream.location().line; } }); Object.defineProperty(Tokenizer.prototype, 'columnNumber', { get: function() { return this._inputStream.location().column; } }); exports.Tokenizer = Tokenizer; }, {"./EntityParser":2,"./InputStream":3}], 6:[function(_dereq_,module,exports){ var assert = _dereq_('assert'); var messages = _dereq_('./messages.json'); var constants = _dereq_('./constants'); var EventEmitter = _dereq_('events').EventEmitter; var Tokenizer = _dereq_('./Tokenizer').Tokenizer; var ElementStack = _dereq_('./ElementStack').ElementStack; var StackItem = _dereq_('./StackItem').StackItem; var Marker = {}; function isWhitespace(ch) { return ch === " " || ch === "\n" || ch === "\t" || ch === "\r" || ch === "\f"; } function isWhitespaceOrReplacementCharacter(ch) { return isWhitespace(ch) || ch === '\uFFFD'; } function isAllWhitespace(characters) { for (var i = 0; i < characters.length; i++) { var ch = characters[i]; if (!isWhitespace(ch)) return false; } return true; } function isAllWhitespaceOrReplacementCharacters(characters) { for (var i = 0; i < characters.length; i++) { var ch = characters[i]; if (!isWhitespaceOrReplacementCharacter(ch)) return false; } return true; } function getAttribute(node, name) { for (var i = 0; i < node.attributes.length; i++) { var attribute = node.attributes[i]; if (attribute.nodeName === name) { return attribute; } } return null; } function CharacterBuffer(characters) { this.characters = characters; this.current = 0; this.end = this.characters.length; } CharacterBuffer.prototype.skipAtMostOneLeadingNewline = function() { if (this.characters[this.current] === '\n') this.current++; }; CharacterBuffer.prototype.skipLeadingWhitespace = function() { while (isWhitespace(this.characters[this.current])) { if (++this.current == this.end) return; } }; CharacterBuffer.prototype.skipLeadingNonWhitespace = function() { while (!isWhitespace(this.characters[this.current])) { if (++this.current == this.end) return; } }; CharacterBuffer.prototype.takeRemaining = function() { return this.characters.substring(this.current); }; CharacterBuffer.prototype.takeLeadingWhitespace = function() { var start = this.current; this.skipLeadingWhitespace(); if (start === this.current) return ""; return this.characters.substring(start, this.current - start); }; Object.defineProperty(CharacterBuffer.prototype, 'length', { get: function(){ return this.end - this.current; } }); function TreeBuilder() { this.tokenizer = null; this.errorHandler = null; this.scriptingEnabled = false; this.document = null; this.head = null; this.form = null; this.openElements = new ElementStack(); this.activeFormattingElements = []; this.insertionMode = null; this.insertionModeName = ""; this.originalInsertionMode = ""; this.inQuirksMode = false; // TODO quirks mode this.compatMode = "no quirks"; this.framesetOk = true; this.redirectAttachToFosterParent = false; this.selfClosingFlagAcknowledged = false; this.context = ""; this.pendingTableCharacters = []; this.shouldSkipLeadingNewline = false; var tree = this; var modes = this.insertionModes = {}; modes.base = { end_tag_handlers: {"-default": 'endTagOther'}, start_tag_handlers: {"-default": 'startTagOther'}, processEOF: function() { tree.generateImpliedEndTags(); if (tree.openElements.length > 2) { tree.parseError('expected-closing-tag-but-got-eof'); } else if (tree.openElements.length == 2 && tree.openElements.item(1).localName != 'body') { tree.parseError('expected-closing-tag-but-got-eof'); } else if (tree.context && tree.openElements.length > 1) { } }, processComment: function(data) { tree.insertComment(data, tree.currentStackItem().node); }, processDoctype: function(name, publicId, systemId, forceQuirks) { tree.parseError('unexpected-doctype'); }, processStartTag: function(name, attributes, selfClosing) { if (this[this.start_tag_handlers[name]]) { this[this.start_tag_handlers[name]](name, attributes, selfClosing); } else if (this[this.start_tag_handlers["-default"]]) { this[this.start_tag_handlers["-default"]](name, attributes, selfClosing); } else { throw(new Error("No handler found for "+name)); } }, processEndTag: function(name) { if (this[this.end_tag_handlers[name]]) { this[this.end_tag_handlers[name]](name); } else if (this[this.end_tag_handlers["-default"]]) { this[this.end_tag_handlers["-default"]](name); } else { throw(new Error("No handler found for "+name)); } }, startTagHtml: function(name, attributes) { modes.inBody.startTagHtml(name, attributes); } }; modes.initial = Object.create(modes.base); modes.initial.processEOF = function() { tree.parseError("expected-doctype-but-got-eof"); this.anythingElse(); tree.insertionMode.processEOF(); }; modes.initial.processComment = function(data) { tree.insertComment(data, tree.document); }; modes.initial.processDoctype = function(name, publicId, systemId, forceQuirks) { tree.insertDoctype(name || '', publicId || '', systemId || ''); if (forceQuirks || name != 'html' || (publicId != null && ([ "+//silmaril//dtd html pro v0r11 19970101//", "-//advasoft ltd//dtd html 3.0 aswedit + extensions//", "-//as//dtd html 3.0 aswedit + extensions//", "-//ietf//dtd html 2.0 level 1//", "-//ietf//dtd html 2.0 level 2//", "-//ietf//dtd html 2.0 strict level 1//", "-//ietf//dtd html 2.0 strict level 2//", "-//ietf//dtd html 2.0 strict//", "-//ietf//dtd html 2.0//", "-//ietf//dtd html 2.1e//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.0//", "-//ietf//dtd html 3.2 final//", "-//ietf//dtd html 3.2//", "-//ietf//dtd html 3//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 0//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 1//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 2//", "-//ietf//dtd html level 3//", "-//ietf//dtd html level 3//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 0//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 1//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 2//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict level 3//", "-//ietf//dtd html strict//", "-//ietf//dtd html strict//", "-//ietf//dtd html strict//", "-//ietf//dtd html//", "-//ietf//dtd html//", "-//ietf//dtd html//", "-//metrius//dtd metrius presentational//", "-//microsoft//dtd internet explorer 2.0 html strict//", "-//microsoft//dtd internet explorer 2.0 html//", "-//microsoft//dtd internet explorer 2.0 tables//", "-//microsoft//dtd internet explorer 3.0 html strict//", "-//microsoft//dtd internet explorer 3.0 html//", "-//microsoft//dtd internet explorer 3.0 tables//", "-//netscape comm. corp.//dtd html//", "-//netscape comm. corp.//dtd strict html//", "-//o'reilly and associates//dtd html 2.0//", "-//o'reilly and associates//dtd html extended 1.0//", "-//spyglass//dtd html 2.0 extended//", "-//sq//dtd html 2.0 hotmetal + extensions//", "-//sun microsystems corp.//dtd hotjava html//", "-//sun microsystems corp.//dtd hotjava strict html//", "-//w3c//dtd html 3 1995-03-24//", "-//w3c//dtd html 3.2 draft//", "-//w3c//dtd html 3.2 final//", "-//w3c//dtd html 3.2//", "-//w3c//dtd html 3.2s draft//", "-//w3c//dtd html 4.0 frameset//", "-//w3c//dtd html 4.0 transitional//", "-//w3c//dtd html experimental 19960712//", "-//w3c//dtd html experimental 970421//", "-//w3c//dtd w3 html//", "-//w3o//dtd w3 html 3.0//", "-//webtechs//dtd mozilla html 2.0//", "-//webtechs//dtd mozilla html//", "html" ].some(publicIdStartsWith) || [ "-//w3o//dtd w3 html strict 3.0//en//", "-/w3c/dtd html 4.0 transitional/en", "html" ].indexOf(publicId.toLowerCase()) > -1 || (systemId == null && [ "-//w3c//dtd html 4.01 transitional//", "-//w3c//dtd html 4.01 frameset//" ].some(publicIdStartsWith))) ) || (systemId != null && (systemId.toLowerCase() == "http://www.ibm.com/data/dtd/v11/ibmxhtml1-transitional.dtd")) ) { tree.compatMode = "quirks"; tree.parseError("quirky-doctype"); } else if (publicId != null && ([ "-//w3c//dtd xhtml 1.0 transitional//", "-//w3c//dtd xhtml 1.0 frameset//" ].some(publicIdStartsWith) || (systemId != null && [ "-//w3c//dtd html 4.01 transitional//", "-//w3c//dtd html 4.01 frameset//" ].indexOf(publicId.toLowerCase()) > -1)) ) { tree.compatMode = "limited quirks"; tree.parseError("almost-standards-doctype"); } else { if ((publicId == "-//W3C//DTD HTML 4.0//EN" && (systemId == null || systemId == "http://www.w3.org/TR/REC-html40/strict.dtd")) || (publicId == "-//W3C//DTD HTML 4.01//EN" && (systemId == null || systemId == "http://www.w3.org/TR/html4/strict.dtd")) || (publicId == "-//W3C//DTD XHTML 1.0 Strict//EN" && (systemId == "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd")) || (publicId == "-//W3C//DTD XHTML 1.1//EN" && (systemId == "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd")) ) { } else if (!((systemId == null || systemId == "about:legacy-compat") && publicId == null)) { tree.parseError("unknown-doctype"); } } tree.setInsertionMode('beforeHTML'); function publicIdStartsWith(string) { return publicId.toLowerCase().indexOf(string) === 0; } }; modes.initial.processCharacters = function(buffer) { buffer.skipLeadingWhitespace(); if (!buffer.length) return; tree.parseError('expected-doctype-but-got-chars'); this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.initial.processStartTag = function(name, attributes, selfClosing) { tree.parseError('expected-doctype-but-got-start-tag', {name: name}); this.anythingElse(); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.initial.processEndTag = function(name) { tree.parseError('expected-doctype-but-got-end-tag', {name: name}); this.anythingElse(); tree.insertionMode.processEndTag(name); }; modes.initial.anythingElse = function() { tree.compatMode = 'quirks'; tree.setInsertionMode('beforeHTML'); }; modes.beforeHTML = Object.create(modes.base); modes.beforeHTML.start_tag_handlers = { html: 'startTagHtml', '-default': 'startTagOther' }; modes.beforeHTML.processEOF = function() { this.anythingElse(); tree.insertionMode.processEOF(); }; modes.beforeHTML.processComment = function(data) { tree.insertComment(data, tree.document); }; modes.beforeHTML.processCharacters = function(buffer) { buffer.skipLeadingWhitespace(); if (!buffer.length) return; this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.beforeHTML.startTagHtml = function(name, attributes, selfClosing) { tree.insertHtmlElement(attributes); tree.setInsertionMode('beforeHead'); }; modes.beforeHTML.startTagOther = function(name, attributes, selfClosing) { this.anythingElse(); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.beforeHTML.processEndTag = function(name) { this.anythingElse(); tree.insertionMode.processEndTag(name); }; modes.beforeHTML.anythingElse = function() { tree.insertHtmlElement(); tree.setInsertionMode('beforeHead'); }; modes.afterAfterBody = Object.create(modes.base); modes.afterAfterBody.start_tag_handlers = { html: 'startTagHtml', '-default': 'startTagOther' }; modes.afterAfterBody.processComment = function(data) { tree.insertComment(data, tree.document); }; modes.afterAfterBody.processDoctype = function(data) { modes.inBody.processDoctype(data); }; modes.afterAfterBody.startTagHtml = function(data, attributes) { modes.inBody.startTagHtml(data, attributes); }; modes.afterAfterBody.startTagOther = function(name, attributes, selfClosing) { tree.parseError('unexpected-start-tag', {name: name}); tree.setInsertionMode('inBody'); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.afterAfterBody.endTagOther = function(name) { tree.parseError('unexpected-end-tag', {name: name}); tree.setInsertionMode('inBody'); tree.insertionMode.processEndTag(name); }; modes.afterAfterBody.processCharacters = function(data) { if (!isAllWhitespace(data.characters)) { tree.parseError('unexpected-char-after-body'); tree.setInsertionMode('inBody'); return tree.insertionMode.processCharacters(data); } modes.inBody.processCharacters(data); }; modes.afterBody = Object.create(modes.base); modes.afterBody.end_tag_handlers = { html: 'endTagHtml', '-default': 'endTagOther' }; modes.afterBody.processComment = function(data) { tree.insertComment(data, tree.openElements.rootNode); }; modes.afterBody.processCharacters = function(data) { if (!isAllWhitespace(data.characters)) { tree.parseError('unexpected-char-after-body'); tree.setInsertionMode('inBody'); return tree.insertionMode.processCharacters(data); } modes.inBody.processCharacters(data); }; modes.afterBody.processStartTag = function(name, attributes, selfClosing) { tree.parseError('unexpected-start-tag-after-body', {name: name}); tree.setInsertionMode('inBody'); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.afterBody.endTagHtml = function(name) { if (tree.context) { tree.parseError('end-html-in-innerhtml'); } else { tree.setInsertionMode('afterAfterBody'); } }; modes.afterBody.endTagOther = function(name) { tree.parseError('unexpected-end-tag-after-body', {name: name}); tree.setInsertionMode('inBody'); tree.insertionMode.processEndTag(name); }; modes.afterFrameset = Object.create(modes.base); modes.afterFrameset.start_tag_handlers = { html: 'startTagHtml', noframes: 'startTagNoframes', '-default': 'startTagOther' }; modes.afterFrameset.end_tag_handlers = { html: 'endTagHtml', '-default': 'endTagOther' }; modes.afterFrameset.processCharacters = function(buffer) { var characters = buffer.takeRemaining(); var whitespace = ""; for (var i = 0; i < characters.length; i++) { var ch = characters[i]; if (isWhitespace(ch)) whitespace += ch; } if (whitespace) { tree.insertText(whitespace); } if (whitespace.length < characters.length) tree.parseError('expected-eof-but-got-char'); }; modes.afterFrameset.startTagNoframes = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.afterFrameset.startTagOther = function(name, attributes) { tree.parseError("unexpected-start-tag-after-frameset", {name: name}); }; modes.afterFrameset.endTagHtml = function(name) { tree.setInsertionMode('afterAfterFrameset'); }; modes.afterFrameset.endTagOther = function(name) { tree.parseError("unexpected-end-tag-after-frameset", {name: name}); }; modes.beforeHead = Object.create(modes.base); modes.beforeHead.start_tag_handlers = { html: 'startTagHtml', head: 'startTagHead', '-default': 'startTagOther' }; modes.beforeHead.end_tag_handlers = { html: 'endTagImplyHead', head: 'endTagImplyHead', body: 'endTagImplyHead', br: 'endTagImplyHead', '-default': 'endTagOther' }; modes.beforeHead.processEOF = function() { this.startTagHead('head', []); tree.insertionMode.processEOF(); }; modes.beforeHead.processCharacters = function(buffer) { buffer.skipLeadingWhitespace(); if (!buffer.length) return; this.startTagHead('head', []); tree.insertionMode.processCharacters(buffer); }; modes.beforeHead.startTagHead = function(name, attributes) { tree.insertHeadElement(attributes); tree.setInsertionMode('inHead'); }; modes.beforeHead.startTagOther = function(name, attributes, selfClosing) { this.startTagHead('head', []); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.beforeHead.endTagImplyHead = function(name) { this.startTagHead('head', []); tree.insertionMode.processEndTag(name); }; modes.beforeHead.endTagOther = function(name) { tree.parseError('end-tag-after-implied-root', {name: name}); }; modes.inHead = Object.create(modes.base); modes.inHead.start_tag_handlers = { html: 'startTagHtml', head: 'startTagHead', title: 'startTagTitle', script: 'startTagScript', style: 'startTagNoFramesStyle', noscript: 'startTagNoScript', noframes: 'startTagNoFramesStyle', base: 'startTagBaseBasefontBgsoundLink', basefont: 'startTagBaseBasefontBgsoundLink', bgsound: 'startTagBaseBasefontBgsoundLink', link: 'startTagBaseBasefontBgsoundLink', meta: 'startTagMeta', "-default": 'startTagOther' }; modes.inHead.end_tag_handlers = { head: 'endTagHead', html: 'endTagHtmlBodyBr', body: 'endTagHtmlBodyBr', br: 'endTagHtmlBodyBr', "-default": 'endTagOther' }; modes.inHead.processEOF = function() { var name = tree.currentStackItem().localName; if (['title', 'style', 'script'].indexOf(name) != -1) { tree.parseError("expected-named-closing-tag-but-got-eof", {name: name}); tree.popElement(); } this.anythingElse(); tree.insertionMode.processEOF(); }; modes.inHead.processCharacters = function(buffer) { var leadingWhitespace = buffer.takeLeadingWhitespace(); if (leadingWhitespace) tree.insertText(leadingWhitespace); if (!buffer.length) return; this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.inHead.startTagHtml = function(name, attributes) { modes.inBody.processStartTag(name, attributes); }; modes.inHead.startTagHead = function(name, attributes) { tree.parseError('two-heads-are-not-better-than-one'); }; modes.inHead.startTagTitle = function(name, attributes) { tree.processGenericRCDATAStartTag(name, attributes); }; modes.inHead.startTagNoScript = function(name, attributes) { if (tree.scriptingEnabled) return tree.processGenericRawTextStartTag(name, attributes); tree.insertElement(name, attributes); tree.setInsertionMode('inHeadNoscript'); }; modes.inHead.startTagNoFramesStyle = function(name, attributes) { tree.processGenericRawTextStartTag(name, attributes); }; modes.inHead.startTagScript = function(name, attributes) { tree.insertElement(name, attributes); tree.tokenizer.setState(Tokenizer.SCRIPT_DATA); tree.originalInsertionMode = tree.insertionModeName; tree.setInsertionMode('text'); }; modes.inHead.startTagBaseBasefontBgsoundLink = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inHead.startTagMeta = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inHead.startTagOther = function(name, attributes, selfClosing) { this.anythingElse(); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.inHead.endTagHead = function(name) { if (tree.openElements.item(tree.openElements.length - 1).localName == 'head') { tree.openElements.pop(); } else { tree.parseError('unexpected-end-tag', {name: 'head'}); } tree.setInsertionMode('afterHead'); }; modes.inHead.endTagHtmlBodyBr = function(name) { this.anythingElse(); tree.insertionMode.processEndTag(name); }; modes.inHead.endTagOther = function(name) { tree.parseError('unexpected-end-tag', {name: name}); }; modes.inHead.anythingElse = function() { this.endTagHead('head'); }; modes.afterHead = Object.create(modes.base); modes.afterHead.start_tag_handlers = { html: 'startTagHtml', head: 'startTagHead', body: 'startTagBody', frameset: 'startTagFrameset', base: 'startTagFromHead', link: 'startTagFromHead', meta: 'startTagFromHead', script: 'startTagFromHead', style: 'startTagFromHead', title: 'startTagFromHead', "-default": 'startTagOther' }; modes.afterHead.end_tag_handlers = { body: 'endTagBodyHtmlBr', html: 'endTagBodyHtmlBr', br: 'endTagBodyHtmlBr', "-default": 'endTagOther' }; modes.afterHead.processEOF = function() { this.anythingElse(); tree.insertionMode.processEOF(); }; modes.afterHead.processCharacters = function(buffer) { var leadingWhitespace = buffer.takeLeadingWhitespace(); if (leadingWhitespace) tree.insertText(leadingWhitespace); if (!buffer.length) return; this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.afterHead.startTagHtml = function(name, attributes) { modes.inBody.processStartTag(name, attributes); }; modes.afterHead.startTagBody = function(name, attributes) { tree.framesetOk = false; tree.insertBodyElement(attributes); tree.setInsertionMode('inBody'); }; modes.afterHead.startTagFrameset = function(name, attributes) { tree.insertElement(name, attributes); tree.setInsertionMode('inFrameset'); }; modes.afterHead.startTagFromHead = function(name, attributes, selfClosing) { tree.parseError("unexpected-start-tag-out-of-my-head", {name: name}); tree.openElements.push(tree.head); modes.inHead.processStartTag(name, attributes, selfClosing); tree.openElements.remove(tree.head); }; modes.afterHead.startTagHead = function(name, attributes, selfClosing) { tree.parseError('unexpected-start-tag', {name: name}); }; modes.afterHead.startTagOther = function(name, attributes, selfClosing) { this.anythingElse(); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.afterHead.endTagBodyHtmlBr = function(name) { this.anythingElse(); tree.insertionMode.processEndTag(name); }; modes.afterHead.endTagOther = function(name) { tree.parseError('unexpected-end-tag', {name: name}); }; modes.afterHead.anythingElse = function() { tree.insertBodyElement([]); tree.setInsertionMode('inBody'); tree.framesetOk = true; } modes.inBody = Object.create(modes.base); modes.inBody.start_tag_handlers = { html: 'startTagHtml', head: 'startTagMisplaced', base: 'startTagProcessInHead', basefont: 'startTagProcessInHead', bgsound: 'startTagProcessInHead', link: 'startTagProcessInHead', meta: 'startTagProcessInHead', noframes: 'startTagProcessInHead', script: 'startTagProcessInHead', style: 'startTagProcessInHead', title: 'startTagProcessInHead', body: 'startTagBody', form: 'startTagForm', plaintext: 'startTagPlaintext', a: 'startTagA', button: 'startTagButton', xmp: 'startTagXmp', table: 'startTagTable', hr: 'startTagHr', image: 'startTagImage', input: 'startTagInput', textarea: 'startTagTextarea', select: 'startTagSelect', isindex: 'startTagIsindex', applet: 'startTagAppletMarqueeObject', marquee: 'startTagAppletMarqueeObject', object: 'startTagAppletMarqueeObject', li: 'startTagListItem', dd: 'startTagListItem', dt: 'startTagListItem', address: 'startTagCloseP', article: 'startTagCloseP', aside: 'startTagCloseP', blockquote: 'startTagCloseP', center: 'startTagCloseP', details: 'startTagCloseP', dir: 'startTagCloseP', div: 'startTagCloseP', dl: 'startTagCloseP', fieldset: 'startTagCloseP', figcaption: 'startTagCloseP', figure: 'startTagCloseP', footer: 'startTagCloseP', header: 'startTagCloseP', hgroup: 'startTagCloseP', main: 'startTagCloseP', menu: 'startTagCloseP', nav: 'startTagCloseP', ol: 'startTagCloseP', p: 'startTagCloseP', section: 'startTagCloseP', summary: 'startTagCloseP', ul: 'startTagCloseP', listing: 'startTagPreListing', pre: 'startTagPreListing', b: 'startTagFormatting', big: 'startTagFormatting', code: 'startTagFormatting', em: 'startTagFormatting', font: 'startTagFormatting', i: 'startTagFormatting', s: 'startTagFormatting', small: 'startTagFormatting', strike: 'startTagFormatting', strong: 'startTagFormatting', tt: 'startTagFormatting', u: 'startTagFormatting', nobr: 'startTagNobr', area: 'startTagVoidFormatting', br: 'startTagVoidFormatting', embed: 'startTagVoidFormatting', img: 'startTagVoidFormatting', keygen: 'startTagVoidFormatting', wbr: 'startTagVoidFormatting', param: 'startTagParamSourceTrack', source: 'startTagParamSourceTrack', track: 'startTagParamSourceTrack', iframe: 'startTagIFrame', noembed: 'startTagRawText', noscript: 'startTagRawText', h1: 'startTagHeading', h2: 'startTagHeading', h3: 'startTagHeading', h4: 'startTagHeading', h5: 'startTagHeading', h6: 'startTagHeading', caption: 'startTagMisplaced', col: 'startTagMisplaced', colgroup: 'startTagMisplaced', frame: 'startTagMisplaced', frameset: 'startTagFrameset', tbody: 'startTagMisplaced', td: 'startTagMisplaced', tfoot: 'startTagMisplaced', th: 'startTagMisplaced', thead: 'startTagMisplaced', tr: 'startTagMisplaced', option: 'startTagOptionOptgroup', optgroup: 'startTagOptionOptgroup', math: 'startTagMath', svg: 'startTagSVG', rt: 'startTagRpRt', rp: 'startTagRpRt', "-default": 'startTagOther' }; modes.inBody.end_tag_handlers = { p: 'endTagP', body: 'endTagBody', html: 'endTagHtml', address: 'endTagBlock', article: 'endTagBlock', aside: 'endTagBlock', blockquote: 'endTagBlock', button: 'endTagBlock', center: 'endTagBlock', details: 'endTagBlock', dir: 'endTagBlock', div: 'endTagBlock', dl: 'endTagBlock', fieldset: 'endTagBlock', figcaption: 'endTagBlock', figure: 'endTagBlock', footer: 'endTagBlock', header: 'endTagBlock', hgroup: 'endTagBlock', listing: 'endTagBlock', main: 'endTagBlock', menu: 'endTagBlock', nav: 'endTagBlock', ol: 'endTagBlock', pre: 'endTagBlock', section: 'endTagBlock', summary: 'endTagBlock', ul: 'endTagBlock', form: 'endTagForm', applet: 'endTagAppletMarqueeObject', marquee: 'endTagAppletMarqueeObject', object: 'endTagAppletMarqueeObject', dd: 'endTagListItem', dt: 'endTagListItem', li: 'endTagListItem', h1: 'endTagHeading', h2: 'endTagHeading', h3: 'endTagHeading', h4: 'endTagHeading', h5: 'endTagHeading', h6: 'endTagHeading', a: 'endTagFormatting', b: 'endTagFormatting', big: 'endTagFormatting', code: 'endTagFormatting', em: 'endTagFormatting', font: 'endTagFormatting', i: 'endTagFormatting', nobr: 'endTagFormatting', s: 'endTagFormatting', small: 'endTagFormatting', strike: 'endTagFormatting', strong: 'endTagFormatting', tt: 'endTagFormatting', u: 'endTagFormatting', br: 'endTagBr', "-default": 'endTagOther' }; modes.inBody.processCharacters = function(buffer) { if (tree.shouldSkipLeadingNewline) { tree.shouldSkipLeadingNewline = false; buffer.skipAtMostOneLeadingNewline(); } tree.reconstructActiveFormattingElements(); var characters = buffer.takeRemaining(); characters = characters.replace(/\u0000/g, function(match, index){ tree.parseError("invalid-codepoint"); return ''; }); if (!characters) return; tree.insertText(characters); if (tree.framesetOk && !isAllWhitespaceOrReplacementCharacters(characters)) tree.framesetOk = false; }; modes.inBody.startTagHtml = function(name, attributes) { tree.parseError('non-html-root'); tree.addAttributesToElement(tree.openElements.rootNode, attributes); }; modes.inBody.startTagProcessInHead = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.inBody.startTagBody = function(name, attributes) { tree.parseError('unexpected-start-tag', {name: 'body'}); if (tree.openElements.length == 1 || tree.openElements.item(1).localName != 'body') { assert.ok(tree.context); } else { tree.framesetOk = false; tree.addAttributesToElement(tree.openElements.bodyElement, attributes); } }; modes.inBody.startTagFrameset = function(name, attributes) { tree.parseError('unexpected-start-tag', {name: 'frameset'}); if (tree.openElements.length == 1 || tree.openElements.item(1).localName != 'body') { assert.ok(tree.context); } else if (tree.framesetOk) { tree.detachFromParent(tree.openElements.bodyElement); while (tree.openElements.length > 1) tree.openElements.pop(); tree.insertElement(name, attributes); tree.setInsertionMode('inFrameset'); } }; modes.inBody.startTagCloseP = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); }; modes.inBody.startTagPreListing = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); tree.framesetOk = false; tree.shouldSkipLeadingNewline = true; }; modes.inBody.startTagForm = function(name, attributes) { if (tree.form) { tree.parseError('unexpected-start-tag', {name: name}); } else { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); tree.form = tree.currentStackItem(); } }; modes.inBody.startTagRpRt = function(name, attributes) { if (tree.openElements.inScope('ruby')) { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != 'ruby') { tree.parseError('unexpected-start-tag', {name: name}); } } tree.insertElement(name, attributes); }; modes.inBody.startTagListItem = function(name, attributes) { var stopNames = {li: ['li'], dd: ['dd', 'dt'], dt: ['dd', 'dt']}; var stopName = stopNames[name]; var els = tree.openElements; for (var i = els.length - 1; i >= 0; i--) { var node = els.item(i); if (stopName.indexOf(node.localName) != -1) { tree.insertionMode.processEndTag(node.localName); break; } if (node.isSpecial() && node.localName !== 'p' && node.localName !== 'address' && node.localName !== 'div') break; } if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); tree.framesetOk = false; }; modes.inBody.startTagPlaintext = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertElement(name, attributes); tree.tokenizer.setState(Tokenizer.PLAINTEXT); }; modes.inBody.startTagHeading = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); if (tree.currentStackItem().isNumberedHeader()) { tree.parseError('unexpected-start-tag', {name: name}); tree.popElement(); } tree.insertElement(name, attributes); }; modes.inBody.startTagA = function(name, attributes) { var activeA = tree.elementInActiveFormattingElements('a'); if (activeA) { tree.parseError("unexpected-start-tag-implies-end-tag", {startName: "a", endName: "a"}); tree.adoptionAgencyEndTag('a'); if (tree.openElements.contains(activeA)) tree.openElements.remove(activeA); tree.removeElementFromActiveFormattingElements(activeA); } tree.reconstructActiveFormattingElements(); tree.insertFormattingElement(name, attributes); }; modes.inBody.startTagFormatting = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertFormattingElement(name, attributes); }; modes.inBody.startTagNobr = function(name, attributes) { tree.reconstructActiveFormattingElements(); if (tree.openElements.inScope('nobr')) { tree.parseError("unexpected-start-tag-implies-end-tag", {startName: 'nobr', endName: 'nobr'}); this.processEndTag('nobr'); tree.reconstructActiveFormattingElements(); } tree.insertFormattingElement(name, attributes); }; modes.inBody.startTagButton = function(name, attributes) { if (tree.openElements.inScope('button')) { tree.parseError('unexpected-start-tag-implies-end-tag', {startName: 'button', endName: 'button'}); this.processEndTag('button'); tree.insertionMode.processStartTag(name, attributes); } else { tree.framesetOk = false; tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); } }; modes.inBody.startTagAppletMarqueeObject = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); tree.activeFormattingElements.push(Marker); tree.framesetOk = false; }; modes.inBody.endTagAppletMarqueeObject = function(name) { if (!tree.openElements.inScope(name)) { tree.parseError("unexpected-end-tag", {name: name}); } else { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != name) { tree.parseError('end-tag-too-early', {name: name}); } tree.openElements.popUntilPopped(name); tree.clearActiveFormattingElements(); } }; modes.inBody.startTagXmp = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.processEndTag('p'); tree.reconstructActiveFormattingElements(); tree.processGenericRawTextStartTag(name, attributes); tree.framesetOk = false; }; modes.inBody.startTagTable = function(name, attributes) { if (tree.compatMode !== "quirks") if (tree.openElements.inButtonScope('p')) this.processEndTag('p'); tree.insertElement(name, attributes); tree.setInsertionMode('inTable'); tree.framesetOk = false; }; modes.inBody.startTagVoidFormatting = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertSelfClosingElement(name, attributes); tree.framesetOk = false; }; modes.inBody.startTagParamSourceTrack = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inBody.startTagHr = function(name, attributes) { if (tree.openElements.inButtonScope('p')) this.endTagP('p'); tree.insertSelfClosingElement(name, attributes); tree.framesetOk = false; }; modes.inBody.startTagImage = function(name, attributes) { tree.parseError('unexpected-start-tag-treated-as', {originalName: 'image', newName: 'img'}); this.processStartTag('img', attributes); }; modes.inBody.startTagInput = function(name, attributes) { var currentFramesetOk = tree.framesetOk; this.startTagVoidFormatting(name, attributes); for (var key in attributes) { if (attributes[key].nodeName == 'type') { if (attributes[key].nodeValue.toLowerCase() == 'hidden') tree.framesetOk = currentFramesetOk; break; } } }; modes.inBody.startTagIsindex = function(name, attributes) { tree.parseError('deprecated-tag', {name: 'isindex'}); tree.selfClosingFlagAcknowledged = true; if (tree.form) return; var formAttributes = []; var inputAttributes = []; var prompt = "This is a searchable index. Enter search keywords: "; for (var key in attributes) { switch (attributes[key].nodeName) { case 'action': formAttributes.push({nodeName: 'action', nodeValue: attributes[key].nodeValue}); break; case 'prompt': prompt = attributes[key].nodeValue; break; case 'name': break; default: inputAttributes.push({nodeName: attributes[key].nodeName, nodeValue: attributes[key].nodeValue}); } } inputAttributes.push({nodeName: 'name', nodeValue: 'isindex'}); this.processStartTag('form', formAttributes); this.processStartTag('hr'); this.processStartTag('label'); this.processCharacters(new CharacterBuffer(prompt)); this.processStartTag('input', inputAttributes); this.processEndTag('label'); this.processStartTag('hr'); this.processEndTag('form'); }; modes.inBody.startTagTextarea = function(name, attributes) { tree.insertElement(name, attributes); tree.tokenizer.setState(Tokenizer.RCDATA); tree.originalInsertionMode = tree.insertionModeName; tree.shouldSkipLeadingNewline = true; tree.framesetOk = false; tree.setInsertionMode('text'); }; modes.inBody.startTagIFrame = function(name, attributes) { tree.framesetOk = false; this.startTagRawText(name, attributes); }; modes.inBody.startTagRawText = function(name, attributes) { tree.processGenericRawTextStartTag(name, attributes); }; modes.inBody.startTagSelect = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); tree.framesetOk = false; var insertionModeName = tree.insertionModeName; if (insertionModeName == 'inTable' || insertionModeName == 'inCaption' || insertionModeName == 'inColumnGroup' || insertionModeName == 'inTableBody' || insertionModeName == 'inRow' || insertionModeName == 'inCell') { tree.setInsertionMode('inSelectInTable'); } else { tree.setInsertionMode('inSelect'); } }; modes.inBody.startTagMisplaced = function(name, attributes) { tree.parseError('unexpected-start-tag-ignored', {name: name}); }; modes.inBody.endTagMisplaced = function(name) { tree.parseError("unexpected-end-tag", {name: name}); }; modes.inBody.endTagBr = function(name) { tree.parseError("unexpected-end-tag-treated-as", {originalName: "br", newName: "br element"}); tree.reconstructActiveFormattingElements(); tree.insertElement(name, []); tree.popElement(); }; modes.inBody.startTagOptionOptgroup = function(name, attributes) { if (tree.currentStackItem().localName == 'option') tree.popElement(); tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); }; modes.inBody.startTagOther = function(name, attributes) { tree.reconstructActiveFormattingElements(); tree.insertElement(name, attributes); }; modes.inBody.endTagOther = function(name) { var node; for (var i = tree.openElements.length - 1; i > 0; i--) { node = tree.openElements.item(i); if (node.localName == name) { tree.generateImpliedEndTags(name); if (tree.currentStackItem().localName != name) tree.parseError('unexpected-end-tag', {name: name}); tree.openElements.remove_openElements_until(function(x) {return x === node;}); break; } if (node.isSpecial()) { tree.parseError('unexpected-end-tag', {name: name}); break; } } }; modes.inBody.startTagMath = function(name, attributes, selfClosing) { tree.reconstructActiveFormattingElements(); attributes = tree.adjustMathMLAttributes(attributes); attributes = tree.adjustForeignAttributes(attributes); tree.insertForeignElement(name, attributes, "http://www.w3.org/1998/Math/MathML", selfClosing); }; modes.inBody.startTagSVG = function(name, attributes, selfClosing) { tree.reconstructActiveFormattingElements(); attributes = tree.adjustSVGAttributes(attributes); attributes = tree.adjustForeignAttributes(attributes); tree.insertForeignElement(name, attributes, "http://www.w3.org/2000/svg", selfClosing); }; modes.inBody.endTagP = function(name) { if (!tree.openElements.inButtonScope('p')) { tree.parseError('unexpected-end-tag', {name: 'p'}); this.startTagCloseP('p', []); this.endTagP('p'); } else { tree.generateImpliedEndTags('p'); if (tree.currentStackItem().localName != 'p') tree.parseError('unexpected-implied-end-tag', {name: 'p'}); tree.openElements.popUntilPopped(name); } }; modes.inBody.endTagBody = function(name) { if (!tree.openElements.inScope('body')) { tree.parseError('unexpected-end-tag', {name: name}); return; } if (tree.currentStackItem().localName != 'body') { tree.parseError('expected-one-end-tag-but-got-another', { expectedName: tree.currentStackItem().localName, gotName: name }); } tree.setInsertionMode('afterBody'); }; modes.inBody.endTagHtml = function(name) { if (!tree.openElements.inScope('body')) { tree.parseError('unexpected-end-tag', {name: name}); return; } if (tree.currentStackItem().localName != 'body') { tree.parseError('expected-one-end-tag-but-got-another', { expectedName: tree.currentStackItem().localName, gotName: name }); } tree.setInsertionMode('afterBody'); tree.insertionMode.processEndTag(name); }; modes.inBody.endTagBlock = function(name) { if (!tree.openElements.inScope(name)) { tree.parseError('unexpected-end-tag', {name: name}); } else { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != name) { tree.parseError('end-tag-too-early', {name: name}); } tree.openElements.popUntilPopped(name); } }; modes.inBody.endTagForm = function(name) { var node = tree.form; tree.form = null; if (!node || !tree.openElements.inScope(name)) { tree.parseError('unexpected-end-tag', {name: name}); } else { tree.generateImpliedEndTags(); if (tree.currentStackItem() != node) { tree.parseError('end-tag-too-early-ignored', {name: 'form'}); } tree.openElements.remove(node); } }; modes.inBody.endTagListItem = function(name) { if (!tree.openElements.inListItemScope(name)) { tree.parseError('unexpected-end-tag', {name: name}); } else { tree.generateImpliedEndTags(name); if (tree.currentStackItem().localName != name) tree.parseError('end-tag-too-early', {name: name}); tree.openElements.popUntilPopped(name); } }; modes.inBody.endTagHeading = function(name) { if (!tree.openElements.hasNumberedHeaderElementInScope()) { tree.parseError('unexpected-end-tag', {name: name}); return; } tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != name) tree.parseError('end-tag-too-early', {name: name}); tree.openElements.remove_openElements_until(function(e) { return e.isNumberedHeader(); }); }; modes.inBody.endTagFormatting = function(name, attributes) { if (!tree.adoptionAgencyEndTag(name)) this.endTagOther(name, attributes); }; modes.inCaption = Object.create(modes.base); modes.inCaption.start_tag_handlers = { html: 'startTagHtml', caption: 'startTagTableElement', col: 'startTagTableElement', colgroup: 'startTagTableElement', tbody: 'startTagTableElement', td: 'startTagTableElement', tfoot: 'startTagTableElement', thead: 'startTagTableElement', tr: 'startTagTableElement', '-default': 'startTagOther' }; modes.inCaption.end_tag_handlers = { caption: 'endTagCaption', table: 'endTagTable', body: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', tbody: 'endTagIgnore', td: 'endTagIgnore', tfood: 'endTagIgnore', thead: 'endTagIgnore', tr: 'endTagIgnore', '-default': 'endTagOther' }; modes.inCaption.processCharacters = function(data) { modes.inBody.processCharacters(data); }; modes.inCaption.startTagTableElement = function(name, attributes) { tree.parseError('unexpected-end-tag', {name: name}); var ignoreEndTag = !tree.openElements.inTableScope('caption'); tree.insertionMode.processEndTag('caption'); if (!ignoreEndTag) tree.insertionMode.processStartTag(name, attributes); }; modes.inCaption.startTagOther = function(name, attributes, selfClosing) { modes.inBody.processStartTag(name, attributes, selfClosing); }; modes.inCaption.endTagCaption = function(name) { if (!tree.openElements.inTableScope('caption')) { assert.ok(tree.context); tree.parseError('unexpected-end-tag', {name: name}); } else { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != 'caption') { tree.parseError('expected-one-end-tag-but-got-another', { gotName: "caption", expectedName: tree.currentStackItem().localName }); } tree.openElements.popUntilPopped('caption'); tree.clearActiveFormattingElements(); tree.setInsertionMode('inTable'); } }; modes.inCaption.endTagTable = function(name) { tree.parseError("unexpected-end-table-in-caption"); var ignoreEndTag = !tree.openElements.inTableScope('caption'); tree.insertionMode.processEndTag('caption'); if (!ignoreEndTag) tree.insertionMode.processEndTag(name); }; modes.inCaption.endTagIgnore = function(name) { tree.parseError('unexpected-end-tag', {name: name}); }; modes.inCaption.endTagOther = function(name) { modes.inBody.processEndTag(name); }; modes.inCell = Object.create(modes.base); modes.inCell.start_tag_handlers = { html: 'startTagHtml', caption: 'startTagTableOther', col: 'startTagTableOther', colgroup: 'startTagTableOther', tbody: 'startTagTableOther', td: 'startTagTableOther', tfoot: 'startTagTableOther', th: 'startTagTableOther', thead: 'startTagTableOther', tr: 'startTagTableOther', '-default': 'startTagOther' }; modes.inCell.end_tag_handlers = { td: 'endTagTableCell', th: 'endTagTableCell', body: 'endTagIgnore', caption: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', table: 'endTagImply', tbody: 'endTagImply', tfoot: 'endTagImply', thead: 'endTagImply', tr: 'endTagImply', '-default': 'endTagOther' }; modes.inCell.processCharacters = function(data) { modes.inBody.processCharacters(data); }; modes.inCell.startTagTableOther = function(name, attributes, selfClosing) { if (tree.openElements.inTableScope('td') || tree.openElements.inTableScope('th')) { this.closeCell(); tree.insertionMode.processStartTag(name, attributes, selfClosing); } else { tree.parseError('unexpected-start-tag', {name: name}); } }; modes.inCell.startTagOther = function(name, attributes, selfClosing) { modes.inBody.processStartTag(name, attributes, selfClosing); }; modes.inCell.endTagTableCell = function(name) { if (tree.openElements.inTableScope(name)) { tree.generateImpliedEndTags(name); if (tree.currentStackItem().localName != name.toLowerCase()) { tree.parseError('unexpected-cell-end-tag', {name: name}); tree.openElements.popUntilPopped(name); } else { tree.popElement(); } tree.clearActiveFormattingElements(); tree.setInsertionMode('inRow'); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inCell.endTagIgnore = function(name) { tree.parseError('unexpected-end-tag', {name: name}); }; modes.inCell.endTagImply = function(name) { if (tree.openElements.inTableScope(name)) { this.closeCell(); tree.insertionMode.processEndTag(name); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inCell.endTagOther = function(name) { modes.inBody.processEndTag(name); }; modes.inCell.closeCell = function() { if (tree.openElements.inTableScope('td')) { this.endTagTableCell('td'); } else if (tree.openElements.inTableScope('th')) { this.endTagTableCell('th'); } }; modes.inColumnGroup = Object.create(modes.base); modes.inColumnGroup.start_tag_handlers = { html: 'startTagHtml', col: 'startTagCol', '-default': 'startTagOther' }; modes.inColumnGroup.end_tag_handlers = { colgroup: 'endTagColgroup', col: 'endTagCol', '-default': 'endTagOther' }; modes.inColumnGroup.ignoreEndTagColgroup = function() { return tree.currentStackItem().localName == 'html'; }; modes.inColumnGroup.processCharacters = function(buffer) { var leadingWhitespace = buffer.takeLeadingWhitespace(); if (leadingWhitespace) tree.insertText(leadingWhitespace); if (!buffer.length) return; var ignoreEndTag = this.ignoreEndTagColgroup(); this.endTagColgroup('colgroup'); if (!ignoreEndTag) tree.insertionMode.processCharacters(buffer); }; modes.inColumnGroup.startTagCol = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inColumnGroup.startTagOther = function(name, attributes, selfClosing) { var ignoreEndTag = this.ignoreEndTagColgroup(); this.endTagColgroup('colgroup'); if (!ignoreEndTag) tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.inColumnGroup.endTagColgroup = function(name) { if (this.ignoreEndTagColgroup()) { assert.ok(tree.context); tree.parseError('unexpected-end-tag', {name: name}); } else { tree.popElement(); tree.setInsertionMode('inTable'); } }; modes.inColumnGroup.endTagCol = function(name) { tree.parseError("no-end-tag", {name: 'col'}); }; modes.inColumnGroup.endTagOther = function(name) { var ignoreEndTag = this.ignoreEndTagColgroup(); this.endTagColgroup('colgroup'); if (!ignoreEndTag) tree.insertionMode.processEndTag(name) ; }; modes.inForeignContent = Object.create(modes.base); modes.inForeignContent.processStartTag = function(name, attributes, selfClosing) { if (['b', 'big', 'blockquote', 'body', 'br', 'center', 'code', 'dd', 'div', 'dl', 'dt', 'em', 'embed', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'hr', 'i', 'img', 'li', 'listing', 'menu', 'meta', 'nobr', 'ol', 'p', 'pre', 'ruby', 's', 'small', 'span', 'strong', 'strike', 'sub', 'sup', 'table', 'tt', 'u', 'ul', 'var'].indexOf(name) != -1 || (name == 'font' && attributes.some(function(attr){ return ['color', 'face', 'size'].indexOf(attr.nodeName) >= 0 }))) { tree.parseError('unexpected-html-element-in-foreign-content', {name: name}); while (tree.currentStackItem().isForeign() && !tree.currentStackItem().isHtmlIntegrationPoint() && !tree.currentStackItem().isMathMLTextIntegrationPoint()) { tree.openElements.pop(); } tree.insertionMode.processStartTag(name, attributes, selfClosing); return; } if (tree.currentStackItem().namespaceURI == "http://www.w3.org/1998/Math/MathML") { attributes = tree.adjustMathMLAttributes(attributes); } if (tree.currentStackItem().namespaceURI == "http://www.w3.org/2000/svg") { name = tree.adjustSVGTagNameCase(name); attributes = tree.adjustSVGAttributes(attributes); } attributes = tree.adjustForeignAttributes(attributes); tree.insertForeignElement(name, attributes, tree.currentStackItem().namespaceURI, selfClosing); }; modes.inForeignContent.processEndTag = function(name) { var node = tree.currentStackItem(); var index = tree.openElements.length - 1; if (node.localName.toLowerCase() != name) tree.parseError("unexpected-end-tag", {name: name}); while (true) { if (index === 0) break; if (node.localName.toLowerCase() == name) { while (tree.openElements.pop() != node); break; } index -= 1; node = tree.openElements.item(index); if (node.isForeign()) { continue; } else { tree.insertionMode.processEndTag(name); break; } } }; modes.inForeignContent.processCharacters = function(buffer) { var characters = buffer.takeRemaining(); characters = characters.replace(/\u0000/g, function(match, index){ tree.parseError('invalid-codepoint'); return '\uFFFD'; }); if (tree.framesetOk && !isAllWhitespaceOrReplacementCharacters(characters)) tree.framesetOk = false; tree.insertText(characters); }; modes.inHeadNoscript = Object.create(modes.base); modes.inHeadNoscript.start_tag_handlers = { html: 'startTagHtml', basefont: 'startTagBasefontBgsoundLinkMetaNoframesStyle', bgsound: 'startTagBasefontBgsoundLinkMetaNoframesStyle', link: 'startTagBasefontBgsoundLinkMetaNoframesStyle', meta: 'startTagBasefontBgsoundLinkMetaNoframesStyle', noframes: 'startTagBasefontBgsoundLinkMetaNoframesStyle', style: 'startTagBasefontBgsoundLinkMetaNoframesStyle', head: 'startTagHeadNoscript', noscript: 'startTagHeadNoscript', "-default": 'startTagOther' }; modes.inHeadNoscript.end_tag_handlers = { noscript: 'endTagNoscript', br: 'endTagBr', '-default': 'endTagOther' }; modes.inHeadNoscript.processCharacters = function(buffer) { var leadingWhitespace = buffer.takeLeadingWhitespace(); if (leadingWhitespace) tree.insertText(leadingWhitespace); if (!buffer.length) return; tree.parseError("unexpected-char-in-frameset"); this.anythingElse(); tree.insertionMode.processCharacters(buffer); }; modes.inHeadNoscript.processComment = function(data) { modes.inHead.processComment(data); }; modes.inHeadNoscript.startTagBasefontBgsoundLinkMetaNoframesStyle = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.inHeadNoscript.startTagHeadNoscript = function(name, attributes) { tree.parseError("unexpected-start-tag-in-frameset", {name: name}); }; modes.inHeadNoscript.startTagOther = function(name, attributes) { tree.parseError("unexpected-start-tag-in-frameset", {name: name}); this.anythingElse(); tree.insertionMode.processStartTag(name, attributes); }; modes.inHeadNoscript.endTagBr = function(name, attributes) { tree.parseError("unexpected-end-tag-in-frameset", {name: name}); this.anythingElse(); tree.insertionMode.processEndTag(name, attributes); }; modes.inHeadNoscript.endTagNoscript = function(name, attributes) { tree.popElement(); tree.setInsertionMode('inHead'); }; modes.inHeadNoscript.endTagOther = function(name, attributes) { tree.parseError("unexpected-end-tag-in-frameset", {name: name}); }; modes.inHeadNoscript.anythingElse = function() { tree.popElement(); tree.setInsertionMode('inHead'); }; modes.inFrameset = Object.create(modes.base); modes.inFrameset.start_tag_handlers = { html: 'startTagHtml', frameset: 'startTagFrameset', frame: 'startTagFrame', noframes: 'startTagNoframes', "-default": 'startTagOther' }; modes.inFrameset.end_tag_handlers = { frameset: 'endTagFrameset', noframes: 'endTagNoframes', '-default': 'endTagOther' }; modes.inFrameset.processCharacters = function(data) { tree.parseError("unexpected-char-in-frameset"); }; modes.inFrameset.startTagFrameset = function(name, attributes) { tree.insertElement(name, attributes); }; modes.inFrameset.startTagFrame = function(name, attributes) { tree.insertSelfClosingElement(name, attributes); }; modes.inFrameset.startTagNoframes = function(name, attributes) { modes.inBody.processStartTag(name, attributes); }; modes.inFrameset.startTagOther = function(name, attributes) { tree.parseError("unexpected-start-tag-in-frameset", {name: name}); }; modes.inFrameset.endTagFrameset = function(name, attributes) { if (tree.currentStackItem().localName == 'html') { tree.parseError("unexpected-frameset-in-frameset-innerhtml"); } else { tree.popElement(); } if (!tree.context && tree.currentStackItem().localName != 'frameset') { tree.setInsertionMode('afterFrameset'); } }; modes.inFrameset.endTagNoframes = function(name) { modes.inBody.processEndTag(name); }; modes.inFrameset.endTagOther = function(name) { tree.parseError("unexpected-end-tag-in-frameset", {name: name}); }; modes.inTable = Object.create(modes.base); modes.inTable.start_tag_handlers = { html: 'startTagHtml', caption: 'startTagCaption', colgroup: 'startTagColgroup', col: 'startTagCol', table: 'startTagTable', tbody: 'startTagRowGroup', tfoot: 'startTagRowGroup', thead: 'startTagRowGroup', td: 'startTagImplyTbody', th: 'startTagImplyTbody', tr: 'startTagImplyTbody', style: 'startTagStyleScript', script: 'startTagStyleScript', input: 'startTagInput', form: 'startTagForm', '-default': 'startTagOther' }; modes.inTable.end_tag_handlers = { table: 'endTagTable', body: 'endTagIgnore', caption: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', tbody: 'endTagIgnore', td: 'endTagIgnore', tfoot: 'endTagIgnore', th: 'endTagIgnore', thead: 'endTagIgnore', tr: 'endTagIgnore', '-default': 'endTagOther' }; modes.inTable.processCharacters = function(data) { if (tree.currentStackItem().isFosterParenting()) { var originalInsertionMode = tree.insertionModeName; tree.setInsertionMode('inTableText'); tree.originalInsertionMode = originalInsertionMode; tree.insertionMode.processCharacters(data); } else { tree.redirectAttachToFosterParent = true; modes.inBody.processCharacters(data); tree.redirectAttachToFosterParent = false; } }; modes.inTable.startTagCaption = function(name, attributes) { tree.openElements.popUntilTableScopeMarker(); tree.activeFormattingElements.push(Marker); tree.insertElement(name, attributes); tree.setInsertionMode('inCaption'); }; modes.inTable.startTagColgroup = function(name, attributes) { tree.openElements.popUntilTableScopeMarker(); tree.insertElement(name, attributes); tree.setInsertionMode('inColumnGroup'); }; modes.inTable.startTagCol = function(name, attributes) { this.startTagColgroup('colgroup', []); tree.insertionMode.processStartTag(name, attributes); }; modes.inTable.startTagRowGroup = function(name, attributes) { tree.openElements.popUntilTableScopeMarker(); tree.insertElement(name, attributes); tree.setInsertionMode('inTableBody'); }; modes.inTable.startTagImplyTbody = function(name, attributes) { this.startTagRowGroup('tbody', []); tree.insertionMode.processStartTag(name, attributes); }; modes.inTable.startTagTable = function(name, attributes) { tree.parseError("unexpected-start-tag-implies-end-tag", {startName: "table", endName: "table"}); tree.insertionMode.processEndTag('table'); if (!tree.context) tree.insertionMode.processStartTag(name, attributes); }; modes.inTable.startTagStyleScript = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.inTable.startTagInput = function(name, attributes) { for (var key in attributes) { if (attributes[key].nodeName.toLowerCase() == 'type') { if (attributes[key].nodeValue.toLowerCase() == 'hidden') { tree.parseError("unexpected-hidden-input-in-table"); tree.insertElement(name, attributes); tree.openElements.pop(); return; } break; } } this.startTagOther(name, attributes); }; modes.inTable.startTagForm = function(name, attributes) { tree.parseError("unexpected-form-in-table"); if (!tree.form) { tree.insertElement(name, attributes); tree.form = tree.currentStackItem(); tree.openElements.pop(); } }; modes.inTable.startTagOther = function(name, attributes, selfClosing) { tree.parseError("unexpected-start-tag-implies-table-voodoo", {name: name}); tree.redirectAttachToFosterParent = true; modes.inBody.processStartTag(name, attributes, selfClosing); tree.redirectAttachToFosterParent = false; }; modes.inTable.endTagTable = function(name) { if (tree.openElements.inTableScope(name)) { tree.generateImpliedEndTags(); if (tree.currentStackItem().localName != name) { tree.parseError("end-tag-too-early-named", {gotName: 'table', expectedName: tree.currentStackItem().localName}); } tree.openElements.popUntilPopped('table'); tree.resetInsertionMode(); } else { assert.ok(tree.context); tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inTable.endTagIgnore = function(name) { tree.parseError("unexpected-end-tag", {name: name}); }; modes.inTable.endTagOther = function(name) { tree.parseError("unexpected-end-tag-implies-table-voodoo", {name: name}); tree.redirectAttachToFosterParent = true; modes.inBody.processEndTag(name); tree.redirectAttachToFosterParent = false; }; modes.inTableText = Object.create(modes.base); modes.inTableText.flushCharacters = function() { var characters = tree.pendingTableCharacters.join(''); if (!isAllWhitespace(characters)) { tree.redirectAttachToFosterParent = true; tree.reconstructActiveFormattingElements(); tree.insertText(characters); tree.framesetOk = false; tree.redirectAttachToFosterParent = false; } else { tree.insertText(characters); } tree.pendingTableCharacters = []; }; modes.inTableText.processComment = function(data) { this.flushCharacters(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processComment(data); }; modes.inTableText.processEOF = function(data) { this.flushCharacters(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processEOF(); }; modes.inTableText.processCharacters = function(buffer) { var characters = buffer.takeRemaining(); characters = characters.replace(/\u0000/g, function(match, index){ tree.parseError("invalid-codepoint"); return ''; }); if (!characters) return; tree.pendingTableCharacters.push(characters); }; modes.inTableText.processStartTag = function(name, attributes, selfClosing) { this.flushCharacters(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processStartTag(name, attributes, selfClosing); }; modes.inTableText.processEndTag = function(name, attributes) { this.flushCharacters(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processEndTag(name, attributes); }; modes.inTableBody = Object.create(modes.base); modes.inTableBody.start_tag_handlers = { html: 'startTagHtml', tr: 'startTagTr', td: 'startTagTableCell', th: 'startTagTableCell', caption: 'startTagTableOther', col: 'startTagTableOther', colgroup: 'startTagTableOther', tbody: 'startTagTableOther', tfoot: 'startTagTableOther', thead: 'startTagTableOther', '-default': 'startTagOther' }; modes.inTableBody.end_tag_handlers = { table: 'endTagTable', tbody: 'endTagTableRowGroup', tfoot: 'endTagTableRowGroup', thead: 'endTagTableRowGroup', body: 'endTagIgnore', caption: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', td: 'endTagIgnore', th: 'endTagIgnore', tr: 'endTagIgnore', '-default': 'endTagOther' }; modes.inTableBody.processCharacters = function(data) { modes.inTable.processCharacters(data); }; modes.inTableBody.startTagTr = function(name, attributes) { tree.openElements.popUntilTableBodyScopeMarker(); tree.insertElement(name, attributes); tree.setInsertionMode('inRow'); }; modes.inTableBody.startTagTableCell = function(name, attributes) { tree.parseError("unexpected-cell-in-table-body", {name: name}); this.startTagTr('tr', []); tree.insertionMode.processStartTag(name, attributes); }; modes.inTableBody.startTagTableOther = function(name, attributes) { if (tree.openElements.inTableScope('tbody') || tree.openElements.inTableScope('thead') || tree.openElements.inTableScope('tfoot')) { tree.openElements.popUntilTableBodyScopeMarker(); this.endTagTableRowGroup(tree.currentStackItem().localName); tree.insertionMode.processStartTag(name, attributes); } else { tree.parseError('unexpected-start-tag', {name: name}); } }; modes.inTableBody.startTagOther = function(name, attributes) { modes.inTable.processStartTag(name, attributes); }; modes.inTableBody.endTagTableRowGroup = function(name) { if (tree.openElements.inTableScope(name)) { tree.openElements.popUntilTableBodyScopeMarker(); tree.popElement(); tree.setInsertionMode('inTable'); } else { tree.parseError('unexpected-end-tag-in-table-body', {name: name}); } }; modes.inTableBody.endTagTable = function(name) { if (tree.openElements.inTableScope('tbody') || tree.openElements.inTableScope('thead') || tree.openElements.inTableScope('tfoot')) { tree.openElements.popUntilTableBodyScopeMarker(); this.endTagTableRowGroup(tree.currentStackItem().localName); tree.insertionMode.processEndTag(name); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inTableBody.endTagIgnore = function(name) { tree.parseError("unexpected-end-tag-in-table-body", {name: name}); }; modes.inTableBody.endTagOther = function(name) { modes.inTable.processEndTag(name); }; modes.inSelect = Object.create(modes.base); modes.inSelect.start_tag_handlers = { html: 'startTagHtml', option: 'startTagOption', optgroup: 'startTagOptgroup', select: 'startTagSelect', input: 'startTagInput', keygen: 'startTagInput', textarea: 'startTagInput', script: 'startTagScript', '-default': 'startTagOther' }; modes.inSelect.end_tag_handlers = { option: 'endTagOption', optgroup: 'endTagOptgroup', select: 'endTagSelect', caption: 'endTagTableElements', table: 'endTagTableElements', tbody: 'endTagTableElements', tfoot: 'endTagTableElements', thead: 'endTagTableElements', tr: 'endTagTableElements', td: 'endTagTableElements', th: 'endTagTableElements', '-default': 'endTagOther' }; modes.inSelect.processCharacters = function(buffer) { var data = buffer.takeRemaining(); data = data.replace(/\u0000/g, function(match, index){ tree.parseError("invalid-codepoint"); return ''; }); if (!data) return; tree.insertText(data); }; modes.inSelect.startTagOption = function(name, attributes) { if (tree.currentStackItem().localName == 'option') tree.popElement(); tree.insertElement(name, attributes); }; modes.inSelect.startTagOptgroup = function(name, attributes) { if (tree.currentStackItem().localName == 'option') tree.popElement(); if (tree.currentStackItem().localName == 'optgroup') tree.popElement(); tree.insertElement(name, attributes); }; modes.inSelect.endTagOption = function(name) { if (tree.currentStackItem().localName !== 'option') { tree.parseError('unexpected-end-tag-in-select', {name: name}); return; } tree.popElement(); }; modes.inSelect.endTagOptgroup = function(name) { if (tree.currentStackItem().localName == 'option' && tree.openElements.item(tree.openElements.length - 2).localName == 'optgroup') { tree.popElement(); } if (tree.currentStackItem().localName == 'optgroup') { tree.popElement(); } else { tree.parseError('unexpected-end-tag-in-select', {name: 'optgroup'}); } }; modes.inSelect.startTagSelect = function(name) { tree.parseError("unexpected-select-in-select"); this.endTagSelect('select'); }; modes.inSelect.endTagSelect = function(name) { if (tree.openElements.inTableScope('select')) { tree.openElements.popUntilPopped('select'); tree.resetInsertionMode(); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inSelect.startTagInput = function(name, attributes) { tree.parseError("unexpected-input-in-select"); if (tree.openElements.inSelectScope('select')) { this.endTagSelect('select'); tree.insertionMode.processStartTag(name, attributes); } }; modes.inSelect.startTagScript = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.inSelect.endTagTableElements = function(name) { tree.parseError('unexpected-end-tag-in-select', {name: name}); if (tree.openElements.inTableScope(name)) { this.endTagSelect('select'); tree.insertionMode.processEndTag(name); } }; modes.inSelect.startTagOther = function(name, attributes) { tree.parseError("unexpected-start-tag-in-select", {name: name}); }; modes.inSelect.endTagOther = function(name) { tree.parseError('unexpected-end-tag-in-select', {name: name}); }; modes.inSelectInTable = Object.create(modes.base); modes.inSelectInTable.start_tag_handlers = { caption: 'startTagTable', table: 'startTagTable', tbody: 'startTagTable', tfoot: 'startTagTable', thead: 'startTagTable', tr: 'startTagTable', td: 'startTagTable', th: 'startTagTable', '-default': 'startTagOther' }; modes.inSelectInTable.end_tag_handlers = { caption: 'endTagTable', table: 'endTagTable', tbody: 'endTagTable', tfoot: 'endTagTable', thead: 'endTagTable', tr: 'endTagTable', td: 'endTagTable', th: 'endTagTable', '-default': 'endTagOther' }; modes.inSelectInTable.processCharacters = function(data) { modes.inSelect.processCharacters(data); }; modes.inSelectInTable.startTagTable = function(name, attributes) { tree.parseError("unexpected-table-element-start-tag-in-select-in-table", {name: name}); this.endTagOther("select"); tree.insertionMode.processStartTag(name, attributes); }; modes.inSelectInTable.startTagOther = function(name, attributes, selfClosing) { modes.inSelect.processStartTag(name, attributes, selfClosing); }; modes.inSelectInTable.endTagTable = function(name) { tree.parseError("unexpected-table-element-end-tag-in-select-in-table", {name: name}); if (tree.openElements.inTableScope(name)) { this.endTagOther("select"); tree.insertionMode.processEndTag(name); } }; modes.inSelectInTable.endTagOther = function(name) { modes.inSelect.processEndTag(name); }; modes.inRow = Object.create(modes.base); modes.inRow.start_tag_handlers = { html: 'startTagHtml', td: 'startTagTableCell', th: 'startTagTableCell', caption: 'startTagTableOther', col: 'startTagTableOther', colgroup: 'startTagTableOther', tbody: 'startTagTableOther', tfoot: 'startTagTableOther', thead: 'startTagTableOther', tr: 'startTagTableOther', '-default': 'startTagOther' }; modes.inRow.end_tag_handlers = { tr: 'endTagTr', table: 'endTagTable', tbody: 'endTagTableRowGroup', tfoot: 'endTagTableRowGroup', thead: 'endTagTableRowGroup', body: 'endTagIgnore', caption: 'endTagIgnore', col: 'endTagIgnore', colgroup: 'endTagIgnore', html: 'endTagIgnore', td: 'endTagIgnore', th: 'endTagIgnore', '-default': 'endTagOther' }; modes.inRow.processCharacters = function(data) { modes.inTable.processCharacters(data); }; modes.inRow.startTagTableCell = function(name, attributes) { tree.openElements.popUntilTableRowScopeMarker(); tree.insertElement(name, attributes); tree.setInsertionMode('inCell'); tree.activeFormattingElements.push(Marker); }; modes.inRow.startTagTableOther = function(name, attributes) { var ignoreEndTag = this.ignoreEndTagTr(); this.endTagTr('tr'); if (!ignoreEndTag) tree.insertionMode.processStartTag(name, attributes); }; modes.inRow.startTagOther = function(name, attributes, selfClosing) { modes.inTable.processStartTag(name, attributes, selfClosing); }; modes.inRow.endTagTr = function(name) { if (this.ignoreEndTagTr()) { assert.ok(tree.context); tree.parseError('unexpected-end-tag', {name: name}); } else { tree.openElements.popUntilTableRowScopeMarker(); tree.popElement(); tree.setInsertionMode('inTableBody'); } }; modes.inRow.endTagTable = function(name) { var ignoreEndTag = this.ignoreEndTagTr(); this.endTagTr('tr'); if (!ignoreEndTag) tree.insertionMode.processEndTag(name); }; modes.inRow.endTagTableRowGroup = function(name) { if (tree.openElements.inTableScope(name)) { this.endTagTr('tr'); tree.insertionMode.processEndTag(name); } else { tree.parseError('unexpected-end-tag', {name: name}); } }; modes.inRow.endTagIgnore = function(name) { tree.parseError("unexpected-end-tag-in-table-row", {name: name}); }; modes.inRow.endTagOther = function(name) { modes.inTable.processEndTag(name); }; modes.inRow.ignoreEndTagTr = function() { return !tree.openElements.inTableScope('tr'); }; modes.afterAfterFrameset = Object.create(modes.base); modes.afterAfterFrameset.start_tag_handlers = { html: 'startTagHtml', noframes: 'startTagNoFrames', '-default': 'startTagOther' }; modes.afterAfterFrameset.processEOF = function() {}; modes.afterAfterFrameset.processComment = function(data) { tree.insertComment(data, tree.document); }; modes.afterAfterFrameset.processCharacters = function(buffer) { var characters = buffer.takeRemaining(); var whitespace = ""; for (var i = 0; i < characters.length; i++) { var ch = characters[i]; if (isWhitespace(ch)) whitespace += ch; } if (whitespace) { tree.reconstructActiveFormattingElements(); tree.insertText(whitespace); } if (whitespace.length < characters.length) tree.parseError('expected-eof-but-got-char'); }; modes.afterAfterFrameset.startTagNoFrames = function(name, attributes) { modes.inHead.processStartTag(name, attributes); }; modes.afterAfterFrameset.startTagOther = function(name, attributes, selfClosing) { tree.parseError('expected-eof-but-got-start-tag', {name: name}); }; modes.afterAfterFrameset.processEndTag = function(name, attributes) { tree.parseError('expected-eof-but-got-end-tag', {name: name}); }; modes.text = Object.create(modes.base); modes.text.start_tag_handlers = { '-default': 'startTagOther' }; modes.text.end_tag_handlers = { script: 'endTagScript', '-default': 'endTagOther' }; modes.text.processCharacters = function(buffer) { if (tree.shouldSkipLeadingNewline) { tree.shouldSkipLeadingNewline = false; buffer.skipAtMostOneLeadingNewline(); } var data = buffer.takeRemaining(); if (!data) return; tree.insertText(data); }; modes.text.processEOF = function() { tree.parseError("expected-named-closing-tag-but-got-eof", {name: tree.currentStackItem().localName}); tree.openElements.pop(); tree.setInsertionMode(tree.originalInsertionMode); tree.insertionMode.processEOF(); }; modes.text.startTagOther = function(name) { throw "Tried to process start tag " + name + " in RCDATA/RAWTEXT mode"; }; modes.text.endTagScript = function(name) { var node = tree.openElements.pop(); assert.ok(node.localName == 'script'); tree.setInsertionMode(tree.originalInsertionMode); }; modes.text.endTagOther = function(name) { tree.openElements.pop(); tree.setInsertionMode(tree.originalInsertionMode); }; } TreeBuilder.prototype.setInsertionMode = function(name) { this.insertionMode = this.insertionModes[name]; this.insertionModeName = name; }; TreeBuilder.prototype.adoptionAgencyEndTag = function(name) { var outerIterationLimit = 8; var innerIterationLimit = 3; var formattingElement; function isActiveFormattingElement(el) { return el === formattingElement; } var outerLoopCounter = 0; while (outerLoopCounter++ < outerIterationLimit) { formattingElement = this.elementInActiveFormattingElements(name); if (!formattingElement || (this.openElements.contains(formattingElement) && !this.openElements.inScope(formattingElement.localName))) { this.parseError('adoption-agency-1.1', {name: name}); return false; } if (!this.openElements.contains(formattingElement)) { this.parseError('adoption-agency-1.2', {name: name}); this.removeElementFromActiveFormattingElements(formattingElement); return true; } if (!this.openElements.inScope(formattingElement.localName)) { this.parseError('adoption-agency-4.4', {name: name}); } if (formattingElement != this.currentStackItem()) { this.parseError('adoption-agency-1.3', {name: name}); } var furthestBlock = this.openElements.furthestBlockForFormattingElement(formattingElement.node); if (!furthestBlock) { this.openElements.remove_openElements_until(isActiveFormattingElement); this.removeElementFromActiveFormattingElements(formattingElement); return true; } var afeIndex = this.openElements.elements.indexOf(formattingElement); var commonAncestor = this.openElements.item(afeIndex - 1); var bookmark = this.activeFormattingElements.indexOf(formattingElement); var node = furthestBlock; var lastNode = furthestBlock; var index = this.openElements.elements.indexOf(node); var innerLoopCounter = 0; while (innerLoopCounter++ < innerIterationLimit) { index -= 1; node = this.openElements.item(index); if (this.activeFormattingElements.indexOf(node) < 0) { this.openElements.elements.splice(index, 1); continue; } if (node == formattingElement) break; if (lastNode == furthestBlock) bookmark = this.activeFormattingElements.indexOf(node) + 1; var clone = this.createElement(node.namespaceURI, node.localName, node.attributes); var newNode = new StackItem(node.namespaceURI, node.localName, node.attributes, clone); this.activeFormattingElements[this.activeFormattingElements.indexOf(node)] = newNode; this.openElements.elements[this.openElements.elements.indexOf(node)] = newNode; node = newNode; this.detachFromParent(lastNode.node); this.attachNode(lastNode.node, node.node); lastNode = node; } this.detachFromParent(lastNode.node); if (commonAncestor.isFosterParenting()) { this.insertIntoFosterParent(lastNode.node); } else { this.attachNode(lastNode.node, commonAncestor.node); } var clone = this.createElement("http://www.w3.org/1999/xhtml", formattingElement.localName, formattingElement.attributes); var formattingClone = new StackItem(formattingElement.namespaceURI, formattingElement.localName, formattingElement.attributes, clone); this.reparentChildren(furthestBlock.node, clone); this.attachNode(clone, furthestBlock.node); this.removeElementFromActiveFormattingElements(formattingElement); this.activeFormattingElements.splice(Math.min(bookmark, this.activeFormattingElements.length), 0, formattingClone); this.openElements.remove(formattingElement); this.openElements.elements.splice(this.openElements.elements.indexOf(furthestBlock) + 1, 0, formattingClone); } return true; }; TreeBuilder.prototype.start = function() { throw "Not mplemented"; }; TreeBuilder.prototype.startTokenization = function(tokenizer) { this.tokenizer = tokenizer; this.compatMode = "no quirks"; this.originalInsertionMode = "initial"; this.framesetOk = true; this.openElements = new ElementStack(); this.activeFormattingElements = []; this.start(); if (this.context) { switch(this.context) { case 'title': case 'textarea': this.tokenizer.setState(Tokenizer.RCDATA); break; case 'style': case 'xmp': case 'iframe': case 'noembed': case 'noframes': this.tokenizer.setState(Tokenizer.RAWTEXT); break; case 'script': this.tokenizer.setState(Tokenizer.SCRIPT_DATA); break; case 'noscript': if (this.scriptingEnabled) this.tokenizer.setState(Tokenizer.RAWTEXT); break; case 'plaintext': this.tokenizer.setState(Tokenizer.PLAINTEXT); break; } this.insertHtmlElement(); this.resetInsertionMode(); } else { this.setInsertionMode('initial'); } }; TreeBuilder.prototype.processToken = function(token) { this.selfClosingFlagAcknowledged = false; var currentNode = this.openElements.top || null; var insertionMode; if (!currentNode || !currentNode.isForeign() || (currentNode.isMathMLTextIntegrationPoint() && ((token.type == 'StartTag' && !(token.name in {mglyph:0, malignmark:0})) || (token.type === 'Characters')) ) || (currentNode.namespaceURI == "http://www.w3.org/1998/Math/MathML" && currentNode.localName == 'annotation-xml' && token.type == 'StartTag' && token.name == 'svg' ) || (currentNode.isHtmlIntegrationPoint() && token.type in {StartTag:0, Characters:0} ) || token.type == 'EOF' ) { insertionMode = this.insertionMode; } else { insertionMode = this.insertionModes.inForeignContent; } switch(token.type) { case 'Characters': var buffer = new CharacterBuffer(token.data); insertionMode.processCharacters(buffer); break; case 'Comment': insertionMode.processComment(token.data); break; case 'StartTag': insertionMode.processStartTag(token.name, token.data, token.selfClosing); break; case 'EndTag': insertionMode.processEndTag(token.name); break; case 'Doctype': insertionMode.processDoctype(token.name, token.publicId, token.systemId, token.forceQuirks); break; case 'EOF': insertionMode.processEOF(); break; } }; TreeBuilder.prototype.isCdataSectionAllowed = function() { return this.openElements.length > 0 && this.currentStackItem().isForeign(); }; TreeBuilder.prototype.isSelfClosingFlagAcknowledged = function() { return this.selfClosingFlagAcknowledged; }; TreeBuilder.prototype.createElement = function(namespaceURI, localName, attributes) { throw new Error("Not implemented"); }; TreeBuilder.prototype.attachNode = function(child, parent) { throw new Error("Not implemented"); }; TreeBuilder.prototype.attachNodeToFosterParent = function(child, table, stackParent) { throw new Error("Not implemented"); }; TreeBuilder.prototype.detachFromParent = function(node) { throw new Error("Not implemented"); }; TreeBuilder.prototype.addAttributesToElement = function(element, attributes) { throw new Error("Not implemented"); }; TreeBuilder.prototype.insertHtmlElement = function(attributes) { var root = this.createElement("http://www.w3.org/1999/xhtml", 'html', attributes); this.attachNode(root, this.document); this.openElements.pushHtmlElement(new StackItem("http://www.w3.org/1999/xhtml", 'html', attributes, root)); return root; }; TreeBuilder.prototype.insertHeadElement = function(attributes) { var element = this.createElement("http://www.w3.org/1999/xhtml", "head", attributes); this.head = new StackItem("http://www.w3.org/1999/xhtml", "head", attributes, element); this.attachNode(element, this.openElements.top.node); this.openElements.pushHeadElement(this.head); return element; }; TreeBuilder.prototype.insertBodyElement = function(attributes) { var element = this.createElement("http://www.w3.org/1999/xhtml", "body", attributes); this.attachNode(element, this.openElements.top.node); this.openElements.pushBodyElement(new StackItem("http://www.w3.org/1999/xhtml", "body", attributes, element)); return element; }; TreeBuilder.prototype.insertIntoFosterParent = function(node) { var tableIndex = this.openElements.findIndex('table'); var tableElement = this.openElements.item(tableIndex).node; if (tableIndex === 0) return this.attachNode(node, tableElement); this.attachNodeToFosterParent(node, tableElement, this.openElements.item(tableIndex - 1).node); }; TreeBuilder.prototype.insertElement = function(name, attributes, namespaceURI, selfClosing) { if (!namespaceURI) namespaceURI = "http://www.w3.org/1999/xhtml"; var element = this.createElement(namespaceURI, name, attributes); if (this.shouldFosterParent()) this.insertIntoFosterParent(element); else this.attachNode(element, this.openElements.top.node); if (!selfClosing) this.openElements.push(new StackItem(namespaceURI, name, attributes, element)); }; TreeBuilder.prototype.insertFormattingElement = function(name, attributes) { this.insertElement(name, attributes, "http://www.w3.org/1999/xhtml"); this.appendElementToActiveFormattingElements(this.currentStackItem()); }; TreeBuilder.prototype.insertSelfClosingElement = function(name, attributes) { this.selfClosingFlagAcknowledged = true; this.insertElement(name, attributes, "http://www.w3.org/1999/xhtml", true); }; TreeBuilder.prototype.insertForeignElement = function(name, attributes, namespaceURI, selfClosing) { if (selfClosing) this.selfClosingFlagAcknowledged = true; this.insertElement(name, attributes, namespaceURI, selfClosing); }; TreeBuilder.prototype.insertComment = function(data, parent) { throw new Error("Not implemented"); }; TreeBuilder.prototype.insertDoctype = function(name, publicId, systemId) { throw new Error("Not implemented"); }; TreeBuilder.prototype.insertText = function(data) { throw new Error("Not implemented"); }; TreeBuilder.prototype.currentStackItem = function() { return this.openElements.top; }; TreeBuilder.prototype.popElement = function() { return this.openElements.pop(); }; TreeBuilder.prototype.shouldFosterParent = function() { return this.redirectAttachToFosterParent && this.currentStackItem().isFosterParenting(); }; TreeBuilder.prototype.generateImpliedEndTags = function(exclude) { var name = this.openElements.top.localName; if (['dd', 'dt', 'li', 'option', 'optgroup', 'p', 'rp', 'rt'].indexOf(name) != -1 && name != exclude) { this.popElement(); this.generateImpliedEndTags(exclude); } }; TreeBuilder.prototype.reconstructActiveFormattingElements = function() { if (this.activeFormattingElements.length === 0) return; var i = this.activeFormattingElements.length - 1; var entry = this.activeFormattingElements[i]; if (entry == Marker || this.openElements.contains(entry)) return; while (entry != Marker && !this.openElements.contains(entry)) { i -= 1; entry = this.activeFormattingElements[i]; if (!entry) break; } while (true) { i += 1; entry = this.activeFormattingElements[i]; this.insertElement(entry.localName, entry.attributes); var element = this.currentStackItem(); this.activeFormattingElements[i] = element; if (element == this.activeFormattingElements[this.activeFormattingElements.length -1]) break; } }; TreeBuilder.prototype.ensureNoahsArkCondition = function(item) { var kNoahsArkCapacity = 3; if (this.activeFormattingElements.length < kNoahsArkCapacity) return; var candidates = []; var newItemAttributeCount = item.attributes.length; for (var i = this.activeFormattingElements.length - 1; i >= 0; i--) { var candidate = this.activeFormattingElements[i]; if (candidate === Marker) break; if (item.localName !== candidate.localName || item.namespaceURI !== candidate.namespaceURI) continue; if (candidate.attributes.length != newItemAttributeCount) continue; candidates.push(candidate); } if (candidates.length < kNoahsArkCapacity) return; var remainingCandidates = []; var attributes = item.attributes; for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; for (var j = 0; j < candidates.length; j++) { var candidate = candidates[j]; var candidateAttribute = getAttribute(candidate, attribute.nodeName); if (candidateAttribute && candidateAttribute.nodeValue === attribute.nodeValue) remainingCandidates.push(candidate); } if (remainingCandidates.length < kNoahsArkCapacity) return; candidates = remainingCandidates; remainingCandidates = []; } for (var i = kNoahsArkCapacity - 1; i < candidates.length; i++) this.removeElementFromActiveFormattingElements(candidates[i]); }; TreeBuilder.prototype.appendElementToActiveFormattingElements = function(item) { this.ensureNoahsArkCondition(item); this.activeFormattingElements.push(item); }; TreeBuilder.prototype.removeElementFromActiveFormattingElements = function(item) { var index = this.activeFormattingElements.indexOf(item); if (index >= 0) this.activeFormattingElements.splice(index, 1); }; TreeBuilder.prototype.elementInActiveFormattingElements = function(name) { var els = this.activeFormattingElements; for (var i = els.length - 1; i >= 0; i--) { if (els[i] == Marker) break; if (els[i].localName == name) return els[i]; } return false; }; TreeBuilder.prototype.clearActiveFormattingElements = function() { while (!(this.activeFormattingElements.length === 0 || this.activeFormattingElements.pop() == Marker)); }; TreeBuilder.prototype.reparentChildren = function(oldParent, newParent) { throw new Error("Not implemented"); }; TreeBuilder.prototype.setFragmentContext = function(context) { this.context = context; }; TreeBuilder.prototype.parseError = function(code, args) { if (!this.errorHandler) return; var message = formatMessage(messages[code], args); this.errorHandler.error(message, this.tokenizer._inputStream.location(), code); }; TreeBuilder.prototype.resetInsertionMode = function() { var last = false; var node = null; for (var i = this.openElements.length - 1; i >= 0; i--) { node = this.openElements.item(i); if (i === 0) { assert.ok(this.context); last = true; node = new StackItem("http://www.w3.org/1999/xhtml", this.context, [], null); } if (node.namespaceURI === "http://www.w3.org/1999/xhtml") { if (node.localName === 'select') return this.setInsertionMode('inSelect'); if (node.localName === 'td' || node.localName === 'th') return this.setInsertionMode('inCell'); if (node.localName === 'tr') return this.setInsertionMode('inRow'); if (node.localName === 'tbody' || node.localName === 'thead' || node.localName === 'tfoot') return this.setInsertionMode('inTableBody'); if (node.localName === 'caption') return this.setInsertionMode('inCaption'); if (node.localName === 'colgroup') return this.setInsertionMode('inColumnGroup'); if (node.localName === 'table') return this.setInsertionMode('inTable'); if (node.localName === 'head' && !last) return this.setInsertionMode('inHead'); if (node.localName === 'body') return this.setInsertionMode('inBody'); if (node.localName === 'frameset') return this.setInsertionMode('inFrameset'); if (node.localName === 'html') if (!this.openElements.headElement) return this.setInsertionMode('beforeHead'); else return this.setInsertionMode('afterHead'); } if (last) return this.setInsertionMode('inBody'); } }; TreeBuilder.prototype.processGenericRCDATAStartTag = function(name, attributes) { this.insertElement(name, attributes); this.tokenizer.setState(Tokenizer.RCDATA); this.originalInsertionMode = this.insertionModeName; this.setInsertionMode('text'); }; TreeBuilder.prototype.processGenericRawTextStartTag = function(name, attributes) { this.insertElement(name, attributes); this.tokenizer.setState(Tokenizer.RAWTEXT); this.originalInsertionMode = this.insertionModeName; this.setInsertionMode('text'); }; TreeBuilder.prototype.adjustMathMLAttributes = function(attributes) { attributes.forEach(function(a) { a.namespaceURI = "http://www.w3.org/1998/Math/MathML"; if (constants.MATHMLAttributeMap[a.nodeName]) a.nodeName = constants.MATHMLAttributeMap[a.nodeName]; }); return attributes; }; TreeBuilder.prototype.adjustSVGTagNameCase = function(name) { return constants.SVGTagMap[name] || name; }; TreeBuilder.prototype.adjustSVGAttributes = function(attributes) { attributes.forEach(function(a) { a.namespaceURI = "http://www.w3.org/2000/svg"; if (constants.SVGAttributeMap[a.nodeName]) a.nodeName = constants.SVGAttributeMap[a.nodeName]; }); return attributes; }; TreeBuilder.prototype.adjustForeignAttributes = function(attributes) { for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; var adjusted = constants.ForeignAttributeMap[attribute.nodeName]; if (adjusted) { attribute.nodeName = adjusted.localName; attribute.prefix = adjusted.prefix; attribute.namespaceURI = adjusted.namespaceURI; } } return attributes; }; function formatMessage(format, args) { return format.replace(new RegExp('{[0-9a-z-]+}', 'gi'), function(match) { return args[match.slice(1, -1)] || match; }); } exports.TreeBuilder = TreeBuilder; }, {"./ElementStack":1,"./StackItem":4,"./Tokenizer":5,"./constants":7,"./messages.json":8,"assert":13,"events":16}], 7:[function(_dereq_,module,exports){ exports.SVGTagMap = { "altglyph": "altGlyph", "altglyphdef": "altGlyphDef", "altglyphitem": "altGlyphItem", "animatecolor": "animateColor", "animatemotion": "animateMotion", "animatetransform": "animateTransform", "clippath": "clipPath", "feblend": "feBlend", "fecolormatrix": "feColorMatrix", "fecomponenttransfer": "feComponentTransfer", "fecomposite": "feComposite", "feconvolvematrix": "feConvolveMatrix", "fediffuselighting": "feDiffuseLighting", "fedisplacementmap": "feDisplacementMap", "fedistantlight": "feDistantLight", "feflood": "feFlood", "fefunca": "feFuncA", "fefuncb": "feFuncB", "fefuncg": "feFuncG", "fefuncr": "feFuncR", "fegaussianblur": "feGaussianBlur", "feimage": "feImage", "femerge": "feMerge", "femergenode": "feMergeNode", "femorphology": "feMorphology", "feoffset": "feOffset", "fepointlight": "fePointLight", "fespecularlighting": "feSpecularLighting", "fespotlight": "feSpotLight", "fetile": "feTile", "feturbulence": "feTurbulence", "foreignobject": "foreignObject", "glyphref": "glyphRef", "lineargradient": "linearGradient", "radialgradient": "radialGradient", "textpath": "textPath" }; exports.MATHMLAttributeMap = { definitionurl: 'definitionURL' }; exports.SVGAttributeMap = { attributename: 'attributeName', attributetype: 'attributeType', basefrequency: 'baseFrequency', baseprofile: 'baseProfile', calcmode: 'calcMode', clippathunits: 'clipPathUnits', contentscripttype: 'contentScriptType', contentstyletype: 'contentStyleType', diffuseconstant: 'diffuseConstant', edgemode: 'edgeMode', externalresourcesrequired: 'externalResourcesRequired', filterres: 'filterRes', filterunits: 'filterUnits', glyphref: 'glyphRef', gradienttransform: 'gradientTransform', gradientunits: 'gradientUnits', kernelmatrix: 'kernelMatrix', kernelunitlength: 'kernelUnitLength', keypoints: 'keyPoints', keysplines: 'keySplines', keytimes: 'keyTimes', lengthadjust: 'lengthAdjust', limitingconeangle: 'limitingConeAngle', markerheight: 'markerHeight', markerunits: 'markerUnits', markerwidth: 'markerWidth', maskcontentunits: 'maskContentUnits', maskunits: 'maskUnits', numoctaves: 'numOctaves', pathlength: 'pathLength', patterncontentunits: 'patternContentUnits', patterntransform: 'patternTransform', patternunits: 'patternUnits', pointsatx: 'pointsAtX', pointsaty: 'pointsAtY', pointsatz: 'pointsAtZ', preservealpha: 'preserveAlpha', preserveaspectratio: 'preserveAspectRatio', primitiveunits: 'primitiveUnits', refx: 'refX', refy: 'refY', repeatcount: 'repeatCount', repeatdur: 'repeatDur', requiredextensions: 'requiredExtensions', requiredfeatures: 'requiredFeatures', specularconstant: 'specularConstant', specularexponent: 'specularExponent', spreadmethod: 'spreadMethod', startoffset: 'startOffset', stddeviation: 'stdDeviation', stitchtiles: 'stitchTiles', surfacescale: 'surfaceScale', systemlanguage: 'systemLanguage', tablevalues: 'tableValues', targetx: 'targetX', targety: 'targetY', textlength: 'textLength', viewbox: 'viewBox', viewtarget: 'viewTarget', xchannelselector: 'xChannelSelector', ychannelselector: 'yChannelSelector', zoomandpan: 'zoomAndPan' }; exports.ForeignAttributeMap = { "xlink:actuate": {prefix: "xlink", localName: "actuate", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:arcrole": {prefix: "xlink", localName: "arcrole", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:href": {prefix: "xlink", localName: "href", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:role": {prefix: "xlink", localName: "role", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:show": {prefix: "xlink", localName: "show", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:title": {prefix: "xlink", localName: "title", namespaceURI: "http://www.w3.org/1999/xlink"}, "xlink:type": {prefix: "xlink", localName: "title", namespaceURI: "http://www.w3.org/1999/xlink"}, "xml:base": {prefix: "xml", localName: "base", namespaceURI: "http://www.w3.org/XML/1998/namespace"}, "xml:lang": {prefix: "xml", localName: "lang", namespaceURI: "http://www.w3.org/XML/1998/namespace"}, "xml:space": {prefix: "xml", localName: "space", namespaceURI: "http://www.w3.org/XML/1998/namespace"}, "xmlns": {prefix: null, localName: "xmlns", namespaceURI: "http://www.w3.org/2000/xmlns/"}, "xmlns:xlink": {prefix: "xmlns", localName: "xlink", namespaceURI: "http://www.w3.org/2000/xmlns/"}, }; }, {}], 8:[function(_dereq_,module,exports){ module.exports={ "null-character": "Null character in input stream, replaced with U+FFFD.", "invalid-codepoint": "Invalid codepoint in stream", "incorrectly-placed-solidus": "Solidus (/) incorrectly placed in tag.", "incorrect-cr-newline-entity": "Incorrect CR newline entity, replaced with LF.", "illegal-windows-1252-entity": "Entity used with illegal number (windows-1252 reference).", "cant-convert-numeric-entity": "Numeric entity couldn't be converted to character (codepoint U+{charAsInt}).", "invalid-numeric-entity-replaced": "Numeric entity represents an illegal codepoint. Expanded to the C1 controls range.", "numeric-entity-without-semicolon": "Numeric entity didn't end with ';'.", "expected-numeric-entity-but-got-eof": "Numeric entity expected. Got end of file instead.", "expected-numeric-entity": "Numeric entity expected but none found.", "named-entity-without-semicolon": "Named entity didn't end with ';'.", "expected-named-entity": "Named entity expected. Got none.", "attributes-in-end-tag": "End tag contains unexpected attributes.", "self-closing-flag-on-end-tag": "End tag contains unexpected self-closing flag.", "bare-less-than-sign-at-eof": "End of file after <.", "expected-tag-name-but-got-right-bracket": "Expected tag name. Got '>' instead.", "expected-tag-name-but-got-question-mark": "Expected tag name. Got '?' instead. (HTML doesn't support processing instructions.)", "expected-tag-name": "Expected tag name. Got something else instead.", "expected-closing-tag-but-got-right-bracket": "Expected closing tag. Got '>' instead. Ignoring '</>'.", "expected-closing-tag-but-got-eof": "Expected closing tag. Unexpected end of file.", "expected-closing-tag-but-got-char": "Expected closing tag. Unexpected character '{data}' found.", "eof-in-tag-name": "Unexpected end of file in the tag name.", "expected-attribute-name-but-got-eof": "Unexpected end of file. Expected attribute name instead.", "eof-in-attribute-name": "Unexpected end of file in attribute name.", "invalid-character-in-attribute-name": "Invalid character in attribute name.", "duplicate-attribute": "Dropped duplicate attribute '{name}' on tag.", "expected-end-of-tag-but-got-eof": "Unexpected end of file. Expected = or end of tag.", "expected-attribute-value-but-got-eof": "Unexpected end of file. Expected attribute value.", "expected-attribute-value-but-got-right-bracket": "Expected attribute value. Got '>' instead.", "unexpected-character-in-unquoted-attribute-value": "Unexpected character in unquoted attribute", "invalid-character-after-attribute-name": "Unexpected character after attribute name.", "unexpected-character-after-attribute-value": "Unexpected character after attribute value.", "eof-in-attribute-value-double-quote": "Unexpected end of file in attribute value (\").", "eof-in-attribute-value-single-quote": "Unexpected end of file in attribute value (').", "eof-in-attribute-value-no-quotes": "Unexpected end of file in attribute value.", "eof-after-attribute-value": "Unexpected end of file after attribute value.", "unexpected-eof-after-solidus-in-tag": "Unexpected end of file in tag. Expected >.", "unexpected-character-after-solidus-in-tag": "Unexpected character after / in tag. Expected >.", "expected-dashes-or-doctype": "Expected '--' or 'DOCTYPE'. Not found.", "unexpected-bang-after-double-dash-in-comment": "Unexpected ! after -- in comment.", "incorrect-comment": "Incorrect comment.", "eof-in-comment": "Unexpected end of file in comment.", "eof-in-comment-end-dash": "Unexpected end of file in comment (-).", "unexpected-dash-after-double-dash-in-comment": "Unexpected '-' after '--' found in comment.", "eof-in-comment-double-dash": "Unexpected end of file in comment (--).", "eof-in-comment-end-bang-state": "Unexpected end of file in comment.", "unexpected-char-in-comment": "Unexpected character in comment found.", "need-space-after-doctype": "No space after literal string 'DOCTYPE'.", "expected-doctype-name-but-got-right-bracket": "Unexpected > character. Expected DOCTYPE name.", "expected-doctype-name-but-got-eof": "Unexpected end of file. Expected DOCTYPE name.", "eof-in-doctype-name": "Unexpected end of file in DOCTYPE name.", "eof-in-doctype": "Unexpected end of file in DOCTYPE.", "expected-space-or-right-bracket-in-doctype": "Expected space or '>'. Got '{data}'.", "unexpected-end-of-doctype": "Unexpected end of DOCTYPE.", "unexpected-char-in-doctype": "Unexpected character in DOCTYPE.", "eof-in-bogus-doctype": "Unexpected end of file in bogus doctype.", "eof-in-innerhtml": "Unexpected EOF in inner html mode.", "unexpected-doctype": "Unexpected DOCTYPE. Ignored.", "non-html-root": "html needs to be the first start tag.", "expected-doctype-but-got-eof": "Unexpected End of file. Expected DOCTYPE.", "unknown-doctype": "Erroneous DOCTYPE. Expected <!DOCTYPE html>.", "quirky-doctype": "Quirky doctype. Expected <!DOCTYPE html>.", "almost-standards-doctype": "Almost standards mode doctype. Expected <!DOCTYPE html>.", "obsolete-doctype": "Obsolete doctype. Expected <!DOCTYPE html>.", "expected-doctype-but-got-chars": "Non-space characters found without seeing a doctype first. Expected e.g. <!DOCTYPE html>.", "expected-doctype-but-got-start-tag": "Start tag seen without seeing a doctype first. Expected e.g. <!DOCTYPE html>.", "expected-doctype-but-got-end-tag": "End tag seen without seeing a doctype first. Expected e.g. <!DOCTYPE html>.", "end-tag-after-implied-root": "Unexpected end tag ({name}) after the (implied) root element.", "expected-named-closing-tag-but-got-eof": "Unexpected end of file. Expected end tag ({name}).", "two-heads-are-not-better-than-one": "Unexpected start tag head in existing head. Ignored.", "unexpected-end-tag": "Unexpected end tag ({name}). Ignored.", "unexpected-implied-end-tag": "End tag {name} implied, but there were open elements.", "unexpected-start-tag-out-of-my-head": "Unexpected start tag ({name}) that can be in head. Moved.", "unexpected-start-tag": "Unexpected start tag ({name}).", "missing-end-tag": "Missing end tag ({name}).", "missing-end-tags": "Missing end tags ({name}).", "unexpected-start-tag-implies-end-tag": "Unexpected start tag ({startName}) implies end tag ({endName}).", "unexpected-start-tag-treated-as": "Unexpected start tag ({originalName}). Treated as {newName}.", "deprecated-tag": "Unexpected start tag {name}. Don't use it!", "unexpected-start-tag-ignored": "Unexpected start tag {name}. Ignored.", "expected-one-end-tag-but-got-another": "Unexpected end tag ({gotName}). Missing end tag ({expectedName}).", "end-tag-too-early": "End tag ({name}) seen too early. Expected other end tag.", "end-tag-too-early-named": "Unexpected end tag ({gotName}). Expected end tag ({expectedName}.", "end-tag-too-early-ignored": "End tag ({name}) seen too early. Ignored.", "adoption-agency-1.1": "End tag ({name}) violates step 1, paragraph 1 of the adoption agency algorithm.", "adoption-agency-1.2": "End tag ({name}) violates step 1, paragraph 2 of the adoption agency algorithm.", "adoption-agency-1.3": "End tag ({name}) violates step 1, paragraph 3 of the adoption agency algorithm.", "adoption-agency-4.4": "End tag ({name}) violates step 4, paragraph 4 of the adoption agency algorithm.", "unexpected-end-tag-treated-as": "Unexpected end tag ({originalName}). Treated as {newName}.", "no-end-tag": "This element ({name}) has no end tag.", "unexpected-implied-end-tag-in-table": "Unexpected implied end tag ({name}) in the table phase.", "unexpected-implied-end-tag-in-table-body": "Unexpected implied end tag ({name}) in the table body phase.", "unexpected-char-implies-table-voodoo": "Unexpected non-space characters in table context caused voodoo mode.", "unexpected-hidden-input-in-table": "Unexpected input with type hidden in table context.", "unexpected-form-in-table": "Unexpected form in table context.", "unexpected-start-tag-implies-table-voodoo": "Unexpected start tag ({name}) in table context caused voodoo mode.", "unexpected-end-tag-implies-table-voodoo": "Unexpected end tag ({name}) in table context caused voodoo mode.", "unexpected-cell-in-table-body": "Unexpected table cell start tag ({name}) in the table body phase.", "unexpected-cell-end-tag": "Got table cell end tag ({name}) while required end tags are missing.", "unexpected-end-tag-in-table-body": "Unexpected end tag ({name}) in the table body phase. Ignored.", "unexpected-implied-end-tag-in-table-row": "Unexpected implied end tag ({name}) in the table row phase.", "unexpected-end-tag-in-table-row": "Unexpected end tag ({name}) in the table row phase. Ignored.", "unexpected-select-in-select": "Unexpected select start tag in the select phase treated as select end tag.", "unexpected-input-in-select": "Unexpected input start tag in the select phase.", "unexpected-start-tag-in-select": "Unexpected start tag token ({name}) in the select phase. Ignored.", "unexpected-end-tag-in-select": "Unexpected end tag ({name}) in the select phase. Ignored.", "unexpected-table-element-start-tag-in-select-in-table": "Unexpected table element start tag ({name}) in the select in table phase.", "unexpected-table-element-end-tag-in-select-in-table": "Unexpected table element end tag ({name}) in the select in table phase.", "unexpected-char-after-body": "Unexpected non-space characters in the after body phase.", "unexpected-start-tag-after-body": "Unexpected start tag token ({name}) in the after body phase.", "unexpected-end-tag-after-body": "Unexpected end tag token ({name}) in the after body phase.", "unexpected-char-in-frameset": "Unepxected characters in the frameset phase. Characters ignored.", "unexpected-start-tag-in-frameset": "Unexpected start tag token ({name}) in the frameset phase. Ignored.", "unexpected-frameset-in-frameset-innerhtml": "Unexpected end tag token (frameset in the frameset phase (innerHTML).", "unexpected-end-tag-in-frameset": "Unexpected end tag token ({name}) in the frameset phase. Ignored.", "unexpected-char-after-frameset": "Unexpected non-space characters in the after frameset phase. Ignored.", "unexpected-start-tag-after-frameset": "Unexpected start tag ({name}) in the after frameset phase. Ignored.", "unexpected-end-tag-after-frameset": "Unexpected end tag ({name}) in the after frameset phase. Ignored.", "expected-eof-but-got-char": "Unexpected non-space characters. Expected end of file.", "expected-eof-but-got-start-tag": "Unexpected start tag ({name}). Expected end of file.", "expected-eof-but-got-end-tag": "Unexpected end tag ({name}). Expected end of file.", "unexpected-end-table-in-caption": "Unexpected end table tag in caption. Generates implied end caption.", "end-html-in-innerhtml": "Unexpected html end tag in inner html mode.", "eof-in-table": "Unexpected end of file. Expected table content.", "eof-in-script": "Unexpected end of file. Expected script content.", "non-void-element-with-trailing-solidus": "Trailing solidus not allowed on element {name}.", "unexpected-html-element-in-foreign-content": "HTML start tag \"{name}\" in a foreign namespace context.", "unexpected-start-tag-in-table": "Unexpected {name}. Expected table content." } }, {}], 9:[function(_dereq_,module,exports){ var SAXTreeBuilder = _dereq_('./SAXTreeBuilder').SAXTreeBuilder; var Tokenizer = _dereq_('../Tokenizer').Tokenizer; var TreeParser = _dereq_('./TreeParser').TreeParser; function SAXParser() { this.contentHandler = null; this._errorHandler = null; this._treeBuilder = new SAXTreeBuilder(); this._tokenizer = new Tokenizer(this._treeBuilder); this._scriptingEnabled = false; } SAXParser.prototype.parse = function(source) { this._tokenizer.tokenize(source); var document = this._treeBuilder.document; if (document) { new TreeParser(this.contentHandler).parse(document); } }; SAXParser.prototype.parseFragment = function(source, context) { this._treeBuilder.setFragmentContext(context); this._tokenizer.tokenize(source); var fragment = this._treeBuilder.getFragment(); if (fragment) { new TreeParser(this.contentHandler).parse(fragment); } }; Object.defineProperty(SAXParser.prototype, 'scriptingEnabled', { get: function() { return this._scriptingEnabled; }, set: function(value) { this._scriptingEnabled = value; this._treeBuilder.scriptingEnabled = value; } }); Object.defineProperty(SAXParser.prototype, 'errorHandler', { get: function() { return this._errorHandler; }, set: function(value) { this._errorHandler = value; this._treeBuilder.errorHandler = value; } }); exports.SAXParser = SAXParser; }, {"../Tokenizer":5,"./SAXTreeBuilder":10,"./TreeParser":11}], 10:[function(_dereq_,module,exports){ var util = _dereq_('util'); var TreeBuilder = _dereq_('../TreeBuilder').TreeBuilder; function SAXTreeBuilder() { TreeBuilder.call(this); } util.inherits(SAXTreeBuilder, TreeBuilder); SAXTreeBuilder.prototype.start = function(tokenizer) { this.document = new Document(this.tokenizer); }; SAXTreeBuilder.prototype.end = function() { this.document.endLocator = this.tokenizer; }; SAXTreeBuilder.prototype.insertDoctype = function(name, publicId, systemId) { var doctype = new DTD(this.tokenizer, name, publicId, systemId); doctype.endLocator = this.tokenizer; this.document.appendChild(doctype); }; SAXTreeBuilder.prototype.createElement = function(namespaceURI, localName, attributes) { var element = new Element(this.tokenizer, namespaceURI, localName, localName, attributes || []); return element; }; SAXTreeBuilder.prototype.insertComment = function(data, parent) { if (!parent) parent = this.currentStackItem(); var comment = new Comment(this.tokenizer, data); parent.appendChild(comment); }; SAXTreeBuilder.prototype.appendCharacters = function(parent, data) { var text = new Characters(this.tokenizer, data); parent.appendChild(text); }; SAXTreeBuilder.prototype.insertText = function(data) { if (this.redirectAttachToFosterParent && this.openElements.top.isFosterParenting()) { var tableIndex = this.openElements.findIndex('table'); var tableItem = this.openElements.item(tableIndex); var table = tableItem.node; if (tableIndex === 0) { return this.appendCharacters(table, data); } var text = new Characters(this.tokenizer, data); var parent = table.parentNode; if (parent) { parent.insertBetween(text, table.previousSibling, table); return; } var stackParent = this.openElements.item(tableIndex - 1).node; stackParent.appendChild(text); return; } this.appendCharacters(this.currentStackItem().node, data); }; SAXTreeBuilder.prototype.attachNode = function(node, parent) { parent.appendChild(node); }; SAXTreeBuilder.prototype.attachNodeToFosterParent = function(child, table, stackParent) { var parent = table.parentNode; if (parent) parent.insertBetween(child, table.previousSibling, table); else stackParent.appendChild(child); }; SAXTreeBuilder.prototype.detachFromParent = function(element) { element.detach(); }; SAXTreeBuilder.prototype.reparentChildren = function(oldParent, newParent) { newParent.appendChildren(oldParent.firstChild); }; SAXTreeBuilder.prototype.getFragment = function() { var fragment = new DocumentFragment(); this.reparentChildren(this.openElements.rootNode, fragment); return fragment; }; function getAttribute(node, name) { for (var i = 0; i < node.attributes.length; i++) { var attribute = node.attributes[i]; if (attribute.nodeName === name) return attribute.nodeValue; } } SAXTreeBuilder.prototype.addAttributesToElement = function(element, attributes) { for (var i = 0; i < attributes.length; i++) { var attribute = attributes[i]; if (!getAttribute(element, attribute.nodeName)) element.attributes.push(attribute); } }; var NodeType = { CDATA: 1, CHARACTERS: 2, COMMENT: 3, DOCUMENT: 4, DOCUMENT_FRAGMENT: 5, DTD: 6, ELEMENT: 7, ENTITY: 8, IGNORABLE_WHITESPACE: 9, PROCESSING_INSTRUCTION: 10, SKIPPED_ENTITY: 11 }; function Node(locator) { if (!locator) { this.columnNumber = -1; this.lineNumber = -1; } else { this.columnNumber = locator.columnNumber; this.lineNumber = locator.lineNumber; } this.parentNode = null; this.nextSibling = null; this.firstChild = null; } Node.prototype.visit = function(treeParser) { throw new Error("Not Implemented"); }; Node.prototype.revisit = function(treeParser) { return; }; Node.prototype.detach = function() { if (this.parentNode !== null) { this.parentNode.removeChild(this); this.parentNode = null; } }; Object.defineProperty(Node.prototype, 'previousSibling', { get: function() { var prev = null; var next = this.parentNode.firstChild; for(;;) { if (this == next) { return prev; } prev = next; next = next.nextSibling; } } }); function ParentNode(locator) { Node.call(this, locator); this.lastChild = null; this._endLocator = null; } ParentNode.prototype = Object.create(Node.prototype); ParentNode.prototype.insertBefore = function(child, sibling) { if (!sibling) { return this.appendChild(child); } child.detach(); child.parentNode = this; if (this.firstChild == sibling) { child.nextSibling = sibling; this.firstChild = child; } else { var prev = this.firstChild; var next = this.firstChild.nextSibling; while (next != sibling) { prev = next; next = next.nextSibling; } prev.nextSibling = child; child.nextSibling = next; } return child; }; ParentNode.prototype.insertBetween = function(child, prev, next) { if (!next) { return this.appendChild(child); } child.detach(); child.parentNode = this; child.nextSibling = next; if (!prev) { firstChild = child; } else { prev.nextSibling = child; } return child; }; ParentNode.prototype.appendChild = function(child) { child.detach(); child.parentNode = this; if (!this.firstChild) { this.firstChild = child; } else { this.lastChild.nextSibling = child; } this.lastChild = child; return child; }; ParentNode.prototype.appendChildren = function(parent) { var child = parent.firstChild; if (!child) { return; } var another = parent; if (!this.firstChild) { this.firstChild = child; } else { this.lastChild.nextSibling = child; } this.lastChild = another.lastChild; do { child.parentNode = this; } while ((child = child.nextSibling)); another.firstChild = null; another.lastChild = null; }; ParentNode.prototype.removeChild = function(node) { if (this.firstChild == node) { this.firstChild = node.nextSibling; if (this.lastChild == node) { this.lastChild = null; } } else { var prev = this.firstChild; var next = this.firstChild.nextSibling; while (next != node) { prev = next; next = next.nextSibling; } prev.nextSibling = node.nextSibling; if (this.lastChild == node) { this.lastChild = prev; } } node.parentNode = null; return node; }; Object.defineProperty(ParentNode.prototype, 'endLocator', { get: function() { return this._endLocator; }, set: function(endLocator) { this._endLocator = { lineNumber: endLocator.lineNumber, columnNumber: endLocator.columnNumber }; } }); function Document (locator) { ParentNode.call(this, locator); this.nodeType = NodeType.DOCUMENT; } Document.prototype = Object.create(ParentNode.prototype); Document.prototype.visit = function(treeParser) { treeParser.startDocument(this); }; Document.prototype.revisit = function(treeParser) { treeParser.endDocument(this.endLocator); }; function DocumentFragment() { ParentNode.call(this, new Locator()); this.nodeType = NodeType.DOCUMENT_FRAGMENT; } DocumentFragment.prototype = Object.create(ParentNode.prototype); DocumentFragment.prototype.visit = function(treeParser) { }; function Element(locator, uri, localName, qName, atts, prefixMappings) { ParentNode.call(this, locator); this.uri = uri; this.localName = localName; this.qName = qName; this.attributes = atts; this.prefixMappings = prefixMappings; this.nodeType = NodeType.ELEMENT; } Element.prototype = Object.create(ParentNode.prototype); Element.prototype.visit = function(treeParser) { if (this.prefixMappings) { for (var key in prefixMappings) { var mapping = prefixMappings[key]; treeParser.startPrefixMapping(mapping.getPrefix(), mapping.getUri(), this); } } treeParser.startElement(this.uri, this.localName, this.qName, this.attributes, this); }; Element.prototype.revisit = function(treeParser) { treeParser.endElement(this.uri, this.localName, this.qName, this.endLocator); if (this.prefixMappings) { for (var key in prefixMappings) { var mapping = prefixMappings[key]; treeParser.endPrefixMapping(mapping.getPrefix(), this.endLocator); } } }; function Characters(locator, data){ Node.call(this, locator); this.data = data; this.nodeType = NodeType.CHARACTERS; } Characters.prototype = Object.create(Node.prototype); Characters.prototype.visit = function (treeParser) { treeParser.characters(this.data, 0, this.data.length, this); }; function IgnorableWhitespace(locator, data) { Node.call(this, locator); this.data = data; this.nodeType = NodeType.IGNORABLE_WHITESPACE; } IgnorableWhitespace.prototype = Object.create(Node.prototype); IgnorableWhitespace.prototype.visit = function(treeParser) { treeParser.ignorableWhitespace(this.data, 0, this.data.length, this); }; function Comment(locator, data) { Node.call(this, locator); this.data = data; this.nodeType = NodeType.COMMENT; } Comment.prototype = Object.create(Node.prototype); Comment.prototype.visit = function(treeParser) { treeParser.comment(this.data, 0, this.data.length, this); }; function CDATA(locator) { ParentNode.call(this, locator); this.nodeType = NodeType.CDATA; } CDATA.prototype = Object.create(ParentNode.prototype); CDATA.prototype.visit = function(treeParser) { treeParser.startCDATA(this); }; CDATA.prototype.revisit = function(treeParser) { treeParser.endCDATA(this.endLocator); }; function Entity(name) { ParentNode.call(this); this.name = name; this.nodeType = NodeType.ENTITY; } Entity.prototype = Object.create(ParentNode.prototype); Entity.prototype.visit = function(treeParser) { treeParser.startEntity(this.name, this); }; Entity.prototype.revisit = function(treeParser) { treeParser.endEntity(this.name); }; function SkippedEntity(name) { Node.call(this); this.name = name; this.nodeType = NodeType.SKIPPED_ENTITY; } SkippedEntity.prototype = Object.create(Node.prototype); SkippedEntity.prototype.visit = function(treeParser) { treeParser.skippedEntity(this.name, this); }; function ProcessingInstruction(target, data) { Node.call(this); this.target = target; this.data = data; } ProcessingInstruction.prototype = Object.create(Node.prototype); ProcessingInstruction.prototype.visit = function(treeParser) { treeParser.processingInstruction(this.target, this.data, this); }; ProcessingInstruction.prototype.getNodeType = function() { return NodeType.PROCESSING_INSTRUCTION; }; function DTD(name, publicIdentifier, systemIdentifier) { ParentNode.call(this); this.name = name; this.publicIdentifier = publicIdentifier; this.systemIdentifier = systemIdentifier; this.nodeType = NodeType.DTD; } DTD.prototype = Object.create(ParentNode.prototype); DTD.prototype.visit = function(treeParser) { treeParser.startDTD(this.name, this.publicIdentifier, this.systemIdentifier, this); }; DTD.prototype.revisit = function(treeParser) { treeParser.endDTD(); }; exports.SAXTreeBuilder = SAXTreeBuilder; }, {"../TreeBuilder":6,"util":20}], 11:[function(_dereq_,module,exports){ function TreeParser(contentHandler, lexicalHandler){ this.contentHandler; this.lexicalHandler; this.locatorDelegate; if (!contentHandler) { throw new IllegalArgumentException("contentHandler was null."); } this.contentHandler = contentHandler; if (!lexicalHandler) { this.lexicalHandler = new NullLexicalHandler(); } else { this.lexicalHandler = lexicalHandler; } } TreeParser.prototype.parse = function(node) { this.contentHandler.documentLocator = this; var current = node; var next; for (;;) { current.visit(this); if (next = current.firstChild) { current = next; continue; } for (;;) { current.revisit(this); if (current == node) { return; } if (next = current.nextSibling) { current = next; break; } current = current.parentNode; } } }; TreeParser.prototype.characters = function(ch, start, length, locator) { this.locatorDelegate = locator; this.contentHandler.characters(ch, start, length); }; TreeParser.prototype.endDocument = function(locator) { this.locatorDelegate = locator; this.contentHandler.endDocument(); }; TreeParser.prototype.endElement = function(uri, localName, qName, locator) { this.locatorDelegate = locator; this.contentHandler.endElement(uri, localName, qName); }; TreeParser.prototype.endPrefixMapping = function(prefix, locator) { this.locatorDelegate = locator; this.contentHandler.endPrefixMapping(prefix); }; TreeParser.prototype.ignorableWhitespace = function(ch, start, length, locator) { this.locatorDelegate = locator; this.contentHandler.ignorableWhitespace(ch, start, length); }; TreeParser.prototype.processingInstruction = function(target, data, locator) { this.locatorDelegate = locator; this.contentHandler.processingInstruction(target, data); }; TreeParser.prototype.skippedEntity = function(name, locator) { this.locatorDelegate = locator; this.contentHandler.skippedEntity(name); }; TreeParser.prototype.startDocument = function(locator) { this.locatorDelegate = locator; this.contentHandler.startDocument(); }; TreeParser.prototype.startElement = function(uri, localName, qName, atts, locator) { this.locatorDelegate = locator; this.contentHandler.startElement(uri, localName, qName, atts); }; TreeParser.prototype.startPrefixMapping = function(prefix, uri, locator) { this.locatorDelegate = locator; this.contentHandler.startPrefixMapping(prefix, uri); }; TreeParser.prototype.comment = function(ch, start, length, locator) { this.locatorDelegate = locator; this.lexicalHandler.comment(ch, start, length); }; TreeParser.prototype.endCDATA = function(locator) { this.locatorDelegate = locator; this.lexicalHandler.endCDATA(); }; TreeParser.prototype.endDTD = function(locator) { this.locatorDelegate = locator; this.lexicalHandler.endDTD(); }; TreeParser.prototype.endEntity = function(name, locator) { this.locatorDelegate = locator; this.lexicalHandler.endEntity(name); }; TreeParser.prototype.startCDATA = function(locator) { this.locatorDelegate = locator; this.lexicalHandler.startCDATA(); }; TreeParser.prototype.startDTD = function(name, publicId, systemId, locator) { this.locatorDelegate = locator; this.lexicalHandler.startDTD(name, publicId, systemId); }; TreeParser.prototype.startEntity = function(name, locator) { this.locatorDelegate = locator; this.lexicalHandler.startEntity(name); }; Object.defineProperty(TreeParser.prototype, 'columnNumber', { get: function() { if (!this.locatorDelegate) return -1; else return this.locatorDelegate.columnNumber; } }); Object.defineProperty(TreeParser.prototype, 'lineNumber', { get: function() { if (!this.locatorDelegate) return -1; else return this.locatorDelegate.lineNumber; } }); function NullLexicalHandler() { } NullLexicalHandler.prototype.comment = function() {}; NullLexicalHandler.prototype.endCDATA = function() {}; NullLexicalHandler.prototype.endDTD = function() {}; NullLexicalHandler.prototype.endEntity = function() {}; NullLexicalHandler.prototype.startCDATA = function() {}; NullLexicalHandler.prototype.startDTD = function() {}; NullLexicalHandler.prototype.startEntity = function() {}; exports.TreeParser = TreeParser; }, {}], 12:[function(_dereq_,module,exports){ module.exports = { "Aacute;": "\u00C1", "Aacute": "\u00C1", "aacute;": "\u00E1", "aacute": "\u00E1", "Abreve;": "\u0102", "abreve;": "\u0103", "ac;": "\u223E", "acd;": "\u223F", "acE;": "\u223E\u0333", "Acirc;": "\u00C2", "Acirc": "\u00C2", "acirc;": "\u00E2", "acirc": "\u00E2", "acute;": "\u00B4", "acute": "\u00B4", "Acy;": "\u0410", "acy;": "\u0430", "AElig;": "\u00C6", "AElig": "\u00C6", "aelig;": "\u00E6", "aelig": "\u00E6", "af;": "\u2061", "Afr;": "\uD835\uDD04", "afr;": "\uD835\uDD1E", "Agrave;": "\u00C0", "Agrave": "\u00C0", "agrave;": "\u00E0", "agrave": "\u00E0", "alefsym;": "\u2135", "aleph;": "\u2135", "Alpha;": "\u0391", "alpha;": "\u03B1", "Amacr;": "\u0100", "amacr;": "\u0101", "amalg;": "\u2A3F", "amp;": "\u0026", "amp": "\u0026", "AMP;": "\u0026", "AMP": "\u0026", "andand;": "\u2A55", "And;": "\u2A53", "and;": "\u2227", "andd;": "\u2A5C", "andslope;": "\u2A58", "andv;": "\u2A5A", "ang;": "\u2220", "ange;": "\u29A4", "angle;": "\u2220", "angmsdaa;": "\u29A8", "angmsdab;": "\u29A9", "angmsdac;": "\u29AA", "angmsdad;": "\u29AB", "angmsdae;": "\u29AC", "angmsdaf;": "\u29AD", "angmsdag;": "\u29AE", "angmsdah;": "\u29AF", "angmsd;": "\u2221", "angrt;": "\u221F", "angrtvb;": "\u22BE", "angrtvbd;": "\u299D", "angsph;": "\u2222", "angst;": "\u00C5", "angzarr;": "\u237C", "Aogon;": "\u0104", "aogon;": "\u0105", "Aopf;": "\uD835\uDD38", "aopf;": "\uD835\uDD52", "apacir;": "\u2A6F", "ap;": "\u2248", "apE;": "\u2A70", "ape;": "\u224A", "apid;": "\u224B", "apos;": "\u0027", "ApplyFunction;": "\u2061", "approx;": "\u2248", "approxeq;": "\u224A", "Aring;": "\u00C5", "Aring": "\u00C5", "aring;": "\u00E5", "aring": "\u00E5", "Ascr;": "\uD835\uDC9C", "ascr;": "\uD835\uDCB6", "Assign;": "\u2254", "ast;": "\u002A", "asymp;": "\u2248", "asympeq;": "\u224D", "Atilde;": "\u00C3", "Atilde": "\u00C3", "atilde;": "\u00E3", "atilde": "\u00E3", "Auml;": "\u00C4", "Auml": "\u00C4", "auml;": "\u00E4", "auml": "\u00E4", "awconint;": "\u2233", "awint;": "\u2A11", "backcong;": "\u224C", "backepsilon;": "\u03F6", "backprime;": "\u2035", "backsim;": "\u223D", "backsimeq;": "\u22CD", "Backslash;": "\u2216", "Barv;": "\u2AE7", "barvee;": "\u22BD", "barwed;": "\u2305", "Barwed;": "\u2306", "barwedge;": "\u2305", "bbrk;": "\u23B5", "bbrktbrk;": "\u23B6", "bcong;": "\u224C", "Bcy;": "\u0411", "bcy;": "\u0431", "bdquo;": "\u201E", "becaus;": "\u2235", "because;": "\u2235", "Because;": "\u2235", "bemptyv;": "\u29B0", "bepsi;": "\u03F6", "bernou;": "\u212C", "Bernoullis;": "\u212C", "Beta;": "\u0392", "beta;": "\u03B2", "beth;": "\u2136", "between;": "\u226C", "Bfr;": "\uD835\uDD05", "bfr;": "\uD835\uDD1F", "bigcap;": "\u22C2", "bigcirc;": "\u25EF", "bigcup;": "\u22C3", "bigodot;": "\u2A00", "bigoplus;": "\u2A01", "bigotimes;": "\u2A02", "bigsqcup;": "\u2A06", "bigstar;": "\u2605", "bigtriangledown;": "\u25BD", "bigtriangleup;": "\u25B3", "biguplus;": "\u2A04", "bigvee;": "\u22C1", "bigwedge;": "\u22C0", "bkarow;": "\u290D", "blacklozenge;": "\u29EB", "blacksquare;": "\u25AA", "blacktriangle;": "\u25B4", "blacktriangledown;": "\u25BE", "blacktriangleleft;": "\u25C2", "blacktriangleright;": "\u25B8", "blank;": "\u2423", "blk12;": "\u2592", "blk14;": "\u2591", "blk34;": "\u2593", "block;": "\u2588", "bne;": "\u003D\u20E5", "bnequiv;": "\u2261\u20E5", "bNot;": "\u2AED", "bnot;": "\u2310", "Bopf;": "\uD835\uDD39", "bopf;": "\uD835\uDD53", "bot;": "\u22A5", "bottom;": "\u22A5", "bowtie;": "\u22C8", "boxbox;": "\u29C9", "boxdl;": "\u2510", "boxdL;": "\u2555", "boxDl;": "\u2556", "boxDL;": "\u2557", "boxdr;": "\u250C", "boxdR;": "\u2552", "boxDr;": "\u2553", "boxDR;": "\u2554", "boxh;": "\u2500", "boxH;": "\u2550", "boxhd;": "\u252C", "boxHd;": "\u2564", "boxhD;": "\u2565", "boxHD;": "\u2566", "boxhu;": "\u2534", "boxHu;": "\u2567", "boxhU;": "\u2568", "boxHU;": "\u2569", "boxminus;": "\u229F", "boxplus;": "\u229E", "boxtimes;": "\u22A0", "boxul;": "\u2518", "boxuL;": "\u255B", "boxUl;": "\u255C", "boxUL;": "\u255D", "boxur;": "\u2514", "boxuR;": "\u2558", "boxUr;": "\u2559", "boxUR;": "\u255A", "boxv;": "\u2502", "boxV;": "\u2551", "boxvh;": "\u253C", "boxvH;": "\u256A", "boxVh;": "\u256B", "boxVH;": "\u256C", "boxvl;": "\u2524", "boxvL;": "\u2561", "boxVl;": "\u2562", "boxVL;": "\u2563", "boxvr;": "\u251C", "boxvR;": "\u255E", "boxVr;": "\u255F", "boxVR;": "\u2560", "bprime;": "\u2035", "breve;": "\u02D8", "Breve;": "\u02D8", "brvbar;": "\u00A6", "brvbar": "\u00A6", "bscr;": "\uD835\uDCB7", "Bscr;": "\u212C", "bsemi;": "\u204F", "bsim;": "\u223D", "bsime;": "\u22CD", "bsolb;": "\u29C5", "bsol;": "\u005C", "bsolhsub;": "\u27C8", "bull;": "\u2022", "bullet;": "\u2022", "bump;": "\u224E", "bumpE;": "\u2AAE", "bumpe;": "\u224F", "Bumpeq;": "\u224E", "bumpeq;": "\u224F", "Cacute;": "\u0106", "cacute;": "\u0107", "capand;": "\u2A44", "capbrcup;": "\u2A49", "capcap;": "\u2A4B", "cap;": "\u2229", "Cap;": "\u22D2", "capcup;": "\u2A47", "capdot;": "\u2A40", "CapitalDifferentialD;": "\u2145", "caps;": "\u2229\uFE00", "caret;": "\u2041", "caron;": "\u02C7", "Cayleys;": "\u212D", "ccaps;": "\u2A4D", "Ccaron;": "\u010C", "ccaron;": "\u010D", "Ccedil;": "\u00C7", "Ccedil": "\u00C7", "ccedil;": "\u00E7", "ccedil": "\u00E7", "Ccirc;": "\u0108", "ccirc;": "\u0109", "Cconint;": "\u2230", "ccups;": "\u2A4C", "ccupssm;": "\u2A50", "Cdot;": "\u010A", "cdot;": "\u010B", "cedil;": "\u00B8", "cedil": "\u00B8", "Cedilla;": "\u00B8", "cemptyv;": "\u29B2", "cent;": "\u00A2", "cent": "\u00A2", "centerdot;": "\u00B7", "CenterDot;": "\u00B7", "cfr;": "\uD835\uDD20", "Cfr;": "\u212D", "CHcy;": "\u0427", "chcy;": "\u0447", "check;": "\u2713", "checkmark;": "\u2713", "Chi;": "\u03A7", "chi;": "\u03C7", "circ;": "\u02C6", "circeq;": "\u2257", "circlearrowleft;": "\u21BA", "circlearrowright;": "\u21BB", "circledast;": "\u229B", "circledcirc;": "\u229A", "circleddash;": "\u229D", "CircleDot;": "\u2299", "circledR;": "\u00AE", "circledS;": "\u24C8", "CircleMinus;": "\u2296", "CirclePlus;": "\u2295", "CircleTimes;": "\u2297", "cir;": "\u25CB", "cirE;": "\u29C3", "cire;": "\u2257", "cirfnint;": "\u2A10", "cirmid;": "\u2AEF", "cirscir;": "\u29C2", "ClockwiseContourIntegral;": "\u2232", "CloseCurlyDoubleQuote;": "\u201D", "CloseCurlyQuote;": "\u2019", "clubs;": "\u2663", "clubsuit;": "\u2663", "colon;": "\u003A", "Colon;": "\u2237", "Colone;": "\u2A74", "colone;": "\u2254", "coloneq;": "\u2254", "comma;": "\u002C", "commat;": "\u0040", "comp;": "\u2201", "compfn;": "\u2218", "complement;": "\u2201", "complexes;": "\u2102", "cong;": "\u2245", "congdot;": "\u2A6D", "Congruent;": "\u2261", "conint;": "\u222E", "Conint;": "\u222F", "ContourIntegral;": "\u222E", "copf;": "\uD835\uDD54", "Copf;": "\u2102", "coprod;": "\u2210", "Coproduct;": "\u2210", "copy;": "\u00A9", "copy": "\u00A9", "COPY;": "\u00A9", "COPY": "\u00A9", "copysr;": "\u2117", "CounterClockwiseContourIntegral;": "\u2233", "crarr;": "\u21B5", "cross;": "\u2717", "Cross;": "\u2A2F", "Cscr;": "\uD835\uDC9E", "cscr;": "\uD835\uDCB8", "csub;": "\u2ACF", "csube;": "\u2AD1", "csup;": "\u2AD0", "csupe;": "\u2AD2", "ctdot;": "\u22EF", "cudarrl;": "\u2938", "cudarrr;": "\u2935", "cuepr;": "\u22DE", "cuesc;": "\u22DF", "cularr;": "\u21B6", "cularrp;": "\u293D", "cupbrcap;": "\u2A48", "cupcap;": "\u2A46", "CupCap;": "\u224D", "cup;": "\u222A", "Cup;": "\u22D3", "cupcup;": "\u2A4A", "cupdot;": "\u228D", "cupor;": "\u2A45", "cups;": "\u222A\uFE00", "curarr;": "\u21B7", "curarrm;": "\u293C", "curlyeqprec;": "\u22DE", "curlyeqsucc;": "\u22DF", "curlyvee;": "\u22CE", "curlywedge;": "\u22CF", "curren;": "\u00A4", "curren": "\u00A4", "curvearrowleft;": "\u21B6", "curvearrowright;": "\u21B7", "cuvee;": "\u22CE", "cuwed;": "\u22CF", "cwconint;": "\u2232", "cwint;": "\u2231", "cylcty;": "\u232D", "dagger;": "\u2020", "Dagger;": "\u2021", "daleth;": "\u2138", "darr;": "\u2193", "Darr;": "\u21A1", "dArr;": "\u21D3", "dash;": "\u2010", "Dashv;": "\u2AE4", "dashv;": "\u22A3", "dbkarow;": "\u290F", "dblac;": "\u02DD", "Dcaron;": "\u010E", "dcaron;": "\u010F", "Dcy;": "\u0414", "dcy;": "\u0434", "ddagger;": "\u2021", "ddarr;": "\u21CA", "DD;": "\u2145", "dd;": "\u2146", "DDotrahd;": "\u2911", "ddotseq;": "\u2A77", "deg;": "\u00B0", "deg": "\u00B0", "Del;": "\u2207", "Delta;": "\u0394", "delta;": "\u03B4", "demptyv;": "\u29B1", "dfisht;": "\u297F", "Dfr;": "\uD835\uDD07", "dfr;": "\uD835\uDD21", "dHar;": "\u2965", "dharl;": "\u21C3", "dharr;": "\u21C2", "DiacriticalAcute;": "\u00B4", "DiacriticalDot;": "\u02D9", "DiacriticalDoubleAcute;": "\u02DD", "DiacriticalGrave;": "\u0060", "DiacriticalTilde;": "\u02DC", "diam;": "\u22C4", "diamond;": "\u22C4", "Diamond;": "\u22C4", "diamondsuit;": "\u2666", "diams;": "\u2666", "die;": "\u00A8", "DifferentialD;": "\u2146", "digamma;": "\u03DD", "disin;": "\u22F2", "div;": "\u00F7", "divide;": "\u00F7", "divide": "\u00F7", "divideontimes;": "\u22C7", "divonx;": "\u22C7", "DJcy;": "\u0402", "djcy;": "\u0452", "dlcorn;": "\u231E", "dlcrop;": "\u230D", "dollar;": "\u0024", "Dopf;": "\uD835\uDD3B", "dopf;": "\uD835\uDD55", "Dot;": "\u00A8", "dot;": "\u02D9", "DotDot;": "\u20DC", "doteq;": "\u2250", "doteqdot;": "\u2251", "DotEqual;": "\u2250", "dotminus;": "\u2238", "dotplus;": "\u2214", "dotsquare;": "\u22A1", "doublebarwedge;": "\u2306", "DoubleContourIntegral;": "\u222F", "DoubleDot;": "\u00A8", "DoubleDownArrow;": "\u21D3", "DoubleLeftArrow;": "\u21D0", "DoubleLeftRightArrow;": "\u21D4", "DoubleLeftTee;": "\u2AE4", "DoubleLongLeftArrow;": "\u27F8", "DoubleLongLeftRightArrow;": "\u27FA", "DoubleLongRightArrow;": "\u27F9", "DoubleRightArrow;": "\u21D2", "DoubleRightTee;": "\u22A8", "DoubleUpArrow;": "\u21D1", "DoubleUpDownArrow;": "\u21D5", "DoubleVerticalBar;": "\u2225", "DownArrowBar;": "\u2913", "downarrow;": "\u2193", "DownArrow;": "\u2193", "Downarrow;": "\u21D3", "DownArrowUpArrow;": "\u21F5", "DownBreve;": "\u0311", "downdownarrows;": "\u21CA", "downharpoonleft;": "\u21C3", "downharpoonright;": "\u21C2", "DownLeftRightVector;": "\u2950", "DownLeftTeeVector;": "\u295E", "DownLeftVectorBar;": "\u2956", "DownLeftVector;": "\u21BD", "DownRightTeeVector;": "\u295F", "DownRightVectorBar;": "\u2957", "DownRightVector;": "\u21C1", "DownTeeArrow;": "\u21A7", "DownTee;": "\u22A4", "drbkarow;": "\u2910", "drcorn;": "\u231F", "drcrop;": "\u230C", "Dscr;": "\uD835\uDC9F", "dscr;": "\uD835\uDCB9", "DScy;": "\u0405", "dscy;": "\u0455", "dsol;": "\u29F6", "Dstrok;": "\u0110", "dstrok;": "\u0111", "dtdot;": "\u22F1", "dtri;": "\u25BF", "dtrif;": "\u25BE", "duarr;": "\u21F5", "duhar;": "\u296F", "dwangle;": "\u29A6", "DZcy;": "\u040F", "dzcy;": "\u045F", "dzigrarr;": "\u27FF", "Eacute;": "\u00C9", "Eacute": "\u00C9", "eacute;": "\u00E9", "eacute": "\u00E9", "easter;": "\u2A6E", "Ecaron;": "\u011A", "ecaron;": "\u011B", "Ecirc;": "\u00CA", "Ecirc": "\u00CA", "ecirc;": "\u00EA", "ecirc": "\u00EA", "ecir;": "\u2256", "ecolon;": "\u2255", "Ecy;": "\u042D", "ecy;": "\u044D", "eDDot;": "\u2A77", "Edot;": "\u0116", "edot;": "\u0117", "eDot;": "\u2251", "ee;": "\u2147", "efDot;": "\u2252", "Efr;": "\uD835\uDD08", "efr;": "\uD835\uDD22", "eg;": "\u2A9A", "Egrave;": "\u00C8", "Egrave": "\u00C8", "egrave;": "\u00E8", "egrave": "\u00E8", "egs;": "\u2A96", "egsdot;": "\u2A98", "el;": "\u2A99", "Element;": "\u2208", "elinters;": "\u23E7", "ell;": "\u2113", "els;": "\u2A95", "elsdot;": "\u2A97", "Emacr;": "\u0112", "emacr;": "\u0113", "empty;": "\u2205", "emptyset;": "\u2205", "EmptySmallSquare;": "\u25FB", "emptyv;": "\u2205", "EmptyVerySmallSquare;": "\u25AB", "emsp13;": "\u2004", "emsp14;": "\u2005", "emsp;": "\u2003", "ENG;": "\u014A", "eng;": "\u014B", "ensp;": "\u2002", "Eogon;": "\u0118", "eogon;": "\u0119", "Eopf;": "\uD835\uDD3C", "eopf;": "\uD835\uDD56", "epar;": "\u22D5", "eparsl;": "\u29E3", "eplus;": "\u2A71", "epsi;": "\u03B5", "Epsilon;": "\u0395", "epsilon;": "\u03B5", "epsiv;": "\u03F5", "eqcirc;": "\u2256", "eqcolon;": "\u2255", "eqsim;": "\u2242", "eqslantgtr;": "\u2A96", "eqslantless;": "\u2A95", "Equal;": "\u2A75", "equals;": "\u003D", "EqualTilde;": "\u2242", "equest;": "\u225F", "Equilibrium;": "\u21CC", "equiv;": "\u2261", "equivDD;": "\u2A78", "eqvparsl;": "\u29E5", "erarr;": "\u2971", "erDot;": "\u2253", "escr;": "\u212F", "Escr;": "\u2130", "esdot;": "\u2250", "Esim;": "\u2A73", "esim;": "\u2242", "Eta;": "\u0397", "eta;": "\u03B7", "ETH;": "\u00D0", "ETH": "\u00D0", "eth;": "\u00F0", "eth": "\u00F0", "Euml;": "\u00CB", "Euml": "\u00CB", "euml;": "\u00EB", "euml": "\u00EB", "euro;": "\u20AC", "excl;": "\u0021", "exist;": "\u2203", "Exists;": "\u2203", "expectation;": "\u2130", "exponentiale;": "\u2147", "ExponentialE;": "\u2147", "fallingdotseq;": "\u2252", "Fcy;": "\u0424", "fcy;": "\u0444", "female;": "\u2640", "ffilig;": "\uFB03", "fflig;": "\uFB00", "ffllig;": "\uFB04", "Ffr;": "\uD835\uDD09", "ffr;": "\uD835\uDD23", "filig;": "\uFB01", "FilledSmallSquare;": "\u25FC", "FilledVerySmallSquare;": "\u25AA", "fjlig;": "\u0066\u006A", "flat;": "\u266D", "fllig;": "\uFB02", "fltns;": "\u25B1", "fnof;": "\u0192", "Fopf;": "\uD835\uDD3D", "fopf;": "\uD835\uDD57", "forall;": "\u2200", "ForAll;": "\u2200", "fork;": "\u22D4", "forkv;": "\u2AD9", "Fouriertrf;": "\u2131", "fpartint;": "\u2A0D", "frac12;": "\u00BD", "frac12": "\u00BD", "frac13;": "\u2153", "frac14;": "\u00BC", "frac14": "\u00BC", "frac15;": "\u2155", "frac16;": "\u2159", "frac18;": "\u215B", "frac23;": "\u2154", "frac25;": "\u2156", "frac34;": "\u00BE", "frac34": "\u00BE", "frac35;": "\u2157", "frac38;": "\u215C", "frac45;": "\u2158", "frac56;": "\u215A", "frac58;": "\u215D", "frac78;": "\u215E", "frasl;": "\u2044", "frown;": "\u2322", "fscr;": "\uD835\uDCBB", "Fscr;": "\u2131", "gacute;": "\u01F5", "Gamma;": "\u0393", "gamma;": "\u03B3", "Gammad;": "\u03DC", "gammad;": "\u03DD", "gap;": "\u2A86", "Gbreve;": "\u011E", "gbreve;": "\u011F", "Gcedil;": "\u0122", "Gcirc;": "\u011C", "gcirc;": "\u011D", "Gcy;": "\u0413", "gcy;": "\u0433", "Gdot;": "\u0120", "gdot;": "\u0121", "ge;": "\u2265", "gE;": "\u2267", "gEl;": "\u2A8C", "gel;": "\u22DB", "geq;": "\u2265", "geqq;": "\u2267", "geqslant;": "\u2A7E", "gescc;": "\u2AA9", "ges;": "\u2A7E", "gesdot;": "\u2A80", "gesdoto;": "\u2A82", "gesdotol;": "\u2A84", "gesl;": "\u22DB\uFE00", "gesles;": "\u2A94", "Gfr;": "\uD835\uDD0A", "gfr;": "\uD835\uDD24", "gg;": "\u226B", "Gg;": "\u22D9", "ggg;": "\u22D9", "gimel;": "\u2137", "GJcy;": "\u0403", "gjcy;": "\u0453", "gla;": "\u2AA5", "gl;": "\u2277", "glE;": "\u2A92", "glj;": "\u2AA4", "gnap;": "\u2A8A", "gnapprox;": "\u2A8A", "gne;": "\u2A88", "gnE;": "\u2269", "gneq;": "\u2A88", "gneqq;": "\u2269", "gnsim;": "\u22E7", "Gopf;": "\uD835\uDD3E", "gopf;": "\uD835\uDD58", "grave;": "\u0060", "GreaterEqual;": "\u2265", "GreaterEqualLess;": "\u22DB", "GreaterFullEqual;": "\u2267", "GreaterGreater;": "\u2AA2", "GreaterLess;": "\u2277", "GreaterSlantEqual;": "\u2A7E", "GreaterTilde;": "\u2273", "Gscr;": "\uD835\uDCA2", "gscr;": "\u210A", "gsim;": "\u2273", "gsime;": "\u2A8E", "gsiml;": "\u2A90", "gtcc;": "\u2AA7", "gtcir;": "\u2A7A", "gt;": "\u003E", "gt": "\u003E", "GT;": "\u003E", "GT": "\u003E", "Gt;": "\u226B", "gtdot;": "\u22D7", "gtlPar;": "\u2995", "gtquest;": "\u2A7C", "gtrapprox;": "\u2A86", "gtrarr;": "\u2978", "gtrdot;": "\u22D7", "gtreqless;": "\u22DB", "gtreqqless;": "\u2A8C", "gtrless;": "\u2277", "gtrsim;": "\u2273", "gvertneqq;": "\u2269\uFE00", "gvnE;": "\u2269\uFE00", "Hacek;": "\u02C7", "hairsp;": "\u200A", "half;": "\u00BD", "hamilt;": "\u210B", "HARDcy;": "\u042A", "hardcy;": "\u044A", "harrcir;": "\u2948", "harr;": "\u2194", "hArr;": "\u21D4", "harrw;": "\u21AD", "Hat;": "\u005E", "hbar;": "\u210F", "Hcirc;": "\u0124", "hcirc;": "\u0125", "hearts;": "\u2665", "heartsuit;": "\u2665", "hellip;": "\u2026", "hercon;": "\u22B9", "hfr;": "\uD835\uDD25", "Hfr;": "\u210C", "HilbertSpace;": "\u210B", "hksearow;": "\u2925", "hkswarow;": "\u2926", "hoarr;": "\u21FF", "homtht;": "\u223B", "hookleftarrow;": "\u21A9", "hookrightarrow;": "\u21AA", "hopf;": "\uD835\uDD59", "Hopf;": "\u210D", "horbar;": "\u2015", "HorizontalLine;": "\u2500", "hscr;": "\uD835\uDCBD", "Hscr;": "\u210B", "hslash;": "\u210F", "Hstrok;": "\u0126", "hstrok;": "\u0127", "HumpDownHump;": "\u224E", "HumpEqual;": "\u224F", "hybull;": "\u2043", "hyphen;": "\u2010", "Iacute;": "\u00CD", "Iacute": "\u00CD", "iacute;": "\u00ED", "iacute": "\u00ED", "ic;": "\u2063", "Icirc;": "\u00CE", "Icirc": "\u00CE", "icirc;": "\u00EE", "icirc": "\u00EE", "Icy;": "\u0418", "icy;": "\u0438", "Idot;": "\u0130", "IEcy;": "\u0415", "iecy;": "\u0435", "iexcl;": "\u00A1", "iexcl": "\u00A1", "iff;": "\u21D4", "ifr;": "\uD835\uDD26", "Ifr;": "\u2111", "Igrave;": "\u00CC", "Igrave": "\u00CC", "igrave;": "\u00EC", "igrave": "\u00EC", "ii;": "\u2148", "iiiint;": "\u2A0C", "iiint;": "\u222D", "iinfin;": "\u29DC", "iiota;": "\u2129", "IJlig;": "\u0132", "ijlig;": "\u0133", "Imacr;": "\u012A", "imacr;": "\u012B", "image;": "\u2111", "ImaginaryI;": "\u2148", "imagline;": "\u2110", "imagpart;": "\u2111", "imath;": "\u0131", "Im;": "\u2111", "imof;": "\u22B7", "imped;": "\u01B5", "Implies;": "\u21D2", "incare;": "\u2105", "in;": "\u2208", "infin;": "\u221E", "infintie;": "\u29DD", "inodot;": "\u0131", "intcal;": "\u22BA", "int;": "\u222B", "Int;": "\u222C", "integers;": "\u2124", "Integral;": "\u222B", "intercal;": "\u22BA", "Intersection;": "\u22C2", "intlarhk;": "\u2A17", "intprod;": "\u2A3C", "InvisibleComma;": "\u2063", "InvisibleTimes;": "\u2062", "IOcy;": "\u0401", "iocy;": "\u0451", "Iogon;": "\u012E", "iogon;": "\u012F", "Iopf;": "\uD835\uDD40", "iopf;": "\uD835\uDD5A", "Iota;": "\u0399", "iota;": "\u03B9", "iprod;": "\u2A3C", "iquest;": "\u00BF", "iquest": "\u00BF", "iscr;": "\uD835\uDCBE", "Iscr;": "\u2110", "isin;": "\u2208", "isindot;": "\u22F5", "isinE;": "\u22F9", "isins;": "\u22F4", "isinsv;": "\u22F3", "isinv;": "\u2208", "it;": "\u2062", "Itilde;": "\u0128", "itilde;": "\u0129", "Iukcy;": "\u0406", "iukcy;": "\u0456", "Iuml;": "\u00CF", "Iuml": "\u00CF", "iuml;": "\u00EF", "iuml": "\u00EF", "Jcirc;": "\u0134", "jcirc;": "\u0135", "Jcy;": "\u0419", "jcy;": "\u0439", "Jfr;": "\uD835\uDD0D", "jfr;": "\uD835\uDD27", "jmath;": "\u0237", "Jopf;": "\uD835\uDD41", "jopf;": "\uD835\uDD5B", "Jscr;": "\uD835\uDCA5", "jscr;": "\uD835\uDCBF", "Jsercy;": "\u0408", "jsercy;": "\u0458", "Jukcy;": "\u0404", "jukcy;": "\u0454", "Kappa;": "\u039A", "kappa;": "\u03BA", "kappav;": "\u03F0", "Kcedil;": "\u0136", "kcedil;": "\u0137", "Kcy;": "\u041A", "kcy;": "\u043A", "Kfr;": "\uD835\uDD0E", "kfr;": "\uD835\uDD28", "kgreen;": "\u0138", "KHcy;": "\u0425", "khcy;": "\u0445", "KJcy;": "\u040C", "kjcy;": "\u045C", "Kopf;": "\uD835\uDD42", "kopf;": "\uD835\uDD5C", "Kscr;": "\uD835\uDCA6", "kscr;": "\uD835\uDCC0", "lAarr;": "\u21DA", "Lacute;": "\u0139", "lacute;": "\u013A", "laemptyv;": "\u29B4", "lagran;": "\u2112", "Lambda;": "\u039B", "lambda;": "\u03BB", "lang;": "\u27E8", "Lang;": "\u27EA", "langd;": "\u2991", "langle;": "\u27E8", "lap;": "\u2A85", "Laplacetrf;": "\u2112", "laquo;": "\u00AB", "laquo": "\u00AB", "larrb;": "\u21E4", "larrbfs;": "\u291F", "larr;": "\u2190", "Larr;": "\u219E", "lArr;": "\u21D0", "larrfs;": "\u291D", "larrhk;": "\u21A9", "larrlp;": "\u21AB", "larrpl;": "\u2939", "larrsim;": "\u2973", "larrtl;": "\u21A2", "latail;": "\u2919", "lAtail;": "\u291B", "lat;": "\u2AAB", "late;": "\u2AAD", "lates;": "\u2AAD\uFE00", "lbarr;": "\u290C", "lBarr;": "\u290E", "lbbrk;": "\u2772", "lbrace;": "\u007B", "lbrack;": "\u005B", "lbrke;": "\u298B", "lbrksld;": "\u298F", "lbrkslu;": "\u298D", "Lcaron;": "\u013D", "lcaron;": "\u013E", "Lcedil;": "\u013B", "lcedil;": "\u013C", "lceil;": "\u2308", "lcub;": "\u007B", "Lcy;": "\u041B", "lcy;": "\u043B", "ldca;": "\u2936", "ldquo;": "\u201C", "ldquor;": "\u201E", "ldrdhar;": "\u2967", "ldrushar;": "\u294B", "ldsh;": "\u21B2", "le;": "\u2264", "lE;": "\u2266", "LeftAngleBracket;": "\u27E8", "LeftArrowBar;": "\u21E4", "leftarrow;": "\u2190", "LeftArrow;": "\u2190", "Leftarrow;": "\u21D0", "LeftArrowRightArrow;": "\u21C6", "leftarrowtail;": "\u21A2", "LeftCeiling;": "\u2308", "LeftDoubleBracket;": "\u27E6", "LeftDownTeeVector;": "\u2961", "LeftDownVectorBar;": "\u2959", "LeftDownVector;": "\u21C3", "LeftFloor;": "\u230A", "leftharpoondown;": "\u21BD", "leftharpoonup;": "\u21BC", "leftleftarrows;": "\u21C7", "leftrightarrow;": "\u2194", "LeftRightArrow;": "\u2194", "Leftrightarrow;": "\u21D4", "leftrightarrows;": "\u21C6", "leftrightharpoons;": "\u21CB", "leftrightsquigarrow;": "\u21AD", "LeftRightVector;": "\u294E", "LeftTeeArrow;": "\u21A4", "LeftTee;": "\u22A3", "LeftTeeVector;": "\u295A", "leftthreetimes;": "\u22CB", "LeftTriangleBar;": "\u29CF", "LeftTriangle;": "\u22B2", "LeftTriangleEqual;": "\u22B4", "LeftUpDownVector;": "\u2951", "LeftUpTeeVector;": "\u2960", "LeftUpVectorBar;": "\u2958", "LeftUpVector;": "\u21BF", "LeftVectorBar;": "\u2952", "LeftVector;": "\u21BC", "lEg;": "\u2A8B", "leg;": "\u22DA", "leq;": "\u2264", "leqq;": "\u2266", "leqslant;": "\u2A7D", "lescc;": "\u2AA8", "les;": "\u2A7D", "lesdot;": "\u2A7F", "lesdoto;": "\u2A81", "lesdotor;": "\u2A83", "lesg;": "\u22DA\uFE00", "lesges;": "\u2A93", "lessapprox;": "\u2A85", "lessdot;": "\u22D6", "lesseqgtr;": "\u22DA", "lesseqqgtr;": "\u2A8B", "LessEqualGreater;": "\u22DA", "LessFullEqual;": "\u2266", "LessGreater;": "\u2276", "lessgtr;": "\u2276", "LessLess;": "\u2AA1", "lesssim;": "\u2272", "LessSlantEqual;": "\u2A7D", "LessTilde;": "\u2272", "lfisht;": "\u297C", "lfloor;": "\u230A", "Lfr;": "\uD835\uDD0F", "lfr;": "\uD835\uDD29", "lg;": "\u2276", "lgE;": "\u2A91", "lHar;": "\u2962", "lhard;": "\u21BD", "lharu;": "\u21BC", "lharul;": "\u296A", "lhblk;": "\u2584", "LJcy;": "\u0409", "ljcy;": "\u0459", "llarr;": "\u21C7", "ll;": "\u226A", "Ll;": "\u22D8", "llcorner;": "\u231E", "Lleftarrow;": "\u21DA", "llhard;": "\u296B", "lltri;": "\u25FA", "Lmidot;": "\u013F", "lmidot;": "\u0140", "lmoustache;": "\u23B0", "lmoust;": "\u23B0", "lnap;": "\u2A89", "lnapprox;": "\u2A89", "lne;": "\u2A87", "lnE;": "\u2268", "lneq;": "\u2A87", "lneqq;": "\u2268", "lnsim;": "\u22E6", "loang;": "\u27EC", "loarr;": "\u21FD", "lobrk;": "\u27E6", "longleftarrow;": "\u27F5", "LongLeftArrow;": "\u27F5", "Longleftarrow;": "\u27F8", "longleftrightarrow;": "\u27F7", "LongLeftRightArrow;": "\u27F7", "Longleftrightarrow;": "\u27FA", "longmapsto;": "\u27FC", "longrightarrow;": "\u27F6", "LongRightArrow;": "\u27F6", "Longrightarrow;": "\u27F9", "looparrowleft;": "\u21AB", "looparrowright;": "\u21AC", "lopar;": "\u2985", "Lopf;": "\uD835\uDD43", "lopf;": "\uD835\uDD5D", "loplus;": "\u2A2D", "lotimes;": "\u2A34", "lowast;": "\u2217", "lowbar;": "\u005F", "LowerLeftArrow;": "\u2199", "LowerRightArrow;": "\u2198", "loz;": "\u25CA", "lozenge;": "\u25CA", "lozf;": "\u29EB", "lpar;": "\u0028", "lparlt;": "\u2993", "lrarr;": "\u21C6", "lrcorner;": "\u231F", "lrhar;": "\u21CB", "lrhard;": "\u296D", "lrm;": "\u200E", "lrtri;": "\u22BF", "lsaquo;": "\u2039", "lscr;": "\uD835\uDCC1", "Lscr;": "\u2112", "lsh;": "\u21B0", "Lsh;": "\u21B0", "lsim;": "\u2272", "lsime;": "\u2A8D", "lsimg;": "\u2A8F", "lsqb;": "\u005B", "lsquo;": "\u2018", "lsquor;": "\u201A", "Lstrok;": "\u0141", "lstrok;": "\u0142", "ltcc;": "\u2AA6", "ltcir;": "\u2A79", "lt;": "\u003C", "lt": "\u003C", "LT;": "\u003C", "LT": "\u003C", "Lt;": "\u226A", "ltdot;": "\u22D6", "lthree;": "\u22CB", "ltimes;": "\u22C9", "ltlarr;": "\u2976", "ltquest;": "\u2A7B", "ltri;": "\u25C3", "ltrie;": "\u22B4", "ltrif;": "\u25C2", "ltrPar;": "\u2996", "lurdshar;": "\u294A", "luruhar;": "\u2966", "lvertneqq;": "\u2268\uFE00", "lvnE;": "\u2268\uFE00", "macr;": "\u00AF", "macr": "\u00AF", "male;": "\u2642", "malt;": "\u2720", "maltese;": "\u2720", "Map;": "\u2905", "map;": "\u21A6", "mapsto;": "\u21A6", "mapstodown;": "\u21A7", "mapstoleft;": "\u21A4", "mapstoup;": "\u21A5", "marker;": "\u25AE", "mcomma;": "\u2A29", "Mcy;": "\u041C", "mcy;": "\u043C", "mdash;": "\u2014", "mDDot;": "\u223A", "measuredangle;": "\u2221", "MediumSpace;": "\u205F", "Mellintrf;": "\u2133", "Mfr;": "\uD835\uDD10", "mfr;": "\uD835\uDD2A", "mho;": "\u2127", "micro;": "\u00B5", "micro": "\u00B5", "midast;": "\u002A", "midcir;": "\u2AF0", "mid;": "\u2223", "middot;": "\u00B7", "middot": "\u00B7", "minusb;": "\u229F", "minus;": "\u2212", "minusd;": "\u2238", "minusdu;": "\u2A2A", "MinusPlus;": "\u2213", "mlcp;": "\u2ADB", "mldr;": "\u2026", "mnplus;": "\u2213", "models;": "\u22A7", "Mopf;": "\uD835\uDD44", "mopf;": "\uD835\uDD5E", "mp;": "\u2213", "mscr;": "\uD835\uDCC2", "Mscr;": "\u2133", "mstpos;": "\u223E", "Mu;": "\u039C", "mu;": "\u03BC", "multimap;": "\u22B8", "mumap;": "\u22B8", "nabla;": "\u2207", "Nacute;": "\u0143", "nacute;": "\u0144", "nang;": "\u2220\u20D2", "nap;": "\u2249", "napE;": "\u2A70\u0338", "napid;": "\u224B\u0338", "napos;": "\u0149", "napprox;": "\u2249", "natural;": "\u266E", "naturals;": "\u2115", "natur;": "\u266E", "nbsp;": "\u00A0", "nbsp": "\u00A0", "nbump;": "\u224E\u0338", "nbumpe;": "\u224F\u0338", "ncap;": "\u2A43", "Ncaron;": "\u0147", "ncaron;": "\u0148", "Ncedil;": "\u0145", "ncedil;": "\u0146", "ncong;": "\u2247", "ncongdot;": "\u2A6D\u0338", "ncup;": "\u2A42", "Ncy;": "\u041D", "ncy;": "\u043D", "ndash;": "\u2013", "nearhk;": "\u2924", "nearr;": "\u2197", "neArr;": "\u21D7", "nearrow;": "\u2197", "ne;": "\u2260", "nedot;": "\u2250\u0338", "NegativeMediumSpace;": "\u200B", "NegativeThickSpace;": "\u200B", "NegativeThinSpace;": "\u200B", "NegativeVeryThinSpace;": "\u200B", "nequiv;": "\u2262", "nesear;": "\u2928", "nesim;": "\u2242\u0338", "NestedGreaterGreater;": "\u226B", "NestedLessLess;": "\u226A", "NewLine;": "\u000A", "nexist;": "\u2204", "nexists;": "\u2204", "Nfr;": "\uD835\uDD11", "nfr;": "\uD835\uDD2B", "ngE;": "\u2267\u0338", "nge;": "\u2271", "ngeq;": "\u2271", "ngeqq;": "\u2267\u0338", "ngeqslant;": "\u2A7E\u0338", "nges;": "\u2A7E\u0338", "nGg;": "\u22D9\u0338", "ngsim;": "\u2275", "nGt;": "\u226B\u20D2", "ngt;": "\u226F", "ngtr;": "\u226F", "nGtv;": "\u226B\u0338", "nharr;": "\u21AE", "nhArr;": "\u21CE", "nhpar;": "\u2AF2", "ni;": "\u220B", "nis;": "\u22FC", "nisd;": "\u22FA", "niv;": "\u220B", "NJcy;": "\u040A", "njcy;": "\u045A", "nlarr;": "\u219A", "nlArr;": "\u21CD", "nldr;": "\u2025", "nlE;": "\u2266\u0338", "nle;": "\u2270", "nleftarrow;": "\u219A", "nLeftarrow;": "\u21CD", "nleftrightarrow;": "\u21AE", "nLeftrightarrow;": "\u21CE", "nleq;": "\u2270", "nleqq;": "\u2266\u0338", "nleqslant;": "\u2A7D\u0338", "nles;": "\u2A7D\u0338", "nless;": "\u226E", "nLl;": "\u22D8\u0338", "nlsim;": "\u2274", "nLt;": "\u226A\u20D2", "nlt;": "\u226E", "nltri;": "\u22EA", "nltrie;": "\u22EC", "nLtv;": "\u226A\u0338", "nmid;": "\u2224", "NoBreak;": "\u2060", "NonBreakingSpace;": "\u00A0", "nopf;": "\uD835\uDD5F", "Nopf;": "\u2115", "Not;": "\u2AEC", "not;": "\u00AC", "not": "\u00AC", "NotCongruent;": "\u2262", "NotCupCap;": "\u226D", "NotDoubleVerticalBar;": "\u2226", "NotElement;": "\u2209", "NotEqual;": "\u2260", "NotEqualTilde;": "\u2242\u0338", "NotExists;": "\u2204", "NotGreater;": "\u226F", "NotGreaterEqual;": "\u2271", "NotGreaterFullEqual;": "\u2267\u0338", "NotGreaterGreater;": "\u226B\u0338", "NotGreaterLess;": "\u2279", "NotGreaterSlantEqual;": "\u2A7E\u0338", "NotGreaterTilde;": "\u2275", "NotHumpDownHump;": "\u224E\u0338", "NotHumpEqual;": "\u224F\u0338", "notin;": "\u2209", "notindot;": "\u22F5\u0338", "notinE;": "\u22F9\u0338", "notinva;": "\u2209", "notinvb;": "\u22F7", "notinvc;": "\u22F6", "NotLeftTriangleBar;": "\u29CF\u0338", "NotLeftTriangle;": "\u22EA", "NotLeftTriangleEqual;": "\u22EC", "NotLess;": "\u226E", "NotLessEqual;": "\u2270", "NotLessGreater;": "\u2278", "NotLessLess;": "\u226A\u0338", "NotLessSlantEqual;": "\u2A7D\u0338", "NotLessTilde;": "\u2274", "NotNestedGreaterGreater;": "\u2AA2\u0338", "NotNestedLessLess;": "\u2AA1\u0338", "notni;": "\u220C", "notniva;": "\u220C", "notnivb;": "\u22FE", "notnivc;": "\u22FD", "NotPrecedes;": "\u2280", "NotPrecedesEqual;": "\u2AAF\u0338", "NotPrecedesSlantEqual;": "\u22E0", "NotReverseElement;": "\u220C", "NotRightTriangleBar;": "\u29D0\u0338", "NotRightTriangle;": "\u22EB", "NotRightTriangleEqual;": "\u22ED", "NotSquareSubset;": "\u228F\u0338", "NotSquareSubsetEqual;": "\u22E2", "NotSquareSuperset;": "\u2290\u0338", "NotSquareSupersetEqual;": "\u22E3", "NotSubset;": "\u2282\u20D2", "NotSubsetEqual;": "\u2288", "NotSucceeds;": "\u2281", "NotSucceedsEqual;": "\u2AB0\u0338", "NotSucceedsSlantEqual;": "\u22E1", "NotSucceedsTilde;": "\u227F\u0338", "NotSuperset;": "\u2283\u20D2", "NotSupersetEqual;": "\u2289", "NotTilde;": "\u2241", "NotTildeEqual;": "\u2244", "NotTildeFullEqual;": "\u2247", "NotTildeTilde;": "\u2249", "NotVerticalBar;": "\u2224", "nparallel;": "\u2226", "npar;": "\u2226", "nparsl;": "\u2AFD\u20E5", "npart;": "\u2202\u0338", "npolint;": "\u2A14", "npr;": "\u2280", "nprcue;": "\u22E0", "nprec;": "\u2280", "npreceq;": "\u2AAF\u0338", "npre;": "\u2AAF\u0338", "nrarrc;": "\u2933\u0338", "nrarr;": "\u219B", "nrArr;": "\u21CF", "nrarrw;": "\u219D\u0338", "nrightarrow;": "\u219B", "nRightarrow;": "\u21CF", "nrtri;": "\u22EB", "nrtrie;": "\u22ED", "nsc;": "\u2281", "nsccue;": "\u22E1", "nsce;": "\u2AB0\u0338", "Nscr;": "\uD835\uDCA9", "nscr;": "\uD835\uDCC3", "nshortmid;": "\u2224", "nshortparallel;": "\u2226", "nsim;": "\u2241", "nsime;": "\u2244", "nsimeq;": "\u2244", "nsmid;": "\u2224", "nspar;": "\u2226", "nsqsube;": "\u22E2", "nsqsupe;": "\u22E3", "nsub;": "\u2284", "nsubE;": "\u2AC5\u0338", "nsube;": "\u2288", "nsubset;": "\u2282\u20D2", "nsubseteq;": "\u2288", "nsubseteqq;": "\u2AC5\u0338", "nsucc;": "\u2281", "nsucceq;": "\u2AB0\u0338", "nsup;": "\u2285", "nsupE;": "\u2AC6\u0338", "nsupe;": "\u2289", "nsupset;": "\u2283\u20D2", "nsupseteq;": "\u2289", "nsupseteqq;": "\u2AC6\u0338", "ntgl;": "\u2279", "Ntilde;": "\u00D1", "Ntilde": "\u00D1", "ntilde;": "\u00F1", "ntilde": "\u00F1", "ntlg;": "\u2278", "ntriangleleft;": "\u22EA", "ntrianglelefteq;": "\u22EC", "ntriangleright;": "\u22EB", "ntrianglerighteq;": "\u22ED", "Nu;": "\u039D", "nu;": "\u03BD", "num;": "\u0023", "numero;": "\u2116", "numsp;": "\u2007", "nvap;": "\u224D\u20D2", "nvdash;": "\u22AC", "nvDash;": "\u22AD", "nVdash;": "\u22AE", "nVDash;": "\u22AF", "nvge;": "\u2265\u20D2", "nvgt;": "\u003E\u20D2", "nvHarr;": "\u2904", "nvinfin;": "\u29DE", "nvlArr;": "\u2902", "nvle;": "\u2264\u20D2", "nvlt;": "\u003C\u20D2", "nvltrie;": "\u22B4\u20D2", "nvrArr;": "\u2903", "nvrtrie;": "\u22B5\u20D2", "nvsim;": "\u223C\u20D2", "nwarhk;": "\u2923", "nwarr;": "\u2196", "nwArr;": "\u21D6", "nwarrow;": "\u2196", "nwnear;": "\u2927", "Oacute;": "\u00D3", "Oacute": "\u00D3", "oacute;": "\u00F3", "oacute": "\u00F3", "oast;": "\u229B", "Ocirc;": "\u00D4", "Ocirc": "\u00D4", "ocirc;": "\u00F4", "ocirc": "\u00F4", "ocir;": "\u229A", "Ocy;": "\u041E", "ocy;": "\u043E", "odash;": "\u229D", "Odblac;": "\u0150", "odblac;": "\u0151", "odiv;": "\u2A38", "odot;": "\u2299", "odsold;": "\u29BC", "OElig;": "\u0152", "oelig;": "\u0153", "ofcir;": "\u29BF", "Ofr;": "\uD835\uDD12", "ofr;": "\uD835\uDD2C", "ogon;": "\u02DB", "Ograve;": "\u00D2", "Ograve": "\u00D2", "ograve;": "\u00F2", "ograve": "\u00F2", "ogt;": "\u29C1", "ohbar;": "\u29B5", "ohm;": "\u03A9", "oint;": "\u222E", "olarr;": "\u21BA", "olcir;": "\u29BE", "olcross;": "\u29BB", "oline;": "\u203E", "olt;": "\u29C0", "Omacr;": "\u014C", "omacr;": "\u014D", "Omega;": "\u03A9", "omega;": "\u03C9", "Omicron;": "\u039F", "omicron;": "\u03BF", "omid;": "\u29B6", "ominus;": "\u2296", "Oopf;": "\uD835\uDD46", "oopf;": "\uD835\uDD60", "opar;": "\u29B7", "OpenCurlyDoubleQuote;": "\u201C", "OpenCurlyQuote;": "\u2018", "operp;": "\u29B9", "oplus;": "\u2295", "orarr;": "\u21BB", "Or;": "\u2A54", "or;": "\u2228", "ord;": "\u2A5D", "order;": "\u2134", "orderof;": "\u2134", "ordf;": "\u00AA", "ordf": "\u00AA", "ordm;": "\u00BA", "ordm": "\u00BA", "origof;": "\u22B6", "oror;": "\u2A56", "orslope;": "\u2A57", "orv;": "\u2A5B", "oS;": "\u24C8", "Oscr;": "\uD835\uDCAA", "oscr;": "\u2134", "Oslash;": "\u00D8", "Oslash": "\u00D8", "oslash;": "\u00F8", "oslash": "\u00F8", "osol;": "\u2298", "Otilde;": "\u00D5", "Otilde": "\u00D5", "otilde;": "\u00F5", "otilde": "\u00F5", "otimesas;": "\u2A36", "Otimes;": "\u2A37", "otimes;": "\u2297", "Ouml;": "\u00D6", "Ouml": "\u00D6", "ouml;": "\u00F6", "ouml": "\u00F6", "ovbar;": "\u233D", "OverBar;": "\u203E", "OverBrace;": "\u23DE", "OverBracket;": "\u23B4", "OverParenthesis;": "\u23DC", "para;": "\u00B6", "para": "\u00B6", "parallel;": "\u2225", "par;": "\u2225", "parsim;": "\u2AF3", "parsl;": "\u2AFD", "part;": "\u2202", "PartialD;": "\u2202", "Pcy;": "\u041F", "pcy;": "\u043F", "percnt;": "\u0025", "period;": "\u002E", "permil;": "\u2030", "perp;": "\u22A5", "pertenk;": "\u2031", "Pfr;": "\uD835\uDD13", "pfr;": "\uD835\uDD2D", "Phi;": "\u03A6", "phi;": "\u03C6", "phiv;": "\u03D5", "phmmat;": "\u2133", "phone;": "\u260E", "Pi;": "\u03A0", "pi;": "\u03C0", "pitchfork;": "\u22D4", "piv;": "\u03D6", "planck;": "\u210F", "planckh;": "\u210E", "plankv;": "\u210F", "plusacir;": "\u2A23", "plusb;": "\u229E", "pluscir;": "\u2A22", "plus;": "\u002B", "plusdo;": "\u2214", "plusdu;": "\u2A25", "pluse;": "\u2A72", "PlusMinus;": "\u00B1", "plusmn;": "\u00B1", "plusmn": "\u00B1", "plussim;": "\u2A26", "plustwo;": "\u2A27", "pm;": "\u00B1", "Poincareplane;": "\u210C", "pointint;": "\u2A15", "popf;": "\uD835\uDD61", "Popf;": "\u2119", "pound;": "\u00A3", "pound": "\u00A3", "prap;": "\u2AB7", "Pr;": "\u2ABB", "pr;": "\u227A", "prcue;": "\u227C", "precapprox;": "\u2AB7", "prec;": "\u227A", "preccurlyeq;": "\u227C", "Precedes;": "\u227A", "PrecedesEqual;": "\u2AAF", "PrecedesSlantEqual;": "\u227C", "PrecedesTilde;": "\u227E", "preceq;": "\u2AAF", "precnapprox;": "\u2AB9", "precneqq;": "\u2AB5", "precnsim;": "\u22E8", "pre;": "\u2AAF", "prE;": "\u2AB3", "precsim;": "\u227E", "prime;": "\u2032", "Prime;": "\u2033", "primes;": "\u2119", "prnap;": "\u2AB9", "prnE;": "\u2AB5", "prnsim;": "\u22E8", "prod;": "\u220F", "Product;": "\u220F", "profalar;": "\u232E", "profline;": "\u2312", "profsurf;": "\u2313", "prop;": "\u221D", "Proportional;": "\u221D", "Proportion;": "\u2237", "propto;": "\u221D", "prsim;": "\u227E", "prurel;": "\u22B0", "Pscr;": "\uD835\uDCAB", "pscr;": "\uD835\uDCC5", "Psi;": "\u03A8", "psi;": "\u03C8", "puncsp;": "\u2008", "Qfr;": "\uD835\uDD14", "qfr;": "\uD835\uDD2E", "qint;": "\u2A0C", "qopf;": "\uD835\uDD62", "Qopf;": "\u211A", "qprime;": "\u2057", "Qscr;": "\uD835\uDCAC", "qscr;": "\uD835\uDCC6", "quaternions;": "\u210D", "quatint;": "\u2A16", "quest;": "\u003F", "questeq;": "\u225F", "quot;": "\u0022", "quot": "\u0022", "QUOT;": "\u0022", "QUOT": "\u0022", "rAarr;": "\u21DB", "race;": "\u223D\u0331", "Racute;": "\u0154", "racute;": "\u0155", "radic;": "\u221A", "raemptyv;": "\u29B3", "rang;": "\u27E9", "Rang;": "\u27EB", "rangd;": "\u2992", "range;": "\u29A5", "rangle;": "\u27E9", "raquo;": "\u00BB", "raquo": "\u00BB", "rarrap;": "\u2975", "rarrb;": "\u21E5", "rarrbfs;": "\u2920", "rarrc;": "\u2933", "rarr;": "\u2192", "Rarr;": "\u21A0", "rArr;": "\u21D2", "rarrfs;": "\u291E", "rarrhk;": "\u21AA", "rarrlp;": "\u21AC", "rarrpl;": "\u2945", "rarrsim;": "\u2974", "Rarrtl;": "\u2916", "rarrtl;": "\u21A3", "rarrw;": "\u219D", "ratail;": "\u291A", "rAtail;": "\u291C", "ratio;": "\u2236", "rationals;": "\u211A", "rbarr;": "\u290D", "rBarr;": "\u290F", "RBarr;": "\u2910", "rbbrk;": "\u2773", "rbrace;": "\u007D", "rbrack;": "\u005D", "rbrke;": "\u298C", "rbrksld;": "\u298E", "rbrkslu;": "\u2990", "Rcaron;": "\u0158", "rcaron;": "\u0159", "Rcedil;": "\u0156", "rcedil;": "\u0157", "rceil;": "\u2309", "rcub;": "\u007D", "Rcy;": "\u0420", "rcy;": "\u0440", "rdca;": "\u2937", "rdldhar;": "\u2969", "rdquo;": "\u201D", "rdquor;": "\u201D", "rdsh;": "\u21B3", "real;": "\u211C", "realine;": "\u211B", "realpart;": "\u211C", "reals;": "\u211D", "Re;": "\u211C", "rect;": "\u25AD", "reg;": "\u00AE", "reg": "\u00AE", "REG;": "\u00AE", "REG": "\u00AE", "ReverseElement;": "\u220B", "ReverseEquilibrium;": "\u21CB", "ReverseUpEquilibrium;": "\u296F", "rfisht;": "\u297D", "rfloor;": "\u230B", "rfr;": "\uD835\uDD2F", "Rfr;": "\u211C", "rHar;": "\u2964", "rhard;": "\u21C1", "rharu;": "\u21C0", "rharul;": "\u296C", "Rho;": "\u03A1", "rho;": "\u03C1", "rhov;": "\u03F1", "RightAngleBracket;": "\u27E9", "RightArrowBar;": "\u21E5", "rightarrow;": "\u2192", "RightArrow;": "\u2192", "Rightarrow;": "\u21D2", "RightArrowLeftArrow;": "\u21C4", "rightarrowtail;": "\u21A3", "RightCeiling;": "\u2309", "RightDoubleBracket;": "\u27E7", "RightDownTeeVector;": "\u295D", "RightDownVectorBar;": "\u2955", "RightDownVector;": "\u21C2", "RightFloor;": "\u230B", "rightharpoondown;": "\u21C1", "rightharpoonup;": "\u21C0", "rightleftarrows;": "\u21C4", "rightleftharpoons;": "\u21CC", "rightrightarrows;": "\u21C9", "rightsquigarrow;": "\u219D", "RightTeeArrow;": "\u21A6", "RightTee;": "\u22A2", "RightTeeVector;": "\u295B", "rightthreetimes;": "\u22CC", "RightTriangleBar;": "\u29D0", "RightTriangle;": "\u22B3", "RightTriangleEqual;": "\u22B5", "RightUpDownVector;": "\u294F", "RightUpTeeVector;": "\u295C", "RightUpVectorBar;": "\u2954", "RightUpVector;": "\u21BE", "RightVectorBar;": "\u2953", "RightVector;": "\u21C0", "ring;": "\u02DA", "risingdotseq;": "\u2253", "rlarr;": "\u21C4", "rlhar;": "\u21CC", "rlm;": "\u200F", "rmoustache;": "\u23B1", "rmoust;": "\u23B1", "rnmid;": "\u2AEE", "roang;": "\u27ED", "roarr;": "\u21FE", "robrk;": "\u27E7", "ropar;": "\u2986", "ropf;": "\uD835\uDD63", "Ropf;": "\u211D", "roplus;": "\u2A2E", "rotimes;": "\u2A35", "RoundImplies;": "\u2970", "rpar;": "\u0029", "rpargt;": "\u2994", "rppolint;": "\u2A12", "rrarr;": "\u21C9", "Rrightarrow;": "\u21DB", "rsaquo;": "\u203A", "rscr;": "\uD835\uDCC7", "Rscr;": "\u211B", "rsh;": "\u21B1", "Rsh;": "\u21B1", "rsqb;": "\u005D", "rsquo;": "\u2019", "rsquor;": "\u2019", "rthree;": "\u22CC", "rtimes;": "\u22CA", "rtri;": "\u25B9", "rtrie;": "\u22B5", "rtrif;": "\u25B8", "rtriltri;": "\u29CE", "RuleDelayed;": "\u29F4", "ruluhar;": "\u2968", "rx;": "\u211E", "Sacute;": "\u015A", "sacute;": "\u015B", "sbquo;": "\u201A", "scap;": "\u2AB8", "Scaron;": "\u0160", "scaron;": "\u0161", "Sc;": "\u2ABC", "sc;": "\u227B", "sccue;": "\u227D", "sce;": "\u2AB0", "scE;": "\u2AB4", "Scedil;": "\u015E", "scedil;": "\u015F", "Scirc;": "\u015C", "scirc;": "\u015D", "scnap;": "\u2ABA", "scnE;": "\u2AB6", "scnsim;": "\u22E9", "scpolint;": "\u2A13", "scsim;": "\u227F", "Scy;": "\u0421", "scy;": "\u0441", "sdotb;": "\u22A1", "sdot;": "\u22C5", "sdote;": "\u2A66", "searhk;": "\u2925", "searr;": "\u2198", "seArr;": "\u21D8", "searrow;": "\u2198", "sect;": "\u00A7", "sect": "\u00A7", "semi;": "\u003B", "seswar;": "\u2929", "setminus;": "\u2216", "setmn;": "\u2216", "sext;": "\u2736", "Sfr;": "\uD835\uDD16", "sfr;": "\uD835\uDD30", "sfrown;": "\u2322", "sharp;": "\u266F", "SHCHcy;": "\u0429", "shchcy;": "\u0449", "SHcy;": "\u0428", "shcy;": "\u0448", "ShortDownArrow;": "\u2193", "ShortLeftArrow;": "\u2190", "shortmid;": "\u2223", "shortparallel;": "\u2225", "ShortRightArrow;": "\u2192", "ShortUpArrow;": "\u2191", "shy;": "\u00AD", "shy": "\u00AD", "Sigma;": "\u03A3", "sigma;": "\u03C3", "sigmaf;": "\u03C2", "sigmav;": "\u03C2", "sim;": "\u223C", "simdot;": "\u2A6A", "sime;": "\u2243", "simeq;": "\u2243", "simg;": "\u2A9E", "simgE;": "\u2AA0", "siml;": "\u2A9D", "simlE;": "\u2A9F", "simne;": "\u2246", "simplus;": "\u2A24", "simrarr;": "\u2972", "slarr;": "\u2190", "SmallCircle;": "\u2218", "smallsetminus;": "\u2216", "smashp;": "\u2A33", "smeparsl;": "\u29E4", "smid;": "\u2223", "smile;": "\u2323", "smt;": "\u2AAA", "smte;": "\u2AAC", "smtes;": "\u2AAC\uFE00", "SOFTcy;": "\u042C", "softcy;": "\u044C", "solbar;": "\u233F", "solb;": "\u29C4", "sol;": "\u002F", "Sopf;": "\uD835\uDD4A", "sopf;": "\uD835\uDD64", "spades;": "\u2660", "spadesuit;": "\u2660", "spar;": "\u2225", "sqcap;": "\u2293", "sqcaps;": "\u2293\uFE00", "sqcup;": "\u2294", "sqcups;": "\u2294\uFE00", "Sqrt;": "\u221A", "sqsub;": "\u228F", "sqsube;": "\u2291", "sqsubset;": "\u228F", "sqsubseteq;": "\u2291", "sqsup;": "\u2290", "sqsupe;": "\u2292", "sqsupset;": "\u2290", "sqsupseteq;": "\u2292", "square;": "\u25A1", "Square;": "\u25A1", "SquareIntersection;": "\u2293", "SquareSubset;": "\u228F", "SquareSubsetEqual;": "\u2291", "SquareSuperset;": "\u2290", "SquareSupersetEqual;": "\u2292", "SquareUnion;": "\u2294", "squarf;": "\u25AA", "squ;": "\u25A1", "squf;": "\u25AA", "srarr;": "\u2192", "Sscr;": "\uD835\uDCAE", "sscr;": "\uD835\uDCC8", "ssetmn;": "\u2216", "ssmile;": "\u2323", "sstarf;": "\u22C6", "Star;": "\u22C6", "star;": "\u2606", "starf;": "\u2605", "straightepsilon;": "\u03F5", "straightphi;": "\u03D5", "strns;": "\u00AF", "sub;": "\u2282", "Sub;": "\u22D0", "subdot;": "\u2ABD", "subE;": "\u2AC5", "sube;": "\u2286", "subedot;": "\u2AC3", "submult;": "\u2AC1", "subnE;": "\u2ACB", "subne;": "\u228A", "subplus;": "\u2ABF", "subrarr;": "\u2979", "subset;": "\u2282", "Subset;": "\u22D0", "subseteq;": "\u2286", "subseteqq;": "\u2AC5", "SubsetEqual;": "\u2286", "subsetneq;": "\u228A", "subsetneqq;": "\u2ACB", "subsim;": "\u2AC7", "subsub;": "\u2AD5", "subsup;": "\u2AD3", "succapprox;": "\u2AB8", "succ;": "\u227B", "succcurlyeq;": "\u227D", "Succeeds;": "\u227B", "SucceedsEqual;": "\u2AB0", "SucceedsSlantEqual;": "\u227D", "SucceedsTilde;": "\u227F", "succeq;": "\u2AB0", "succnapprox;": "\u2ABA", "succneqq;": "\u2AB6", "succnsim;": "\u22E9", "succsim;": "\u227F", "SuchThat;": "\u220B", "sum;": "\u2211", "Sum;": "\u2211", "sung;": "\u266A", "sup1;": "\u00B9", "sup1": "\u00B9", "sup2;": "\u00B2", "sup2": "\u00B2", "sup3;": "\u00B3", "sup3": "\u00B3", "sup;": "\u2283", "Sup;": "\u22D1", "supdot;": "\u2ABE", "supdsub;": "\u2AD8", "supE;": "\u2AC6", "supe;": "\u2287", "supedot;": "\u2AC4", "Superset;": "\u2283", "SupersetEqual;": "\u2287", "suphsol;": "\u27C9", "suphsub;": "\u2AD7", "suplarr;": "\u297B", "supmult;": "\u2AC2", "supnE;": "\u2ACC", "supne;": "\u228B", "supplus;": "\u2AC0", "supset;": "\u2283", "Supset;": "\u22D1", "supseteq;": "\u2287", "supseteqq;": "\u2AC6", "supsetneq;": "\u228B", "supsetneqq;": "\u2ACC", "supsim;": "\u2AC8", "supsub;": "\u2AD4", "supsup;": "\u2AD6", "swarhk;": "\u2926", "swarr;": "\u2199", "swArr;": "\u21D9", "swarrow;": "\u2199", "swnwar;": "\u292A", "szlig;": "\u00DF", "szlig": "\u00DF", "Tab;": "\u0009", "target;": "\u2316", "Tau;": "\u03A4", "tau;": "\u03C4", "tbrk;": "\u23B4", "Tcaron;": "\u0164", "tcaron;": "\u0165", "Tcedil;": "\u0162", "tcedil;": "\u0163", "Tcy;": "\u0422", "tcy;": "\u0442", "tdot;": "\u20DB", "telrec;": "\u2315", "Tfr;": "\uD835\uDD17", "tfr;": "\uD835\uDD31", "there4;": "\u2234", "therefore;": "\u2234", "Therefore;": "\u2234", "Theta;": "\u0398", "theta;": "\u03B8", "thetasym;": "\u03D1", "thetav;": "\u03D1", "thickapprox;": "\u2248", "thicksim;": "\u223C", "ThickSpace;": "\u205F\u200A", "ThinSpace;": "\u2009", "thinsp;": "\u2009", "thkap;": "\u2248", "thksim;": "\u223C", "THORN;": "\u00DE", "THORN": "\u00DE", "thorn;": "\u00FE", "thorn": "\u00FE", "tilde;": "\u02DC", "Tilde;": "\u223C", "TildeEqual;": "\u2243", "TildeFullEqual;": "\u2245", "TildeTilde;": "\u2248", "timesbar;": "\u2A31", "timesb;": "\u22A0", "times;": "\u00D7", "times": "\u00D7", "timesd;": "\u2A30", "tint;": "\u222D", "toea;": "\u2928", "topbot;": "\u2336", "topcir;": "\u2AF1", "top;": "\u22A4", "Topf;": "\uD835\uDD4B", "topf;": "\uD835\uDD65", "topfork;": "\u2ADA", "tosa;": "\u2929", "tprime;": "\u2034", "trade;": "\u2122", "TRADE;": "\u2122", "triangle;": "\u25B5", "triangledown;": "\u25BF", "triangleleft;": "\u25C3", "trianglelefteq;": "\u22B4", "triangleq;": "\u225C", "triangleright;": "\u25B9", "trianglerighteq;": "\u22B5", "tridot;": "\u25EC", "trie;": "\u225C", "triminus;": "\u2A3A", "TripleDot;": "\u20DB", "triplus;": "\u2A39", "trisb;": "\u29CD", "tritime;": "\u2A3B", "trpezium;": "\u23E2", "Tscr;": "\uD835\uDCAF", "tscr;": "\uD835\uDCC9", "TScy;": "\u0426", "tscy;": "\u0446", "TSHcy;": "\u040B", "tshcy;": "\u045B", "Tstrok;": "\u0166", "tstrok;": "\u0167", "twixt;": "\u226C", "twoheadleftarrow;": "\u219E", "twoheadrightarrow;": "\u21A0", "Uacute;": "\u00DA", "Uacute": "\u00DA", "uacute;": "\u00FA", "uacute": "\u00FA", "uarr;": "\u2191", "Uarr;": "\u219F", "uArr;": "\u21D1", "Uarrocir;": "\u2949", "Ubrcy;": "\u040E", "ubrcy;": "\u045E", "Ubreve;": "\u016C", "ubreve;": "\u016D", "Ucirc;": "\u00DB", "Ucirc": "\u00DB", "ucirc;": "\u00FB", "ucirc": "\u00FB", "Ucy;": "\u0423", "ucy;": "\u0443", "udarr;": "\u21C5", "Udblac;": "\u0170", "udblac;": "\u0171", "udhar;": "\u296E", "ufisht;": "\u297E", "Ufr;": "\uD835\uDD18", "ufr;": "\uD835\uDD32", "Ugrave;": "\u00D9", "Ugrave": "\u00D9", "ugrave;": "\u00F9", "ugrave": "\u00F9", "uHar;": "\u2963", "uharl;": "\u21BF", "uharr;": "\u21BE", "uhblk;": "\u2580", "ulcorn;": "\u231C", "ulcorner;": "\u231C", "ulcrop;": "\u230F", "ultri;": "\u25F8", "Umacr;": "\u016A", "umacr;": "\u016B", "uml;": "\u00A8", "uml": "\u00A8", "UnderBar;": "\u005F", "UnderBrace;": "\u23DF", "UnderBracket;": "\u23B5", "UnderParenthesis;": "\u23DD", "Union;": "\u22C3", "UnionPlus;": "\u228E", "Uogon;": "\u0172", "uogon;": "\u0173", "Uopf;": "\uD835\uDD4C", "uopf;": "\uD835\uDD66", "UpArrowBar;": "\u2912", "uparrow;": "\u2191", "UpArrow;": "\u2191", "Uparrow;": "\u21D1", "UpArrowDownArrow;": "\u21C5", "updownarrow;": "\u2195", "UpDownArrow;": "\u2195", "Updownarrow;": "\u21D5", "UpEquilibrium;": "\u296E", "upharpoonleft;": "\u21BF", "upharpoonright;": "\u21BE", "uplus;": "\u228E", "UpperLeftArrow;": "\u2196", "UpperRightArrow;": "\u2197", "upsi;": "\u03C5", "Upsi;": "\u03D2", "upsih;": "\u03D2", "Upsilon;": "\u03A5", "upsilon;": "\u03C5", "UpTeeArrow;": "\u21A5", "UpTee;": "\u22A5", "upuparrows;": "\u21C8", "urcorn;": "\u231D", "urcorner;": "\u231D", "urcrop;": "\u230E", "Uring;": "\u016E", "uring;": "\u016F", "urtri;": "\u25F9", "Uscr;": "\uD835\uDCB0", "uscr;": "\uD835\uDCCA", "utdot;": "\u22F0", "Utilde;": "\u0168", "utilde;": "\u0169", "utri;": "\u25B5", "utrif;": "\u25B4", "uuarr;": "\u21C8", "Uuml;": "\u00DC", "Uuml": "\u00DC", "uuml;": "\u00FC", "uuml": "\u00FC", "uwangle;": "\u29A7", "vangrt;": "\u299C", "varepsilon;": "\u03F5", "varkappa;": "\u03F0", "varnothing;": "\u2205", "varphi;": "\u03D5", "varpi;": "\u03D6", "varpropto;": "\u221D", "varr;": "\u2195", "vArr;": "\u21D5", "varrho;": "\u03F1", "varsigma;": "\u03C2", "varsubsetneq;": "\u228A\uFE00", "varsubsetneqq;": "\u2ACB\uFE00", "varsupsetneq;": "\u228B\uFE00", "varsupsetneqq;": "\u2ACC\uFE00", "vartheta;": "\u03D1", "vartriangleleft;": "\u22B2", "vartriangleright;": "\u22B3", "vBar;": "\u2AE8", "Vbar;": "\u2AEB", "vBarv;": "\u2AE9", "Vcy;": "\u0412", "vcy;": "\u0432", "vdash;": "\u22A2", "vDash;": "\u22A8", "Vdash;": "\u22A9", "VDash;": "\u22AB", "Vdashl;": "\u2AE6", "veebar;": "\u22BB", "vee;": "\u2228", "Vee;": "\u22C1", "veeeq;": "\u225A", "vellip;": "\u22EE", "verbar;": "\u007C", "Verbar;": "\u2016", "vert;": "\u007C", "Vert;": "\u2016", "VerticalBar;": "\u2223", "VerticalLine;": "\u007C", "VerticalSeparator;": "\u2758", "VerticalTilde;": "\u2240", "VeryThinSpace;": "\u200A", "Vfr;": "\uD835\uDD19", "vfr;": "\uD835\uDD33", "vltri;": "\u22B2", "vnsub;": "\u2282\u20D2", "vnsup;": "\u2283\u20D2", "Vopf;": "\uD835\uDD4D", "vopf;": "\uD835\uDD67", "vprop;": "\u221D", "vrtri;": "\u22B3", "Vscr;": "\uD835\uDCB1", "vscr;": "\uD835\uDCCB", "vsubnE;": "\u2ACB\uFE00", "vsubne;": "\u228A\uFE00", "vsupnE;": "\u2ACC\uFE00", "vsupne;": "\u228B\uFE00", "Vvdash;": "\u22AA", "vzigzag;": "\u299A", "Wcirc;": "\u0174", "wcirc;": "\u0175", "wedbar;": "\u2A5F", "wedge;": "\u2227", "Wedge;": "\u22C0", "wedgeq;": "\u2259", "weierp;": "\u2118", "Wfr;": "\uD835\uDD1A", "wfr;": "\uD835\uDD34", "Wopf;": "\uD835\uDD4E", "wopf;": "\uD835\uDD68", "wp;": "\u2118", "wr;": "\u2240", "wreath;": "\u2240", "Wscr;": "\uD835\uDCB2", "wscr;": "\uD835\uDCCC", "xcap;": "\u22C2", "xcirc;": "\u25EF", "xcup;": "\u22C3", "xdtri;": "\u25BD", "Xfr;": "\uD835\uDD1B", "xfr;": "\uD835\uDD35", "xharr;": "\u27F7", "xhArr;": "\u27FA", "Xi;": "\u039E", "xi;": "\u03BE", "xlarr;": "\u27F5", "xlArr;": "\u27F8", "xmap;": "\u27FC", "xnis;": "\u22FB", "xodot;": "\u2A00", "Xopf;": "\uD835\uDD4F", "xopf;": "\uD835\uDD69", "xoplus;": "\u2A01", "xotime;": "\u2A02", "xrarr;": "\u27F6", "xrArr;": "\u27F9", "Xscr;": "\uD835\uDCB3", "xscr;": "\uD835\uDCCD", "xsqcup;": "\u2A06", "xuplus;": "\u2A04", "xutri;": "\u25B3", "xvee;": "\u22C1", "xwedge;": "\u22C0", "Yacute;": "\u00DD", "Yacute": "\u00DD", "yacute;": "\u00FD", "yacute": "\u00FD", "YAcy;": "\u042F", "yacy;": "\u044F", "Ycirc;": "\u0176", "ycirc;": "\u0177", "Ycy;": "\u042B", "ycy;": "\u044B", "yen;": "\u00A5", "yen": "\u00A5", "Yfr;": "\uD835\uDD1C", "yfr;": "\uD835\uDD36", "YIcy;": "\u0407", "yicy;": "\u0457", "Yopf;": "\uD835\uDD50", "yopf;": "\uD835\uDD6A", "Yscr;": "\uD835\uDCB4", "yscr;": "\uD835\uDCCE", "YUcy;": "\u042E", "yucy;": "\u044E", "yuml;": "\u00FF", "yuml": "\u00FF", "Yuml;": "\u0178", "Zacute;": "\u0179", "zacute;": "\u017A", "Zcaron;": "\u017D", "zcaron;": "\u017E", "Zcy;": "\u0417", "zcy;": "\u0437", "Zdot;": "\u017B", "zdot;": "\u017C", "zeetrf;": "\u2128", "ZeroWidthSpace;": "\u200B", "Zeta;": "\u0396", "zeta;": "\u03B6", "zfr;": "\uD835\uDD37", "Zfr;": "\u2128", "ZHcy;": "\u0416", "zhcy;": "\u0436", "zigrarr;": "\u21DD", "zopf;": "\uD835\uDD6B", "Zopf;": "\u2124", "Zscr;": "\uD835\uDCB5", "zscr;": "\uD835\uDCCF", "zwj;": "\u200D", "zwnj;": "\u200C" }; }, {}], 13:[function(_dereq_,module,exports){ var util = _dereq_('util/'); var pSlice = Array.prototype.slice; var hasOwn = Object.prototype.hasOwnProperty; var assert = module.exports = ok; assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { var err = new Error(); if (err.stack) { var out = err.stack; var fn_name = stackStartFunction.name; var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; util.inherits(assert.AssertionError, Error); function replacer(key, value) { if (util.isUndefined(value)) { return '' + value; } if (util.isNumber(value) && (isNaN(value) || !isFinite(value))) { return value.toString(); } if (util.isFunction(value) || util.isRegExp(value)) { return value.toString(); } return value; } function truncate(s, n) { if (util.isString(s)) { return s.length < n ? s : s.slice(0, n); } else { return s; } } function getMessage(self) { return truncate(JSON.stringify(self.actual, replacer), 128) + ' ' + self.operator + ' ' + truncate(JSON.stringify(self.expected, replacer), 128); } function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } assert.fail = fail; function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; function _deepEqual(actual, expected) { if (actual === expected) { return true; } else if (util.isBuffer(actual) && util.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; } else if (!util.isObject(actual) && !util.isObject(expected)) { return actual == expected; } else { return objEquiv(actual, expected); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (util.isNullOrUndefined(a) || util.isNullOrUndefined(b)) return false; if (a.prototype !== b.prototype) return false; if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try { var ka = objectKeys(a), kb = objectKeys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } if (ka.length != kb.length) return false; ka.sort(); kb.sort(); for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } else if (actual instanceof expected) { return true; } else if (expected.call({}, actual) === true) { return true; } return false; } function _throws(shouldThrow, block, expected, message) { var actual; if (util.isString(expected)) { message = expected; expected = null; } try { block(); } catch (e) { actual = e; } message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } if (!shouldThrow && expectedException(actual, expected)) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws.apply(this, [true].concat(pSlice.call(arguments))); }; assert.doesNotThrow = function(block, /*optional*/message) { _throws.apply(this, [false].concat(pSlice.call(arguments))); }; assert.ifError = function(err) { if (err) {throw err;}}; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; }, {"util/":15}], 14:[function(_dereq_,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } }, {}], 15:[function(_dereq_,module,exports){ (function (process,global){ var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; exports.deprecate = function(fn, msg) { if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; function inspect(obj, opts) { var ctx = { seen: [], stylize: stylizeNoColor }; if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { ctx.showHidden = opts; } else if (opts) { exports._extend(ctx, opts); } if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { if (ctx.customInspect && value && isFunction(value.inspect) && value.inspect !== exports.inspect && !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; if (isArray(value)) { array = true; braces = ['[', ']']; } if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = _dereq_('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; exports.inherits = _dereq_('inherits'); exports._extend = function(origin, add) { if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,_dereq_("/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js"),typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) }, {"./support/isBuffer":14,"/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":18,"inherits":17}], 16:[function(_dereq_,module,exports){ function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; EventEmitter.defaultMaxListeners = 10; EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { throw TypeError('Uncaught, unspecified "error" event.'); } return false; } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; default: len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; handler.apply(this, args); } } else if (isObject(handler)) { len = arguments.length; args = new Array(len - 1); for (i = 1; i < len; i++) args[i - 1] = arguments[i]; listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) this._events[type] = listener; else if (isObject(this._events[type])) this._events[type].push(listener); else this._events[type] = [this._events[type], listener]; if (isObject(this._events[type]) && !this._events[type].warned) { var m; if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); console.trace(); } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else { while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.listenerCount = function(emitter, type) { var ret; if (!emitter._events || !emitter._events[type]) ret = 0; else if (isFunction(emitter._events[type])) ret = 1; else ret = emitter._events[type].length; return ret; }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } }, {}], 17:[function(_dereq_,module,exports){ if (typeof Object.create === 'function') { module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; } else { module.exports = function inherits(ctor, superCtor) { ctor.super_ = superCtor var TempCtor = function () {} TempCtor.prototype = superCtor.prototype ctor.prototype = new TempCtor() ctor.prototype.constructor = ctor } } }, {}], 18:[function(_dereq_,module,exports){ var process = module.exports = {}; process.nextTick = (function () { var canSetImmediate = typeof window !== 'undefined' && window.setImmediate; var canPost = typeof window !== 'undefined' && window.postMessage && window.addEventListener ; if (canSetImmediate) { return function (f) { return window.setImmediate(f) }; } if (canPost) { var queue = []; window.addEventListener('message', function (ev) { var source = ev.source; if ((source === window || source === null) && ev.data === 'process-tick') { ev.stopPropagation(); if (queue.length > 0) { var fn = queue.shift(); fn(); } } }, true); return function nextTick(fn) { queue.push(fn); window.postMessage('process-tick', '*'); }; } return function nextTick(fn) { setTimeout(fn, 0); }; })(); process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; function noop() {} process.on = noop; process.once = noop; process.off = noop; process.emit = noop; process.binding = function (name) { throw new Error('process.binding is not supported'); } process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; }, {}], 19:[function(_dereq_,module,exports){ module.exports=_dereq_(14) }, {}], 20:[function(_dereq_,module,exports){ module.exports=_dereq_(15) }, {"./support/isBuffer":19,"/usr/local/lib/node_modules/browserify/node_modules/insert-module-globals/node_modules/process/browser.js":18,"inherits":17}]},{},[9]) (9) }); ace.define("ace/mode/html_worker",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/worker/mirror","ace/mode/html/saxparser"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var Mirror = require("../worker/mirror").Mirror; var SAXParser = require("./html/saxparser").SAXParser; var errorTypes = { "expected-doctype-but-got-start-tag": "info", "expected-doctype-but-got-chars": "info", "non-html-root": "info", } var Worker = exports.Worker = function(sender) { Mirror.call(this, sender); this.setTimeout(400); this.context = null; }; oop.inherits(Worker, Mirror); (function() { this.setOptions = function(options) { this.context = options.context; }; this.onUpdate = function() { var value = this.doc.getValue(); if (!value) return; var parser = new SAXParser(); var errors = []; var noop = function(){}; parser.contentHandler = { startDocument: noop, endDocument: noop, startElement: noop, endElement: noop, characters: noop }; parser.errorHandler = { error: function(message, location, code) { errors.push({ row: location.line, column: location.column, text: message, type: errorTypes[code] || "error" }); } }; if (this.context) parser.parseFragment(value, this.context); else parser.parse(value); this.sender.emit("error", errors); }; }).call(Worker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/libs/chai.js
3,464
!function (name, definition) { if (typeof define == 'function' && typeof define.amd == 'object') define(definition); else this[name] = definition(); }('chai', function () { // CommonJS require() function require(p){ var path = require.resolve(p) , mod = require.modules[path]; if (!mod) throw new Error('failed to require "' + p + '"'); if (!mod.exports) { mod.exports = {}; mod.call(mod.exports, mod, mod.exports, require.relative(path)); } return mod.exports; } require.modules = {}; require.resolve = function (path){ var orig = path , reg = path + '.js' , index = path + '/index.js'; return require.modules[reg] && reg || require.modules[index] && index || orig; }; require.register = function (path, fn){ require.modules[path] = fn; }; require.relative = function (parent) { return function(p){ if ('.' != p[0]) return require(p); var path = parent.split('/') , segs = p.split('/'); path.pop(); for (var i = 0; i < segs.length; i++) { var seg = segs[i]; if ('..' == seg) path.pop(); else if ('.' != seg) path.push(seg); } return require(path.join('/')); }; }; require.register("chai.js", function(module, exports, require){ /*! * chai * Copyright(c) 2011-2012 Jake Luer <[email protected]> * MIT Licensed */ var used = [] , exports = module.exports = {}; /*! * Chai version */ exports.version = '1.1.0'; /*! * Primary `Assertion` prototype */ exports.Assertion = require('./chai/assertion'); /*! * Assertion Error */ exports.AssertionError = require('./chai/browser/error'); /*! * Utils for plugins (not exported) */ var util = require('./chai/utils'); /** * # .use(function) * * Provides a way to extend the internals of Chai * * @param {Function} * @returns {this} for chaining * @api public */ exports.use = function (fn) { if (!~used.indexOf(fn)) { fn(this, util); used.push(fn); } return this; }; /*! * Core Assertions */ var core = require('./chai/core/assertions'); exports.use(core); /*! * Expect interface */ var expect = require('./chai/interface/expect'); exports.use(expect); /*! * Should interface */ var should = require('./chai/interface/should'); exports.use(should); /*! * Assert interface */ var assert = require('./chai/interface/assert'); exports.use(assert); }); // module: chai.js require.register("chai/assertion.js", function(module, exports, require){ /*! * chai * http://chaijs.com * Copyright(c) 2011-2012 Jake Luer <[email protected]> * MIT Licensed */ /*! * Module dependencies. */ var AssertionError = require('./browser/error') , util = require('./utils') , flag = util.flag; /*! * Module export. */ module.exports = Assertion; /*! * Assertion Constructor * * Creates object for chaining. * * @api private */ function Assertion (obj, msg, stack) { flag(this, 'ssfi', stack || arguments.callee); flag(this, 'object', obj); flag(this, 'message', msg); } /*! * ### Assertion.includeStack * * User configurable property, influences whether stack trace * is included in Assertion error message. Default of false * suppresses stack trace in the error message * * Assertion.includeStack = true; // enable stack on error * * @api public */ Assertion.includeStack = false; Assertion.addProperty = function (name, fn) { util.addProperty(this.prototype, name, fn); }; Assertion.addMethod = function (name, fn) { util.addMethod(this.prototype, name, fn); }; Assertion.addChainableMethod = function (name, fn, chainingBehavior) { util.addChainableMethod(this.prototype, name, fn, chainingBehavior); }; Assertion.overwriteProperty = function (name, fn) { util.overwriteProperty(this.prototype, name, fn); }; Assertion.overwriteMethod = function (name, fn) { util.overwriteMethod(this.prototype, name, fn); }; /*! * ### .assert(expression, message, negateMessage, expected, actual) * * Executes an expression and check expectations. Throws AssertionError for reporting if test doesn't pass. * * @name assert * @param {Philosophical} expression to be tested * @param {String} message to display if fails * @param {String} negatedMessage to display if negated expression fails * @param {Mixed} expected value (remember to check for negation) * @param {Mixed} actual (optional) will default to `this.obj` * @api private */ Assertion.prototype.assert = function (expr, msg, negateMsg, expected, _actual) { var msg = util.getMessage(this, arguments) , actual = util.getActual(this, arguments) , ok = util.test(this, arguments); if (!ok) { throw new AssertionError({ message: msg , actual: actual , expected: expected , stackStartFunction: (Assertion.includeStack) ? this.assert : flag(this, 'ssfi') }); } }; /*! * ### ._obj * * Quick reference to stored `actual` value for plugin developers. * * @api private */ Object.defineProperty(Assertion.prototype, '_obj', { get: function () { return flag(this, 'object'); } , set: function (val) { flag(this, 'object', val); } }); }); // module: chai/assertion.js require.register("chai/browser/error.js", function(module, exports, require){ /*! * chai * Copyright(c) 2011-2012 Jake Luer <[email protected]> * MIT Licensed */ module.exports = AssertionError; function AssertionError (options) { options = options || {}; this.message = options.message; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.stackStartFunction && Error.captureStackTrace) { var stackStartFunction = options.stackStartFunction; Error.captureStackTrace(this, stackStartFunction); } } AssertionError.prototype = Object.create(Error.prototype); AssertionError.prototype.name = 'AssertionError'; AssertionError.prototype.constructor = AssertionError; AssertionError.prototype.toString = function() { return this.message; }; }); // module: chai/browser/error.js require.register("chai/core/assertions.js", function(module, exports, require){ /*! * chai * http://chaijs.com * Copyright(c) 2011-2012 Jake Luer <[email protected]> * MIT Licensed */ module.exports = function (chai, _) { var Assertion = chai.Assertion , toString = Object.prototype.toString , flag = _.flag; /** * ### Language Chains * * The following are provide as chainable getters to * improve the readability of your assertions. They * do not provide an testing capability unless they * have been overwritten by a plugin. * * **Chains** * * - to * - be * - been * - is * - that * - and * - have * - with * * @name language chains * @api public */ [ 'to', 'be', 'been' , 'is', 'and', 'have' , 'with', 'that' ].forEach(function (chain) { Assertion.addProperty(chain, function () { return this; }); }); /** * ### .not * * Negates any of assertions following in the chain. * * expect(foo).to.not.equal('bar'); * expect(goodFn).to.not.throw(Error); * expect({ foo: 'baz' }).to.have.property('foo') * .and.not.equal('bar'); * * @name not * @api public */ Assertion.addProperty('not', function () { flag(this, 'negate', true); }); /** * ### .deep * * Sets the `deep` flag, later used by the `equal` and * `property` assertions. * * expect(foo).to.deep.equal({ bar: 'baz' }); * expect({ foo: { bar: { baz: 'quux' } } }) * .to.have.deep.property('foo.bar.baz', 'quux'); * * @name deep * @api public */ Assertion.addProperty('deep', function () { flag(this, 'deep', true); }); /** * ### .a(type) * * The `a` and `an` assertions are aliases that can be * used either as language chains or to assert a value's * type (as revealed by `Object.prototype.toString`). * * // typeof * expect('test').to.be.a('string'); * expect({ foo: 'bar' }).to.be.an('object'); * expect(null).to.be.a('null'); * expect(undefined).to.be.an('undefined'); * * // language chain * expect(foo).to.be.an.instanceof(Foo); * * @name a * @alias an * @param {String} type * @api public */ function an(type) { var obj = flag(this, 'object') , klassStart = type.charAt(0).toUpperCase() , klass = klassStart + type.slice(1) , article = ~[ 'A', 'E', 'I', 'O', 'U' ].indexOf(klassStart) ? 'an ' : 'a '; this.assert( '[object ' + klass + ']' === toString.call(obj) , 'expected #{this} to be ' + article + type , 'expected #{this} not to be ' + article + type ); } Assertion.addChainableMethod('an', an); Assertion.addChainableMethod('a', an); /** * ### .include(value) * * The `include` and `contain` assertions can be used as either property * based language chains or as methods to assert the inclusion of an object * in an array or a substring in a string. When used as language chains, * they toggle the `contain` flag for the `keys` assertion. * * expect([1,2,3]).to.include(2); * expect('foobar').to.contain('foo'); * expect({ foo: 'bar', hello: 'universe' }).to.include.keys('foo'); * * @name include * @alias contain * @param {Object|String|Number} obj * @api public */ function includeChainingBehavior () { flag(this, 'contains', true); } function include (val) { var obj = flag(this, 'object') this.assert( ~obj.indexOf(val) , 'expected #{this} to include ' + _.inspect(val) , 'expected #{this} to not include ' + _.inspect(val)); } Assertion.addChainableMethod('include', include, includeChainingBehavior); Assertion.addChainableMethod('contain', include, includeChainingBehavior); /** * ### .ok * * Asserts that the target is truthy. * * expect('everthing').to.be.ok; * expect(1).to.be.ok; * expect(false).to.not.be.ok; * expect(undefined).to.not.be.ok; * expect(null).to.not.be.ok; * * @name ok * @api public */ Assertion.addProperty('ok', function () { this.assert( flag(this, 'object') , 'expected #{this} to be truthy' , 'expected #{this} to be falsy'); }); /** * ### .true * * Asserts that the target is `true`. * * expect(true).to.be.true; * expect(1).to.not.be.true; * * @name true * @api public */ Assertion.addProperty('true', function () { this.assert( true === flag(this, 'object') , 'expected #{this} to be true' , 'expected #{this} to be false' , this.negate ? false : true ); }); /** * ### .false * * Asserts that the target is `false`. * * expect(false).to.be.false; * expect(0).to.not.be.false; * * @name false * @api public */ Assertion.addProperty('false', function () { this.assert( false === flag(this, 'object') , 'expected #{this} to be false' , 'expected #{this} to be true' , this.negate ? true : false ); }); /** * ### .null * * Asserts that the target is `null`. * * expect(null).to.be.null; * expect(undefined).not.to.be.null; * * @name null * @api public */ Assertion.addProperty('null', function () { this.assert( null === flag(this, 'object') , 'expected #{this} to be null' , 'expected #{this} not to be null' ); }); /** * ### .undefined * * Asserts that the target is `undefined`. * * expect(undefined).to.be.undefined; * expect(null).to.not.be.undefined; * * @name undefined * @api public */ Assertion.addProperty('undefined', function () { this.assert( undefined === flag(this, 'object') , 'expected #{this} to be undefined' , 'expected #{this} not to be undefined' ); }); /** * ### .exist * * Asserts that the target is neither `null` nor `undefined`. * * var foo = 'hi' * , bar = null * , baz; * * expect(foo).to.exist; * expect(bar).to.not.exist; * expect(baz).to.not.exist; * * @name exist * @api public */ Assertion.addProperty('exist', function () { this.assert( null != flag(this, 'object') , 'expected #{this} to exist' , 'expected #{this} to not exist' ); }); /** * ### .empty * * Asserts that the target's length is `0`. For arrays, it checks * the `length` property. For objects, it gets the count of * enumerable keys. * * expect([]).to.be.empty; * expect('').to.be.empty; * expect({}).to.be.empty; * * @name empty * @api public */ Assertion.addProperty('empty', function () { var obj = flag(this, 'object') , expected = obj; if (Array.isArray(obj) || 'string' === typeof object) { expected = obj.length; } else if (typeof obj === 'object') { expected = Object.keys(obj).length; } this.assert( !expected , 'expected #{this} to be empty' , 'expected #{this} not to be empty' ); }); /** * ### .arguments * * Asserts that the target is an arguments object. * * function test () { * expect(arguments).to.be.arguments; * } * * @name arguments * @alias Arguments * @api public */ function checkArguments () { var obj = flag(this, 'object') , type = Object.prototype.toString.call(obj); this.assert( '[object Arguments]' === type , 'expected #{this} to be arguments but got ' + type , 'expected #{this} to not be arguments' ); } Assertion.addProperty('arguments', checkArguments); Assertion.addProperty('Arguments', checkArguments); /** * ### .equal(value) * * Asserts that the target is strictly equal (`===`) to `value`. * Alternately, if the `deep` flag is set, asserts that * the target is deeply equal to `value`. * * expect('hello').to.equal('hello'); * expect(42).to.equal(42); * expect(1).to.not.equal(true); * expect({ foo: 'bar' }).to.not.equal({ foo: 'bar' }); * expect({ foo: 'bar' }).to.deep.equal({ foo: 'bar' }); * * @name equal * @alias eq * @alias deep.equal * @param {Mixed} value * @api public */ function assertEqual (val) { var obj = flag(this, 'object'); if (flag(this, 'deep')) { return this.eql(val); } else { this.assert( val === obj , 'expected #{this} to equal #{exp}' , 'expected #{this} to not equal #{exp}' , val ); } } Assertion.addMethod('equal', assertEqual); Assertion.addMethod('eq', assertEqual); /** * ### .eql(value) * * Asserts that the target is deeply equal to `value`. * * expect({ foo: 'bar' }).to.eql({ foo: 'bar' }); * expect([ 1, 2, 3 ]).to.eql([ 1, 2, 3 ]); * * @name eql * @param {Mixed} value * @api public */ Assertion.addMethod('eql', function (obj) { this.assert( _.eql(obj, flag(this, 'object')) , 'expected #{this} to deeply equal #{exp}' , 'expected #{this} to not deeply equal #{exp}' , obj ); }); /** * ### .above(value) * * Asserts that the target is greater than `value`. * * expect(10).to.be.above(5); * * Can also be used in conjunction with `length` to * assert a minimum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.above(2); * expect([ 1, 2, 3 ]).to.have.length.above(2); * * @name above * @alias gt * @alias greaterThan * @param {Number} value * @api public */ function assertAbove (n) { var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj).to.have.property('length'); var len = obj.length; this.assert( len > n , 'expected #{this} to have a length above #{exp} but got #{act}' , 'expected #{this} to not have a length above #{exp}' , n , len ); } else { this.assert( obj > n , 'expected #{this} to be above ' + n , 'expected #{this} to be below ' + n ); } } Assertion.addMethod('above', assertAbove); Assertion.addMethod('gt', assertAbove); Assertion.addMethod('greaterThan', assertAbove); /** * ### .below(value) * * Asserts that the target is less than `value`. * * expect(5).to.be.below(10); * * Can also be used in conjunction with `length` to * assert a maximum length. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.below(4); * expect([ 1, 2, 3 ]).to.have.length.below(4); * * @name below * @alias lt * @alias lessThan * @param {Number} value * @api public */ function assertBelow (n) { var obj = flag(this, 'object'); if (flag(this, 'doLength')) { new Assertion(obj).to.have.property('length'); var len = obj.length; this.assert( len < n , 'expected #{this} to have a length below #{exp} but got #{act}' , 'expected #{this} to not have a length below #{exp}' , n , len ); } else { this.assert( obj < n , 'expected #{this} to be below ' + n , 'expected #{this} to be above ' + n ); } } Assertion.addMethod('below', assertBelow); Assertion.addMethod('lt', assertBelow); Assertion.addMethod('lessThan', assertBelow); /** * ### .within(start, finish) * * Asserts that the target is within a range. * * expect(7).to.be.within(5,10); * * Can also be used in conjunction with `length` to * assert a length range. The benefit being a * more informative error message than if the length * was supplied directly. * * expect('foo').to.have.length.within(2,4); * expect([ 1, 2, 3 ]).to.have.length.within(2,4); * * @name within * @param {Number} start lowerbound inclusive * @param {Number} finish upperbound inclusive * @api public */ Assertion.addMethod('within', function (start, finish) { var obj = flag(this, 'object') , range = start + '..' + finish; if (flag(this, 'doLength')) { new Assertion(obj).to.have.property('length'); var len = obj.length; this.assert( len >= start && len <= finish , 'expected #{this} to have a length within ' + range , 'expected #{this} to not have a length within ' + range ); } else { this.assert( obj >= start && obj <= finish , 'expected #{this} to be within ' + range , 'expected #{this} to not be within ' + range ); } }); /** * ### .instanceof(constructor) * * Asserts that the target is an instance of `constructor`. * * var Tea = function (name) { this.name = name; } * , Chai = new Tea('chai'); * * expect(Chai).to.be.an.instanceof(Tea); * expect([ 1, 2, 3 ]).to.be.instanceof(Array); * * @name instanceof * @param {Constructor} constructor * @alias instanceOf * @api public */ function assertInstanceOf (constructor) { var name = _.getName(constructor); this.assert( flag(this, 'object') instanceof constructor , 'expected #{this} to be an instance of ' + name , 'expected #{this} to not be an instance of ' + name ); }; Assertion.addMethod('instanceof', assertInstanceOf); Assertion.addMethod('instanceOf', assertInstanceOf); /** * ### .property(name, [value]) * * Asserts that the target has a property `name`, optionally asserting that * the value of that property is strictly equal to `value`. * If the `deep` flag is set, you can use dot- and bracket-notation for deep * references into objects and arrays. * * // simple referencing * var obj = { foo: 'bar' }; * expect(obj).to.have.property('foo'); * expect(obj).to.have.property('foo', 'bar'); * * // deep referencing * var deepObj = { * green: { tea: 'matcha' } * , teas: [ 'chai', 'matcha', { tea: 'konacha' } ] * }; * expect(deepObj).to.have.deep.property('green.tea', 'matcha'); * expect(deepObj).to.have.deep.property('teas[1]', 'matcha'); * expect(deepObj).to.have.deep.property('teas[2].tea', 'konacha'); * * You can also use an array as the starting point of a `deep.property` * assertion, or traverse nested arrays. * * var arr = [ * [ 'chai', 'matcha', 'konacha' ] * , [ { tea: 'chai' } * , { tea: 'matcha' } * , { tea: 'konacha' } ] * ]; * * expect(arr).to.have.deep.property('[0][1]', 'matcha'); * expect(arr).to.have.deep.property('[1][2].tea', 'konacha'); * * Furthermore, `property` changes the subject of the assertion * to be the value of that property from the original object. This * permits for further chainable assertions on that property. * * expect(obj).to.have.property('foo') * .that.is.a('string'); * expect(deepObj).to.have.property('green') * .that.is.an('object') * .that.deep.equals({ tea: 'matcha' }); * expect(deepObj).to.have.property('teas') * .that.is.an('array') * .with.deep.property('[2]') * .that.deep.equals({ tea: 'konacha' }); * * @name property * @alias deep.property * @param {String} name * @param {Mixed} value (optional) * @returns value of property for chaining * @api public */ Assertion.addMethod('property', function (name, val) { var obj = flag(this, 'object') , value = flag(this, 'deep') ? _.getPathValue(name, obj) : obj[name] , descriptor = flag(this, 'deep') ? 'deep property ' : 'property ' , negate = flag(this, 'negate'); if (negate && undefined !== val) { if (undefined === value) { throw new Error(_.inspect(obj) + ' has no ' + descriptor + _.inspect(name)); } } else { this.assert( undefined !== value , 'expected #{this} to have a ' + descriptor + _.inspect(name) , 'expected #{this} to not have ' + descriptor + _.inspect(name)); } if (undefined !== val) { this.assert( val === value , 'expected #{this} to have a ' + descriptor + _.inspect(name) + ' of #{exp}, but got #{act}' , 'expected #{this} to not have a ' + descriptor + _.inspect(name) + ' of #{act}' , val , value ); } flag(this, 'object', value); }); /** * ### .ownProperty(name) * * Asserts that the target has an own property `name`. * * expect('test').to.have.ownProperty('length'); * * @name ownProperty * @alias haveOwnProperty * @param {String} name * @api public */ function assertOwnProperty (name) { var obj = flag(this, 'object'); this.assert( obj.hasOwnProperty(name) , 'expected #{this} to have own property ' + _.inspect(name) , 'expected #{this} to not have own property ' + _.inspect(name) ); } Assertion.addMethod('ownProperty', assertOwnProperty); Assertion.addMethod('haveOwnProperty', assertOwnProperty); /** * ### .length(value) * * Asserts that the target's `length` property has * the expected value. * * expect([ 1, 2, 3]).to.have.length(3); * expect('foobar').to.have.length(6); * * Can also be used as a chain precursor to a value * comparison for the length property. * * expect('foo').to.have.length.above(2); * expect([ 1, 2, 3 ]).to.have.length.above(2); * expect('foo').to.have.length.below(4); * expect([ 1, 2, 3 ]).to.have.length.below(4); * expect('foo').to.have.length.within(2,4); * expect([ 1, 2, 3 ]).to.have.length.within(2,4); * * @name length * @alias lengthOf * @param {Number} length * @api public */ function assertLengthChain () { flag(this, 'doLength', true); } function assertLength (n) { var obj = flag(this, 'object'); new Assertion(obj).to.have.property('length'); var len = obj.length; this.assert( len == n , 'expected #{this} to have a length of #{exp} but got #{act}' , 'expected #{this} to not have a length of #{act}' , n , len ); } Assertion.addChainableMethod('length', assertLength, assertLengthChain); Assertion.addMethod('lengthOf', assertLength, assertLengthChain); /** * ### .match(regexp) * * Asserts that the target matches a regular expression. * * expect('foobar').to.match(/^foo/); * * @name match * @param {RegExp} RegularExpression * @api public */ Assertion.addMethod('match', function (re) { var obj = flag(this, 'object'); this.assert( re.exec(obj) , 'expected #{this} to match ' + re , 'expected #{this} not to match ' + re ); }); /** * ### .string(string) * * Asserts that the string target contains another string. * * expect('foobar').to.have.string('bar'); * * @name string * @param {String} string * @api public */ Assertion.addMethod('string', function (str) { var obj = flag(this, 'object'); new Assertion(obj).is.a('string'); this.assert( ~obj.indexOf(str) , 'expected #{this} to contain ' + _.inspect(str) , 'expected #{this} to not contain ' + _.inspect(str) ); }); /** * ### .keys(key1, [key2], [...]) * * Asserts that the target has exactly the given keys, or * asserts the inclusion of some keys when using the * `include` or `contain` modifiers. * * expect({ foo: 1, bar: 2 }).to.have.keys(['foo', 'bar']); * expect({ foo: 1, bar: 2, baz: 3 }).to.contain.keys('foo', 'bar'); * * @name keys * @alias key * @param {String...|Array} keys * @api public */ function assertKeys (keys) { var obj = flag(this, 'object') , str , ok = true; keys = keys instanceof Array ? keys : Array.prototype.slice.call(arguments); if (!keys.length) throw new Error('keys required'); var actual = Object.keys(obj) , len = keys.length; // Inclusion ok = keys.every(function(key){ return ~actual.indexOf(key); }); // Strict if (!flag(this, 'negate') && !flag(this, 'contains')) { ok = ok && keys.length == actual.length; } // Key string if (len > 1) { keys = keys.map(function(key){ return _.inspect(key); }); var last = keys.pop(); str = keys.join(', ') + ', and ' + last; } else { str = _.inspect(keys[0]); } // Form str = (len > 1 ? 'keys ' : 'key ') + str; // Have / include str = (flag(this, 'contains') ? 'contain ' : 'have ') + str; // Assertion this.assert( ok , 'expected #{this} to ' + str , 'expected #{this} to not ' + str ); } Assertion.addMethod('keys', assertKeys); Assertion.addMethod('key', assertKeys); /** * ### .throw(constructor) * * Asserts that the function target will throw a specific error, or specific type of error * (as determined using `instanceof`), optionally with a RegExp or string inclusion test * for the error's message. * * var err = new ReferenceError('This is a bad function.'); * var fn = function () { throw err; } * expect(fn).to.throw(ReferenceError); * expect(fn).to.throw(Error); * expect(fn).to.throw(/bad function/); * expect(fn).to.not.throw('good function'); * expect(fn).to.throw(ReferenceError, /bad function/); * expect(fn).to.throw(err); * expect(fn).to.not.throw(new RangeError('Out of range.')); * * Please note that when a throw expectation is negated, it will check each * parameter independently, starting with error constructor type. The appropriate way * to check for the existence of a type of error but for a message that does not match * is to use `and`. * * expect(fn).to.throw(ReferenceError) * .and.not.throw(/good function/); * * @name throw * @alias throws * @alias Throw * @param {ErrorConstructor} constructor * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types * @api public */ function assertThrows (constructor, msg) { var obj = flag(this, 'object'); new Assertion(obj).is.a('function'); var thrown = false , desiredError = null , name = null; if (arguments.length === 0) { msg = null; constructor = null; } else if (constructor && (constructor instanceof RegExp || 'string' === typeof constructor)) { msg = constructor; constructor = null; } else if (constructor && constructor instanceof Error) { desiredError = constructor; constructor = null; msg = null; } else if (typeof constructor === 'function') { name = (new constructor()).name; } else { constructor = null; } try { obj(); } catch (err) { // first, check desired error if (desiredError) { this.assert( err === desiredError , 'expected #{this} to throw ' + _.inspect(desiredError) + ' but ' + _.inspect(err) + ' was thrown' , 'expected #{this} to not throw ' + _.inspect(desiredError) ); return this; } // next, check constructor if (constructor) { this.assert( err instanceof constructor , 'expected #{this} to throw ' + name + ' but a ' + err.name + ' was thrown' , 'expected #{this} to not throw ' + name ); if (!msg) return this; } // next, check message if (err.message && msg && msg instanceof RegExp) { this.assert( msg.exec(err.message) , 'expected #{this} to throw error matching ' + msg + ' but got ' + _.inspect(err.message) , 'expected #{this} to throw error not matching ' + msg ); return this; } else if (err.message && msg && 'string' === typeof msg) { this.assert( ~err.message.indexOf(msg) , 'expected #{this} to throw error including #{exp} but got #{act}' , 'expected #{this} to throw error not including #{act}' , msg , err.message ); return this; } else { thrown = true; } } var expectedThrown = name ? name : desiredError ? _.inspect(desiredError) : 'an error'; this.assert( thrown === true , 'expected #{this} to throw ' + expectedThrown , 'expected #{this} to not throw ' + expectedThrown ); }; Assertion.addMethod('throw', assertThrows); Assertion.addMethod('throws', assertThrows); Assertion.addMethod('Throw', assertThrows); /** * ### .respondTo(method) * * Asserts that the object or class target will respond to a method. * * Klass.prototype.bar = function(){}; * expect(Klass).to.respondTo('bar'); * expect(obj).to.respondTo('bar'); * * To check if a constructor will respond to a static function, * set the `itself` flag. * * Klass.baz = function(){}; * expect(Klass).itself.to.respondTo('baz'); * * @name respondTo * @param {String} method * @api public */ Assertion.addMethod('respondTo', function (method) { var obj = flag(this, 'object') , itself = flag(this, 'itself') , context = ('function' === typeof obj && !itself) ? obj.prototype[method] : obj[method]; this.assert( 'function' === typeof context , 'expected #{this} to respond to ' + _.inspect(method) , 'expected #{this} to not respond to ' + _.inspect(method) ); }); /** * ### .itself * * Sets the `itself` flag, later used by the `respondTo` assertion. * * function Foo() {} * Foo.bar = function() {} * Foo.prototype.baz = function() {} * * expect(Foo).itself.to.respondTo('bar'); * expect(Foo).itself.not.to.respondTo('baz'); * * @name itself * @api public */ Assertion.addProperty('itself', function () { flag(this, 'itself', true); }); /** * ### .satisfy(method) * * Asserts that the target passes a given truth test. * * expect(1).to.satisfy(function(num) { return num > 0; }); * * @name satisfy * @param {Function} matcher * @api public */ Assertion.addMethod('satisfy', function (matcher) { var obj = flag(this, 'object'); this.assert( matcher(obj) , 'expected #{this} to satisfy ' + _.inspect(matcher) , 'expected #{this} to not satisfy' + _.inspect(matcher) , this.negate ? false : true , matcher(obj) ); }); /** * ### .closeTo(expected, delta) * * Asserts that the target is equal `expected`, to within a +/- `delta` range. * * expect(1.5).to.be.closeTo(1, 0.5); * * @name closeTo * @param {Number} expected * @param {Number} delta * @api public */ Assertion.addMethod('closeTo', function (expected, delta) { var obj = flag(this, 'object'); this.assert( Math.abs(obj - expected) <= delta , 'expected #{this} to be close to ' + expected + ' +/- ' + delta , 'expected #{this} not to be close to ' + expected + ' +/- ' + delta ); }); }; }); // module: chai/core/assertions.js require.register("chai/interface/assert.js", function(module, exports, require){ /*! * chai * Copyright(c) 2011-2012 Jake Luer <[email protected]> * MIT Licensed */ module.exports = function (chai, util) { /*! * Chai dependencies. */ var Assertion = chai.Assertion , flag = util.flag; /*! * Module export. */ /** * ### assert(expression, message) * * Write your own test expressions. * * assert('foo' !== 'bar', 'foo is not bar'); * assert(Array.isArray([]), 'empty arrays are arrays'); * * @param {Mixed} expression to test for truthiness * @param {String} message to display on error * @name assert * @api public */ var assert = chai.assert = function (express, errmsg) { var test = new Assertion(null); test.assert( express , errmsg , '[ negation message unavailable ]' ); }; /** * ### .fail(actual, expected, [message], [operator]) * * Throw a failure. Node.js `assert` module-compatible. * * @name fail * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @param {String} operator * @api public */ assert.fail = function (actual, expected, message, operator) { throw new chai.AssertionError({ actual: actual , expected: expected , message: message , operator: operator , stackStartFunction: assert.fail }); }; /** * ### .ok(object, [message]) * * Asserts that `object` is truthy. * * assert.ok('everything', 'everything is ok'); * assert.ok(false, 'this will fail'); * * @name ok * @param {Mixed} object to test * @param {String} message * @api public */ assert.ok = function (val, msg) { new Assertion(val, msg).is.ok; }; /** * ### .equal(actual, expected, [message]) * * Asserts non-strict equality (`==`) of `actual` and `expected`. * * assert.equal(3, '3', '== coerces values to strings'); * * @name equal * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.equal = function (act, exp, msg) { var test = new Assertion(act, msg); test.assert( exp == flag(test, 'object') , 'expected #{this} to equal #{exp}' , 'expected #{this} to not equal #{act}' , exp , act ); }; /** * ### .notEqual(actual, expected, [message]) * * Asserts non-strict inequality (`!=`) of `actual` and `expected`. * * assert.notEqual(3, 4, 'these numbers are not equal'); * * @name notEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.notEqual = function (act, exp, msg) { var test = new Assertion(act, msg); test.assert( exp != flag(test, 'object') , 'expected #{this} to not equal #{exp}' , 'expected #{this} to equal #{act}' , exp , act ); }; /** * ### .strictEqual(actual, expected, [message]) * * Asserts strict equality (`===`) of `actual` and `expected`. * * assert.strictEqual(true, true, 'these booleans are strictly equal'); * * @name strictEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.strictEqual = function (act, exp, msg) { new Assertion(act, msg).to.equal(exp); }; /** * ### .notStrictEqual(actual, expected, [message]) * * Asserts strict inequality (`!==`) of `actual` and `expected`. * * assert.notStrictEqual(3, '3', 'no coercion for strict equality'); * * @name notStrictEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.notStrictEqual = function (act, exp, msg) { new Assertion(act, msg).to.not.equal(exp); }; /** * ### .deepEqual(actual, expected, [message]) * * Asserts that `actual` is deeply equal to `expected`. * * assert.deepEqual({ tea: 'green' }, { tea: 'green' }); * * @name deepEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.deepEqual = function (act, exp, msg) { new Assertion(act, msg).to.eql(exp); }; /** * ### .notDeepEqual(actual, expected, [message]) * * Assert that `actual` is not deeply equal to `expected`. * * assert.notDeepEqual({ tea: 'green' }, { tea: 'jasmine' }); * * @name notDeepEqual * @param {Mixed} actual * @param {Mixed} expected * @param {String} message * @api public */ assert.notDeepEqual = function (act, exp, msg) { new Assertion(act, msg).to.not.eql(exp); }; /** * ### .isTrue(value, [message]) * * Asserts that `value` is true. * * var teaServed = true; * assert.isTrue(teaServed, 'the tea has been served'); * * @name isTrue * @param {Mixed} value * @param {String} message * @api public */ assert.isTrue = function (val, msg) { new Assertion(val, msg).is['true']; }; /** * ### .isFalse(value, [message]) * * Asserts that `value` is false. * * var teaServed = false; * assert.isFalse(teaServed, 'no tea yet? hmm...'); * * @name isFalse * @param {Mixed} value * @param {String} message * @api public */ assert.isFalse = function (val, msg) { new Assertion(val, msg).is['false']; }; /** * ### .isNull(value, [message]) * * Asserts that `value` is null. * * assert.isNull(err, 'there was no error'); * * @name isNull * @param {Mixed} value * @param {String} message * @api public */ assert.isNull = function (val, msg) { new Assertion(val, msg).to.equal(null); }; /** * ### .isNotNull(value, [message]) * * Asserts that `value` is not null. * * var tea = 'tasty chai'; * assert.isNotNull(tea, 'great, time for tea!'); * * @name isNotNull * @param {Mixed} value * @param {String} message * @api public */ assert.isNotNull = function (val, msg) { new Assertion(val, msg).to.not.equal(null); }; /** * ### .isUndefined(value, [message]) * * Asserts that `value` is `undefined`. * * var tea; * assert.isUndefined(tea, 'no tea defined'); * * @name isUndefined * @param {Mixed} value * @param {String} message * @api public */ assert.isUndefined = function (val, msg) { new Assertion(val, msg).to.equal(undefined); }; /** * ### .isDefined(value, [message]) * * Asserts that `value` is not `undefined`. * * var tea = 'cup of chai'; * assert.isDefined(tea, 'tea has been defined'); * * @name isUndefined * @param {Mixed} value * @param {String} message * @api public */ assert.isDefined = function (val, msg) { new Assertion(val, msg).to.not.equal(undefined); }; /** * ### .isFunction(value, [message]) * * Asserts that `value` is a function. * * function serveTea() { return 'cup of tea'; }; * assert.isFunction(serveTea, 'great, we can have tea now'); * * @name isFunction * @param {Mixed} value * @param {String} message * @api public */ assert.isFunction = function (val, msg) { new Assertion(val, msg).to.be.a('function'); }; /** * ### .isNotFunction(value, [message]) * * Asserts that `value` is _not_ a function. * * var serveTea = [ 'heat', 'pour', 'sip' ]; * assert.isNotFunction(serveTea, 'great, we have listed the steps'); * * @name isNotFunction * @param {Mixed} value * @param {String} message * @api public */ assert.isNotFunction = function (val, msg) { new Assertion(val, msg).to.not.be.a('function'); }; /** * ### .isObject(value, [message]) * * Asserts that `value` is an object (as revealed by * `Object.prototype.toString`). * * var selection = { name: 'Chai', serve: 'with spices' }; * assert.isObject(selection, 'tea selection is an object'); * * @name isObject * @param {Mixed} value * @param {String} message * @api public */ assert.isObject = function (val, msg) { new Assertion(val, msg).to.be.a('object'); }; /** * ### .isNotObject(value, [message]) * * Asserts that `value` is _not_ an object. * * var selection = 'chai' * assert.isObject(selection, 'tea selection is not an object'); * assert.isObject(null, 'null is not an object'); * * @name isNotObject * @param {Mixed} value * @param {String} message * @api public */ assert.isNotObject = function (val, msg) { new Assertion(val, msg).to.not.be.a('object'); }; /** * ### .isArray(value, [message]) * * Asserts that `value` is an array. * * var menu = [ 'green', 'chai', 'oolong' ]; * assert.isArray(menu, 'what kind of tea do we want?'); * * @name isArray * @param {Mixed} value * @param {String} message * @api public */ assert.isArray = function (val, msg) { new Assertion(val, msg).to.be.an('array'); }; /** * ### .isNotArray(value, [message]) * * Asserts that `value` is _not_ an array. * * var menu = 'green|chai|oolong'; * assert.isNotArray(menu, 'what kind of tea do we want?'); * * @name isNotArray * @param {Mixed} value * @param {String} message * @api public */ assert.isNotArray = function (val, msg) { new Assertion(val, msg).to.not.be.an('array'); }; /** * ### .isString(value, [message]) * * Asserts that `value` is a string. * * var teaOrder = 'chai'; * assert.isString(teaOrder, 'order placed'); * * @name isString * @param {Mixed} value * @param {String} message * @api public */ assert.isString = function (val, msg) { new Assertion(val, msg).to.be.a('string'); }; /** * ### .isNotString(value, [message]) * * Asserts that `value` is _not_ a string. * * var teaOrder = 4; * assert.isNotString(teaOrder, 'order placed'); * * @name isNotString * @param {Mixed} value * @param {String} message * @api public */ assert.isNotString = function (val, msg) { new Assertion(val, msg).to.not.be.a('string'); }; /** * ### .isNumber(value, [message]) * * Asserts that `value` is a number. * * var cups = 2; * assert.isNumber(cups, 'how many cups'); * * @name isNumber * @param {Number} value * @param {String} message * @api public */ assert.isNumber = function (val, msg) { new Assertion(val, msg).to.be.a('number'); }; /** * ### .isNotNumber(value, [message]) * * Asserts that `value` is _not_ a number. * * var cups = '2 cups please'; * assert.isNotNumber(cups, 'how many cups'); * * @name isNotNumber * @param {Mixed} value * @param {String} message * @api public */ assert.isNotNumber = function (val, msg) { new Assertion(val, msg).to.not.be.a('number'); }; /** * ### .isBoolean(value, [message]) * * Asserts that `value` is a boolean. * * var teaReady = true * , teaServed = false; * * assert.isBoolean(teaReady, 'is the tea ready'); * assert.isBoolean(teaServed, 'has tea been served'); * * @name isBoolean * @param {Mixed} value * @param {String} message * @api public */ assert.isBoolean = function (val, msg) { new Assertion(val, msg).to.be.a('boolean'); }; /** * ### .isNotBoolean(value, [message]) * * Asserts that `value` is _not_ a boolean. * * var teaReady = 'yep' * , teaServed = 'nope'; * * assert.isNotBoolean(teaReady, 'is the tea ready'); * assert.isNotBoolean(teaServed, 'has tea been served'); * * @name isNotBoolean * @param {Mixed} value * @param {String} message * @api public */ assert.isNotBoolean = function (val, msg) { new Assertion(val, msg).to.not.be.a('boolean'); }; /** * ### .typeOf(value, name, [message]) * * Asserts that `value`'s type is `name`, as determined by * `Object.prototype.toString`. * * assert.typeOf({ tea: 'chai' }, 'object', 'we have an object'); * assert.typeOf(['chai', 'jasmine'], 'array', 'we have an array'); * assert.typeOf('tea', 'string', 'we have a string'); * assert.typeOf(/tea/, 'regexp', 'we have a regular expression'); * assert.typeOf(null, 'null', 'we have a null'); * assert.typeOf(undefined, 'undefined', 'we have an undefined'); * * @name typeOf * @param {Mixed} value * @param {String} name * @param {String} message * @api public */ assert.typeOf = function (val, type, msg) { new Assertion(val, msg).to.be.a(type); }; /** * ### .notTypeOf(value, name, [message]) * * Asserts that `value`'s type is _not_ `name`, as determined by * `Object.prototype.toString`. * * assert.notTypeOf('tea', 'number', 'strings are not numbers'); * * @name notTypeOf * @param {Mixed} value * @param {String} typeof name * @param {String} message * @api public */ assert.notTypeOf = function (val, type, msg) { new Assertion(val, msg).to.not.be.a(type); }; /** * ### .instanceOf(object, constructor, [message]) * * Asserts that `value` is an instance of `constructor`. * * var Tea = function (name) { this.name = name; } * , chai = new Tea('chai'); * * assert.instanceOf(chai, Tea, 'chai is an instance of tea'); * * @name instanceOf * @param {Object} object * @param {Constructor} constructor * @param {String} message * @api public */ assert.instanceOf = function (val, type, msg) { new Assertion(val, msg).to.be.instanceOf(type); }; /** * ### .notInstanceOf(object, constructor, [message]) * * Asserts `value` is not an instance of `constructor`. * * var Tea = function (name) { this.name = name; } * , chai = new String('chai'); * * assert.notInstanceOf(chai, Tea, 'chai is not an instance of tea'); * * @name notInstanceOf * @param {Object} object * @param {Constructor} constructor * @param {String} message * @api public */ assert.notInstanceOf = function (val, type, msg) { new Assertion(val, msg).to.not.be.instanceOf(type); }; /** * ### .include(haystack, needle, [message]) * * Asserts that `haystack` includes `needle`. Works * for strings and arrays. * * assert.include('foobar', 'bar', 'foobar contains string "bar"'); * assert.include([ 1, 2, 3 ], 3, 'array contains value'); * * @name include * @param {Array|String} haystack * @param {Mixed} needle * @param {String} message * @api public */ assert.include = function (exp, inc, msg) { var obj = new Assertion(exp, msg); if (Array.isArray(exp)) { obj.to.include(inc); } else if ('string' === typeof exp) { obj.to.contain.string(inc); } }; /** * ### .match(value, regexp, [message]) * * Asserts that `value` matches the regular expression `regexp`. * * assert.match('foobar', /^foo/, 'regexp matches'); * * @name match * @param {Mixed} value * @param {RegExp} regexp * @param {String} message * @api public */ assert.match = function (exp, re, msg) { new Assertion(exp, msg).to.match(re); }; /** * ### .notMatch(value, regexp, [message]) * * Asserts that `value` does not match the regular expression `regexp`. * * assert.notMatch('foobar', /^foo/, 'regexp does not match'); * * @name notMatch * @param {Mixed} value * @param {RegExp} regexp * @param {String} message * @api public */ assert.notMatch = function (exp, re, msg) { new Assertion(exp, msg).to.not.match(re); }; /** * ### .property(object, property, [message]) * * Asserts that `object` has a property named by `property`. * * assert.property({ tea: { green: 'matcha' }}, 'tea'); * * @name property * @param {Object} object * @param {String} property * @param {String} message * @api public */ assert.property = function (obj, prop, msg) { new Assertion(obj, msg).to.have.property(prop); }; /** * ### .notProperty(object, property, [message]) * * Asserts that `object` does _not_ have a property named by `property`. * * assert.notProperty({ tea: { green: 'matcha' }}, 'coffee'); * * @name notProperty * @param {Object} object * @param {String} property * @param {String} message * @api public */ assert.notProperty = function (obj, prop, msg) { new Assertion(obj, msg).to.not.have.property(prop); }; /** * ### .deepProperty(object, property, [message]) * * Asserts that `object` has a property named by `property`, which can be a * string using dot- and bracket-notation for deep reference. * * assert.deepProperty({ tea: { green: 'matcha' }}, 'tea.green'); * * @name deepProperty * @param {Object} object * @param {String} property * @param {String} message * @api public */ assert.deepProperty = function (obj, prop, msg) { new Assertion(obj, msg).to.have.deep.property(prop); }; /** * ### .notDeepProperty(object, property, [message]) * * Asserts that `object` does _not_ have a property named by `property`, which * can be a string using dot- and bracket-notation for deep reference. * * assert.notDeepProperty({ tea: { green: 'matcha' }}, 'tea.oolong'); * * @name notDeepProperty * @param {Object} object * @param {String} property * @param {String} message * @api public */ assert.notDeepProperty = function (obj, prop, msg) { new Assertion(obj, msg).to.not.have.deep.property(prop); }; /** * ### .propertyVal(object, property, value, [message]) * * Asserts that `object` has a property named by `property` with value given * by `value`. * * assert.propertyVal({ tea: 'is good' }, 'tea', 'is good'); * * @name propertyVal * @param {Object} object * @param {String} property * @param {Mixed} value * @param {String} message * @api public */ assert.propertyVal = function (obj, prop, val, msg) { new Assertion(obj, msg).to.have.property(prop, val); }; /** * ### .propertyNotVal(object, property, value, [message]) * * Asserts that `object` has a property named by `property`, but with a value * different from that given by `value`. * * assert.propertyNotVal({ tea: 'is good' }, 'tea', 'is bad'); * * @name propertyNotVal * @param {Object} object * @param {String} property * @param {Mixed} value * @param {String} message * @api public */ assert.propertyNotVal = function (obj, prop, val, msg) { new Assertion(obj, msg).to.not.have.property(prop, val); }; /** * ### .deepPropertyVal(object, property, value, [message]) * * Asserts that `object` has a property named by `property` with value given * by `value`. `property` can use dot- and bracket-notation for deep * reference. * * assert.deepPropertyVal({ tea: { green: 'matcha' }}, 'tea.green', 'matcha'); * * @name deepPropertyVal * @param {Object} object * @param {String} property * @param {Mixed} value * @param {String} message * @api public */ assert.deepPropertyVal = function (obj, prop, val, msg) { new Assertion(obj, msg).to.have.deep.property(prop, val); }; /** * ### .deepPropertyNotVal(object, property, value, [message]) * * Asserts that `object` has a property named by `property`, but with a value * different from that given by `value`. `property` can use dot- and * bracket-notation for deep reference. * * assert.deepPropertyNotVal({ tea: { green: 'matcha' }}, 'tea.green', 'konacha'); * * @name deepPropertyNotVal * @param {Object} object * @param {String} property * @param {Mixed} value * @param {String} message * @api public */ assert.deepPropertyNotVal = function (obj, prop, val, msg) { new Assertion(obj, msg).to.not.have.deep.property(prop, val); }; /** * ### .lengthOf(object, length, [message]) * * Asserts that `object` has a `length` property with the expected value. * * assert.lengthOf([1,2,3], 3, 'array has length of 3'); * assert.lengthOf('foobar', 5, 'string has length of 6'); * * @name lengthOf * @param {Mixed} object * @param {Number} length * @param {String} message * @api public */ assert.lengthOf = function (exp, len, msg) { new Assertion(exp, msg).to.have.length(len); }; /** * ### .throws(function, [constructor/regexp], [message]) * * Asserts that `function` will throw an error that is an instance of * `constructor`, or alternately that it will throw an error with message * matching `regexp`. * * assert.throw(fn, ReferenceError, 'function throws a reference error'); * * @name throws * @alias throw * @alias Throw * @param {Function} function * @param {ErrorConstructor} constructor * @param {RegExp} regexp * @param {String} message * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types * @api public */ assert.Throw = function (fn, type, msg) { if ('string' === typeof type) { msg = type; type = null; } new Assertion(fn, msg).to.Throw(type); }; /** * ### .doesNotThrow(function, [constructor/regexp], [message]) * * Asserts that `function` will _not_ throw an error that is an instance of * `constructor`, or alternately that it will not throw an error with message * matching `regexp`. * * assert.doesNotThrow(fn, Error, 'function does not throw'); * * @name doesNotThrow * @param {Function} function * @param {ErrorConstructor} constructor * @param {RegExp} regexp * @param {String} message * @see https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Error#Error_types * @api public */ assert.doesNotThrow = function (fn, type, msg) { if ('string' === typeof type) { msg = type; type = null; } new Assertion(fn, msg).to.not.Throw(type); }; /** * ### .operator(val1, operator, val2, [message]) * * Compares two values using `operator`. * * assert.operator(1, '<', 2, 'everything is ok'); * assert.operator(1, '>', 2, 'this will fail'); * * @name operator * @param {Mixed} val1 * @param {String} operator * @param {Mixed} val2 * @param {String} message * @api public */ assert.operator = function (val, operator, val2, msg) { if (!~['==', '===', '>', '>=', '<', '<=', '!=', '!=='].indexOf(operator)) { throw new Error('Invalid operator "' + operator + '"'); } var test = new Assertion(eval(val + operator + val2), msg); test.assert( true === flag(test, 'object') , 'expected ' + util.inspect(val) + ' to be ' + operator + ' ' + util.inspect(val2) , 'expected ' + util.inspect(val) + ' to not be ' + operator + ' ' + util.inspect(val2) ); }; /*! * Undocumented / untested */ assert.ifError = function (val, msg) { new Assertion(val, msg).to.not.be.ok; }; /*! * Aliases. */ (function alias(name, as){ assert[as] = assert[name]; return alias; }) ('Throw', 'throw') ('Throw', 'throws'); }; }); // module: chai/interface/assert.js require.register("chai/interface/expect.js", function(module, exports, require){ /*! * chai * Copyright(c) 2011-2012 Jake Luer <[email protected]> * MIT Licensed */ module.exports = function (chai, util) { chai.expect = function (val, message) { return new chai.Assertion(val, message); }; }; }); // module: chai/interface/expect.js require.register("chai/interface/should.js", function(module, exports, require){ /*! * chai * Copyright(c) 2011-2012 Jake Luer <[email protected]> * MIT Licensed */ module.exports = function (chai, util) { var Assertion = chai.Assertion; function loadShould () { // modify Object.prototype to have `should` Object.defineProperty(Object.prototype, 'should', { set: function () {} , get: function(){ if (this instanceof String || this instanceof Number) { return new Assertion(this.constructor(this)); } else if (this instanceof Boolean) { return new Assertion(this == true); } return new Assertion(this); } , configurable: true }); var should = {}; should.equal = function (val1, val2) { new Assertion(val1).to.equal(val2); }; should.Throw = function (fn, errt, errs) { new Assertion(fn).to.Throw(errt, errs); }; should.exist = function (val) { new Assertion(val).to.exist; } // negation should.not = {} should.not.equal = function (val1, val2) { new Assertion(val1).to.not.equal(val2); }; should.not.Throw = function (fn, errt, errs) { new Assertion(fn).to.not.Throw(errt, errs); }; should.not.exist = function (val) { new Assertion(val).to.not.exist; } should['throw'] = should['Throw']; should.not['throw'] = should.not['Throw']; return should; }; chai.should = loadShould; chai.Should = loadShould; }; }); // module: chai/interface/should.js require.register("chai/utils/addChainableMethod.js", function(module, exports, require){ /*! * Chai - addChainingMethod utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /*! * Module dependencies */ var transferFlags = require('./transferFlags'); /** * ### addChainableMethod (ctx, name, method, chainingBehavior) * * Adds a method to an object, such that the method can also be chained. * * utils.addChainableMethod(chai.Assertion.prototype, 'foo', function (str) { * var obj = utils.flag(this, 'object'); * new chai.Assertion(obj).to.be.equal(str); * }); * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.addChainableMethod('foo', fn, chainingBehavior); * * The result can then be used as both a method assertion, executing both `method` and * `chainingBehavior`, or as a language chain, which only executes `chainingBehavior`. * * expect(fooStr).to.be.foo('bar'); * expect(fooStr).to.be.foo.equal('foo'); * * @param {Object} ctx object to which the method is added * @param {String} name of method to add * @param {Function} method function to be used for `name`, when called * @param {Function} chainingBehavior function to be called every time the property is accessed * @name addChainableMethod * @api public */ module.exports = function (ctx, name, method, chainingBehavior) { if (typeof chainingBehavior !== 'function') chainingBehavior = function () { }; Object.defineProperty(ctx, name, { get: function () { chainingBehavior.call(this); var assert = function () { var result = method.apply(this, arguments); return result === undefined ? this : result; }; // Re-enumerate every time to better accomodate plugins. var asserterNames = Object.getOwnPropertyNames(ctx); asserterNames.forEach(function (asserterName) { var pd = Object.getOwnPropertyDescriptor(ctx, asserterName) , functionProtoPD = Object.getOwnPropertyDescriptor(Function.prototype, asserterName); // Avoid trying to overwrite things that we can't, like `length` and `arguments`. if (functionProtoPD && !functionProtoPD.configurable) return; if (asserterName === 'arguments') return; // @see chaijs/chai/issues/69 Object.defineProperty(assert, asserterName, pd); }); transferFlags(this, assert); return assert; } , configurable: true }); }; }); // module: chai/utils/addChainableMethod.js require.register("chai/utils/addMethod.js", function(module, exports, require){ /*! * Chai - addMethod utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /** * ### addMethod (ctx, name, method) * * Adds a method to the prototype of an object. * * utils.addMethod(chai.Assertion.prototype, 'foo', function (str) { * var obj = utils.flag(this, 'object'); * new chai.Assertion(obj).to.be.equal(str); * }); * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.addMethod('foo', fn); * * Then can be used as any other assertion. * * expect(fooStr).to.be.foo('bar'); * * @param {Object} ctx object to which the method is added * @param {String} name of method to add * @param {Function} method function to be used for name * @name addMethod * @api public */ module.exports = function (ctx, name, method) { ctx[name] = function () { var result = method.apply(this, arguments); return result === undefined ? this : result; }; }; }); // module: chai/utils/addMethod.js require.register("chai/utils/addProperty.js", function(module, exports, require){ /*! * Chai - addProperty utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /** * ### addProperty (ctx, name, getter) * * Adds a property to the prototype of an object. * * utils.addProperty(chai.Assertion.prototype, 'foo', function () { * var obj = utils.flag(this, 'object'); * new chai.Assertion(obj).to.be.instanceof(Foo); * }); * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.addProperty('foo', fn); * * Then can be used as any other assertion. * * expect(myFoo).to.be.foo; * * @param {Object} ctx object to which the property is added * @param {String} name of property to add * @param {Function} getter function to be used for name * @name addProperty * @api public */ module.exports = function (ctx, name, getter) { Object.defineProperty(ctx, name, { get: function () { var result = getter.call(this); return result === undefined ? this : result; } , configurable: true }); }; }); // module: chai/utils/addProperty.js require.register("chai/utils/eql.js", function(module, exports, require){ // This is directly from Node.js assert // https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/assert.js module.exports = _deepEqual; // For browser implementation if (!Buffer) { var Buffer = { isBuffer: function () { return false; } }; } function _deepEqual(actual, expected) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (Buffer.isBuffer(actual) && Buffer.isBuffer(expected)) { if (actual.length != expected.length) return false; for (var i = 0; i < actual.length; i++) { if (actual[i] !== expected[i]) return false; } return true; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (actual instanceof Date && expected instanceof Date) { return actual.getTime() === expected.getTime(); // 7.3. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if (typeof actual != 'object' && typeof expected != 'object') { return actual === expected; // 7.4. For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else { return objEquiv(actual, expected); } } function isUndefinedOrNull(value) { return value === null || value === undefined; } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b) { if (isUndefinedOrNull(a) || isUndefinedOrNull(b)) return false; // an identical 'prototype' property. if (a.prototype !== b.prototype) return false; //~~~I've managed to break Object.keys through screwy arguments passing. // Converting to array solves the problem. if (isArguments(a)) { if (!isArguments(b)) { return false; } a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b); } try { var ka = Object.keys(a), kb = Object.keys(b), key, i; } catch (e) {//happens when one is a string literal and the other isn't return false; } // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length != kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] != kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key])) return false; } return true; } }); // module: chai/utils/eql.js require.register("chai/utils/flag.js", function(module, exports, require){ /*! * Chai - flag utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /** * ### flag(object ,key, [value]) * * Get or set a flag value on an object. If a * value is provided it will be set, else it will * return the currently set value or `undefined` if * the value is not set. * * utils.flag(this, 'foo', 'bar'); // setter * utils.flag(this, 'foo'); // getter, returns `bar` * * @param {Object} object (constructed Assertion * @param {String} key * @param {Mixed} value (optional) * @name flag * @api private */ module.exports = function (obj, key, value) { var flags = obj.__flags || (obj.__flags = Object.create(null)); if (arguments.length === 3) { flags[key] = value; } else { return flags[key]; } }; }); // module: chai/utils/flag.js require.register("chai/utils/getActual.js", function(module, exports, require){ /*! * Chai - getActual utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /** * # getActual(object, [actual]) * * Returns the `actual` value for an Assertion * * @param {Object} object (constructed Assertion) * @param {Arguments} chai.Assertion.prototype.assert arguments */ module.exports = function (obj, args) { var actual = args[4]; return 'undefined' !== actual ? actual : obj.obj; }; }); // module: chai/utils/getActual.js require.register("chai/utils/getMessage.js", function(module, exports, require){ /*! * Chai - message composition utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /*! * Module dependancies */ var flag = require('./flag') , getActual = require('./getActual') , inspect = require('./inspect'); /** * # getMessage(object, message, negateMessage) * * Construct the error message based on flags * and template tags. Template tags will return * a stringified inspection of the object referenced. * * Messsage template tags: * - `#{this}` current asserted object * - `#{act}` actual value * - `#{exp}` expected value * * @param {Object} object (constructed Assertion) * @param {Arguments} chai.Assertion.prototype.assert arguments */ module.exports = function (obj, args) { var negate = flag(obj, 'negate') , val = flag(obj, 'object') , expected = args[3] , actual = getActual(obj, args) , msg = negate ? args[2] : args[1] , flagMsg = flag(obj, 'message'); msg = msg || ''; msg = msg .replace(/#{this}/g, inspect(val)) .replace(/#{act}/g, inspect(actual)) .replace(/#{exp}/g, inspect(expected)); return flagMsg ? flagMsg + ': ' + msg : msg; }; }); // module: chai/utils/getMessage.js require.register("chai/utils/getName.js", function(module, exports, require){ /*! * Chai - getName utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /** * # getName(func) * * Gets the name of a function, in a cross-browser way. * * @param {Function} a function (usually a constructor) */ module.exports = function (func) { if (func.name) return func.name; var match = /^\s?function ([^(]*)\(/.exec(func); return match && match[1] ? match[1] : ""; }; }); // module: chai/utils/getName.js require.register("chai/utils/getPathValue.js", function(module, exports, require){ /*! * Chai - getPathValue utility * Copyright(c) 2012 Jake Luer <[email protected]> * @see https://github.com/logicalparadox/filtr * MIT Licensed */ /** * ### .getPathValue(path, object) * * This allows the retrieval of values in an * object given a string path. * * var obj = { * prop1: { * arr: ['a', 'b', 'c'] * , str: 'Hello' * } * , prop2: { * arr: [ { nested: 'Universe' } ] * , str: 'Hello again!' * } * } * * The following would be the results. * * getPathValue('prop1.str', obj); // Hello * getPathValue('prop1.att[2]', obj); // b * getPathValue('prop2.arr[0].nested', obj); // Universe * * @param {String} path * @param {Object} object * @returns {Object} value or `undefined` * @name getPathValue * @api public */ var getPathValue = module.exports = function (path, obj) { var parsed = parsePath(path); return _getPathValue(parsed, obj); }; /*! * ## parsePath(path) * * Helper function used to parse string object * paths. Use in conjunction with `_getPathValue`. * * var parsed = parsePath('myobject.property.subprop'); * * ### Paths: * * * Can be as near infinitely deep and nested * * Arrays are also valid using the formal `myobject.document[3].property`. * * @param {String} path * @returns {Object} parsed * @api private */ function parsePath (path) { var str = path.replace(/\[/g, '.[') , parts = str.match(/(\\\.|[^.]+?)+/g); return parts.map(function (value) { var re = /\[(\d+)\]$/ , mArr = re.exec(value) if (mArr) return { i: parseFloat(mArr[1]) }; else return { p: value }; }); }; /*! * ## _getPathValue(parsed, obj) * * Helper companion function for `.parsePath` that returns * the value located at the parsed address. * * var value = getPathValue(parsed, obj); * * @param {Object} parsed definition from `parsePath`. * @param {Object} object to search against * @returns {Object|Undefined} value * @api private */ function _getPathValue (parsed, obj) { var tmp = obj , res; for (var i = 0, l = parsed.length; i < l; i++) { var part = parsed[i]; if (tmp) { if ('undefined' !== typeof part.p) tmp = tmp[part.p]; else if ('undefined' !== typeof part.i) tmp = tmp[part.i]; if (i == (l - 1)) res = tmp; } else { res = undefined; } } return res; }; }); // module: chai/utils/getPathValue.js require.register("chai/utils/index.js", function(module, exports, require){ /*! * chai * Copyright(c) 2011 Jake Luer <[email protected]> * MIT Licensed */ /*! * Main exports */ var exports = module.exports = {}; /*! * test utility */ exports.test = require('./test'); /*! * message utility */ exports.getMessage = require('./getMessage'); /*! * actual utility */ exports.getActual = require('./getActual'); /*! * Inspect util */ exports.inspect = require('./inspect'); /*! * Flag utility */ exports.flag = require('./flag'); /*! * Flag transferring utility */ exports.transferFlags = require('./transferFlags'); /*! * Deep equal utility */ exports.eql = require('./eql'); /*! * Deep path value */ exports.getPathValue = require('./getPathValue'); /*! * Function name */ exports.getName = require('./getName'); /*! * add Property */ exports.addProperty = require('./addProperty'); /*! * add Method */ exports.addMethod = require('./addMethod'); /*! * overwrite Property */ exports.overwriteProperty = require('./overwriteProperty'); /*! * overwrite Method */ exports.overwriteMethod = require('./overwriteMethod'); /*! * Add a chainable method */ exports.addChainableMethod = require('./addChainableMethod'); }); // module: chai/utils/index.js require.register("chai/utils/inspect.js", function(module, exports, require){ // This is (almost) directly from Node.js utils // https://github.com/joyent/node/blob/f8c335d0caf47f16d31413f89aa28eda3878e3aa/lib/util.js var getName = require('./getName'); module.exports = inspect; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Boolean} showHidden Flag that shows hidden (not enumerable) * properties of objects. * @param {Number} depth Depth in which to descend in object. Default is 2. * @param {Boolean} colors Flag to turn on ANSI escape codes to color the * output. Default is false (no coloring). */ function inspect(obj, showHidden, depth, colors) { var ctx = { showHidden: showHidden, seen: [], stylize: function (str) { return str; } }; return formatValue(ctx, obj, (typeof depth === 'undefined' ? 2 : depth)); } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (value && typeof value.inspect === 'function' && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { return value.inspect(recurseTimes); } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var visibleKeys = Object.keys(value); var keys = ctx.showHidden ? Object.getOwnPropertyNames(value) : visibleKeys; // Some type of object without properties can be shortcutted. // In IE, errors have a single `stack` property, or if they are vanilla `Error`, // a `stack` plus `description` property; ignore those for consistency. if (keys.length === 0 || (isError(value) && ( (keys.length === 1 && keys[0] === 'stack') || (keys.length === 2 && keys[0] === 'description' && keys[1] === 'stack') ))) { if (typeof value === 'function') { var name = getName(value); var nameSuffix = name ? ': ' + name : ''; return ctx.stylize('[Function' + nameSuffix + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toUTCString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (typeof value === 'function') { var name = getName(value); var nameSuffix = name ? ': ' + name : ''; base = ' [Function' + nameSuffix + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { return formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { switch (typeof value) { case 'undefined': return ctx.stylize('undefined', 'undefined'); case 'string': var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); case 'number': return ctx.stylize('' + value, 'number'); case 'boolean': return ctx.stylize('' + value, 'boolean'); } // For some reason typeof null is "object", so special case here. if (value === null) { return ctx.stylize('null', 'null'); } } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (Object.prototype.hasOwnProperty.call(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str; if (value.__lookupGetter__) { if (value.__lookupGetter__(key)) { if (value.__lookupSetter__(key)) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (value.__lookupSetter__(key)) { str = ctx.stylize('[Setter]', 'special'); } } } if (visibleKeys.indexOf(key) < 0) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(value[key]) < 0) { if (recurseTimes === null) { str = formatValue(ctx, value[key], null); } else { str = formatValue(ctx, value[key], recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (typeof name === 'undefined') { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } function isArray(ar) { return Array.isArray(ar) || (typeof ar === 'object' && objectToString(ar) === '[object Array]'); } function isRegExp(re) { return typeof re === 'object' && objectToString(re) === '[object RegExp]'; } function isDate(d) { return typeof d === 'object' && objectToString(d) === '[object Date]'; } function isError(e) { return typeof e === 'object' && objectToString(e) === '[object Error]'; } function objectToString(o) { return Object.prototype.toString.call(o); } }); // module: chai/utils/inspect.js require.register("chai/utils/overwriteMethod.js", function(module, exports, require){ /*! * Chai - overwriteMethod utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /** * ### overwriteMethod (ctx, name, fn) * * Overwites an already existing method and provides * access to previous function. Must return function * to be used for name. * * utils.overwriteMethod(chai.Assertion.prototype, 'equal', function (_super) { * return function (str) { * var obj = utils.flag(this, 'object'); * if (obj instanceof Foo) { * new chai.Assertion(obj.value).to.equal(str); * } else { * _super.apply(this, arguments); * } * } * }); * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.overwriteMethod('foo', fn); * * Then can be used as any other assertion. * * expect(myFoo).to.equal('bar'); * * @param {Object} ctx object whose method is to be overwritten * @param {String} name of method to overwrite * @param {Function} method function that returns a function to be used for name * @name overwriteMethod * @api public */ module.exports = function (ctx, name, method) { var _method = ctx[name] , _super = function () { return this; }; if (_method && 'function' === typeof _method) _super = _method; ctx[name] = function () { var result = method(_super).apply(this, arguments); return result === undefined ? this : result; } }; }); // module: chai/utils/overwriteMethod.js require.register("chai/utils/overwriteProperty.js", function(module, exports, require){ /*! * Chai - overwriteProperty utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /** * ### overwriteProperty (ctx, name, fn) * * Overwites an already existing property getter and provides * access to previous value. Must return function to use as getter. * * utils.overwriteProperty(chai.Assertion.prototype, 'ok', function (_super) { * return function () { * var obj = utils.flag(this, 'object'); * if (obj instanceof Foo) { * new chai.Assertion(obj.name).to.equal('bar'); * } else { * _super.call(this); * } * } * }); * * * Can also be accessed directly from `chai.Assertion`. * * chai.Assertion.overwriteProperty('foo', fn); * * Then can be used as any other assertion. * * expect(myFoo).to.be.ok; * * @param {Object} ctx object whose property is to be overwritten * @param {String} name of property to overwrite * @param {Function} getter function that returns a getter function to be used for name * @name overwriteProperty * @api public */ module.exports = function (ctx, name, getter) { var _get = Object.getOwnPropertyDescriptor(ctx, name) , _super = function () {}; if (_get && 'function' === typeof _get.get) _super = _get.get Object.defineProperty(ctx, name, { get: function () { var result = getter(_super).call(this); return result === undefined ? this : result; } , configurable: true }); }; }); // module: chai/utils/overwriteProperty.js require.register("chai/utils/test.js", function(module, exports, require){ /*! * Chai - test utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /*! * Module dependancies */ var flag = require('./flag'); /** * # test(object, expression) * * Test and object for expression. * * @param {Object} object (constructed Assertion) * @param {Arguments} chai.Assertion.prototype.assert arguments */ module.exports = function (obj, args) { var negate = flag(obj, 'negate') , expr = args[0]; return negate ? !expr : expr; }; }); // module: chai/utils/test.js require.register("chai/utils/transferFlags.js", function(module, exports, require){ /*! * Chai - transferFlags utility * Copyright(c) 2012 Jake Luer <[email protected]> * MIT Licensed */ /** * ### transferFlags(assertion, object, includeAll = true) * * Transfer all the flags for `assertion` to `object`. If * `includeAll` is set to `false`, then the base Chai * assertion flags (namely `object`, `ssfi`, and `message`) * will not be transferred. * * * var newAssertion = new Assertion(); * utils.transferFlags(assertion, newAssertion); * * var anotherAsseriton = new Assertion(myObj); * utils.transferFlags(assertion, anotherAssertion, false); * * @param {Assertion} assertion the assertion to transfer the flags from * @param {Object} object the object to transfer the flags too; usually a new assertion * @param {Boolean} includeAll * @name getAllFlags * @api private */ module.exports = function (assertion, object, includeAll) { var flags = assertion.__flags || (assertion.__flags = Object.create(null)); if (!object.__flags) { object.__flags = Object.create(null); } includeAll = arguments.length === 3 ? includeAll : true; for (var flag in flags) { if (includeAll || (flag !== 'object' && flag !== 'ssfi' && flag != 'message')) { object.__flags[flag] = flags[flag]; } } }; }); // module: chai/utils/transferFlags.js return require('chai'); });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace/mode-ejs.js
2,961
ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ { token : "comment", regex : "\\/\\/", next : "line_comment" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "keyword.operator", regex : /--|\+\+|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/", next : "line_comment_regex_allowed" }, { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); return "paren"; } if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction", }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ], }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(JavaScriptHighlightRules, "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var getWrapped = function(selection, selected, opening, closing) { var rowDiff = selection.end.row - selection.start.row; return { text: opening + selected + closing, selection: [ 0, selection.start.column + 1, rowDiff, selection.end.column + (rowDiff ? 0 : 1) ] }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '{', '}'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '(', ')'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '[', ']'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, quote, quote); } else if (!selected) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); var rightChar = line.substring(cursor.column, cursor.column + 1); var token = session.getTokenAt(cursor.row, cursor.column); var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); if (leftChar == "\\" && token && /escape/.test(token.type)) return null; var stringBefore = token && /string|escape/.test(token.type); var stringAfter = !rightToken || /string|escape/.test(rightToken.type); var pair; if (rightChar == quote) { pair = stringBefore !== stringAfter; } else { if (stringBefore && !stringAfter) return null; // wrap string with different quote if (stringBefore && stringAfter) return null; // do not pair quotes inside strings var wordRe = session.$mode.tokenRe; wordRe.lastIndex = 0; var isWordBefore = wordRe.test(leftChar); wordRe.lastIndex = 0; var isWordAfter = wordRe.test(leftChar); if (isWordBefore || isWordAfter) return null; // before or after alphanumeric if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) return null; // there is rightChar and it isn't closing pair = true; } return { text: pair ? quote + quote : "", selection: [1,1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getCursorPosition(); var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": ["manifest"], "head": [], "title": [], "base": ["href", "target"], "link": ["href", "hreflang", "rel", "media", "type", "sizes"], "meta": ["http-equiv", "name", "content", "charset"], "style": ["type", "media", "scoped"], "script": ["charset", "type", "src", "defer", "async"], "noscript": ["href"], "body": ["onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onmessage", "onoffline", "onpopstate", "onredo", "onresize", "onstorage", "onundo", "onunload"], "section": [], "nav": [], "article": ["pubdate"], "aside": [], "h1": [], "h2": [], "h3": [], "h4": [], "h5": [], "h6": [], "header": [], "footer": [], "address": [], "main": [], "p": [], "hr": [], "pre": [], "blockquote": ["cite"], "ol": ["start", "reversed"], "ul": [], "li": ["value"], "dl": [], "dt": [], "dd": [], "figure": [], "figcaption": [], "div": [], "a": ["href", "target", "ping", "rel", "media", "hreflang", "type"], "em": [], "strong": [], "small": [], "s": [], "cite": [], "q": ["cite"], "dfn": [], "abbr": [], "data": [], "time": ["datetime"], "code": [], "var": [], "samp": [], "kbd": [], "sub": [], "sup": [], "i": [], "b": [], "u": [], "mark": [], "ruby": [], "rt": [], "rp": [], "bdi": [], "bdo": [], "span": [], "br": [], "wbr": [], "ins": ["cite", "datetime"], "del": ["cite", "datetime"], "img": ["alt", "src", "height", "width", "usemap", "ismap"], "iframe": ["name", "src", "height", "width", "sandbox", "seamless"], "embed": ["src", "height", "width", "type"], "object": ["param", "data", "type", "height" , "width", "usemap", "name", "form", "classid"], "param": ["name", "value"], "video": ["src", "autobuffer", "autoplay", "loop", "controls", "width", "height", "poster"], "audio": ["src", "autobuffer", "autoplay", "loop", "controls"], "source": ["src", "type", "media"], "track": ["kind", "src", "srclang", "label", "default"], "canvas": ["width", "height"], "map": ["name"], "area": ["shape", "coords", "href", "hreflang", "alt", "target", "media", "rel", "ping", "type"], "svg": [], "math": [], "table": ["summary"], "caption": [], "colgroup": ["span"], "col": ["span"], "tbody": [], "thead": [], "tfoot": [], "tr": [], "td": ["headers", "rowspan", "colspan"], "th": ["headers", "rowspan", "colspan", "scope"], "form": ["accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target"], "fieldset": ["disabled", "form", "name"], "legend": [], "label": ["form", "for"], "input": ["type", "accept", "alt", "autocomplete", "checked", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "list", "max", "maxlength", "min", "multiple", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "width", "files", "value"], "button": ["autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "value", "type"], "select": ["autofocus", "disabled", "form", "multiple", "name", "size"], "datalist": [], "optgroup": ["disabled", "label"], "option": ["disabled", "selected", "label", "value"], "textarea": ["autofocus", "disabled", "form", "maxlength", "name", "placeholder", "readonly", "required", "rows", "cols", "wrap"], "keygen": ["autofocus", "challenge", "disabled", "form", "keytype", "name"], "output": ["for", "form", "name"], "progress": ["value", "max"], "meter": ["value", "min", "max", "low", "high", "optimum"], "details": ["open"], "summary": [], "command": ["type", "label", "icon", "disabled", "checked", "radiogroup", "command"], "menu": ["type", "label"], "dialog": ["open"] }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompetions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompetions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(attributeMap[tagName]); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/ruby_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var constantOtherSymbol = exports.constantOtherSymbol = { token : "constant.other.symbol.ruby", // symbol regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?" }; var qString = exports.qString = { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }; var qqString = exports.qqString = { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }; var tString = exports.tString = { token : "string", // backtick string regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]" }; var constantNumericHex = exports.constantNumericHex = { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b" }; var constantNumericFloat = exports.constantNumericFloat = { token : "constant.numeric", // float regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b" }; var RubyHighlightRules = function() { var builtinFunctions = ( "abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" + "assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" + "assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" + "assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" + "assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" + "assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" + "attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" + "caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" + "exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" + "gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" + "link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" + "p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" + "raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" + "set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" + "throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" + "render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" + "content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" + "fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" + "time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" + "select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" + "file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" + "protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" + "send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" + "validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" + "validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" + "authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" + "filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" + "translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" + "cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" + "has_many|has_one|belongs_to|has_and_belongs_to_many" ); var keywords = ( "alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" + "__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" + "redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield" ); var buildinConstants = ( "true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" + "RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING" ); var builtinVariables = ( "\$DEBUG|\$defout|\$FILENAME|\$LOAD_PATH|\$SAFE|\$stdin|\$stdout|\$stderr|\$VERBOSE|" + "$!|root_url|flash|session|cookies|params|request|response|logger|self" ); var keywordMapper = this.$keywords = this.createKeywordMapper({ "keyword": keywords, "constant.language": buildinConstants, "variable.language": builtinVariables, "support.function": builtinFunctions, "invalid.deprecated": "debugger" // TODO is this a remnant from js mode? }, "identifier"); this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "comment", // multi line comment regex : "^=begin(?:$|\\s.*$)", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, [{ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); return "paren.lparen"; } if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1) return "paren.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.start", regex : /"/, push : [{ token : "constant.language.escape", regex : /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/ }, { token : "paren.start", regex : /\#{/, push : "start" }, { token : "string.end", regex : /"/, next : "pop" }, { defaultToken: "string" }] }, { token : "string.start", regex : /`/, push : [{ token : "constant.language.escape", regex : /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/ }, { token : "paren.start", regex : /\#{/, push : "start" }, { token : "string.end", regex : /`/, next : "pop" }, { defaultToken: "string" }] }, { token : "string.start", regex : /'/, push : [{ token : "constant.language.escape", regex : /\\['\\]/ }, { token : "string.end", regex : /'/, next : "pop" }, { defaultToken: "string" }] }], { token : "text", // namespaces aren't symbols regex : "::" }, { token : "variable.instance", // instance variable regex : "@{1,2}[a-zA-Z_\\d]+" }, { token : "support.class", // class name regex : "[A-Z][a-zA-Z_\\d]+" }, constantOtherSymbol, constantNumericHex, constantNumericFloat, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "punctuation.separator.key-value", regex : "=>" }, { stateName: "heredoc", onMatch : function(value, currentState, stack) { var next = value[2] == '-' ? "indentedHeredoc" : "heredoc"; var tokens = value.split(this.splitRegex); stack.push(next, tokens[3]); return [ {type:"constant", value: tokens[1]}, {type:"string", value: tokens[2]}, {type:"support.class", value: tokens[3]}, {type:"string", value: tokens[4]} ]; }, regex : "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)", rules: { heredoc: [{ onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }], indentedHeredoc: [{ token: "string", regex: "^ +" }, { onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }] } }, { regex : "$", token : "empty", next : function(currentState, stack) { if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc") return stack[0]; return currentState; } }, { token : "string.character", regex : "\\B\\?." }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : "^=end(?:$|\\s.*$)", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ] }; this.normalizeRules(); }; oop.inherits(RubyHighlightRules, TextHighlightRules); exports.RubyHighlightRules = RubyHighlightRules; }); ace.define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != "#") return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != "#") break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent!= -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start"; else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start"; else return ""; }; }).call(FoldMode.prototype); }); ace.define("ace/mode/ruby",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/ruby_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/coffee"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var FoldMode = require("./folding/coffee").FoldMode; var Mode = function() { this.HighlightRules = RubyHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new FoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); var startingClassOrMethod = line.match(/^\s*(class|def|module)\s.*$/); var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/); var startingConditional = line.match(/^\s*(if|else)\s*/) if (match || startingClassOrMethod || startingDoBlock || startingConditional) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return /^\s+(end|else)$/.test(line + input) || this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, session, row) { var line = session.getLine(row); if (/}/.test(line)) return this.$outdent.autoOutdent(session, row); var indent = this.$getIndent(line); var prevLine = session.getLine(row - 1); var prevIndent = this.$getIndent(prevLine); var tab = session.getTabString(); if (prevIndent.length <= indent.length) { if (indent.slice(-tab.length) == tab) session.remove(new Range(row, indent.length-tab.length, row, indent.length)); } }; this.$id = "ace/mode/ruby"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/ejs",["require","exports","module","ace/lib/oop","ace/mode/html_highlight_rules","ace/mode/javascript_highlight_rules","ace/lib/oop","ace/mode/html","ace/mode/javascript","ace/mode/css","ace/mode/ruby"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var EjsHighlightRules = function(start, end) { HtmlHighlightRules.call(this); if (!start) start = "(?:<%|<\\?|{{)"; if (!end) end = "(?:%>|\\?>|}})"; for (var i in this.$rules) { this.$rules[i].unshift({ token : "markup.list.meta.tag", regex : start + "(?![>}])[-=]?", push : "ejs-start" }); } this.embedRules(JavaScriptHighlightRules, "ejs-"); this.$rules["ejs-start"].unshift({ token : "markup.list.meta.tag", regex : "-?" + end, next : "pop" }, { token: "comment", regex: "//.*?" + end, next: "pop" }); this.$rules["ejs-no_regex"].unshift({ token : "markup.list.meta.tag", regex : "-?" + end, next : "pop" }, { token: "comment", regex: "//.*?" + end, next: "pop" }); this.normalizeRules(); }; oop.inherits(EjsHighlightRules, HtmlHighlightRules); exports.EjsHighlightRules = EjsHighlightRules; var oop = require("../lib/oop"); var HtmlMode = require("./html").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var RubyMode = require("./ruby").Mode; var Mode = function() { HtmlMode.call(this); this.HighlightRules = EjsHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode, "ejs-": JavaScriptMode }); }; oop.inherits(Mode, HtmlMode); (function() { this.$id = "ace/mode/ejs"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace/mode-php.js
3,612
ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "animation-fill-mode|alignment-adjust|alignment-baseline|animation-delay|animation-direction|animation-duration|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|animation|appearance|azimuth|backface-visibility|background-attachment|background-break|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|background|baseline-shift|binding|bleed|bookmark-label|bookmark-level|bookmark-state|bookmark-target|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|border|bottom|box-align|box-decoration-break|box-direction|box-flex-group|box-flex|box-lines|box-ordinal-group|box-orient|box-pack|box-shadow|box-sizing|break-after|break-before|break-inside|caption-side|clear|clip|color-profile|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|crop|cue-after|cue-before|cue|cursor|direction|display|dominant-baseline|drop-initial-after-adjust|drop-initial-after-align|drop-initial-before-adjust|drop-initial-before-align|drop-initial-size|drop-initial-value|elevation|empty-cells|fit|fit-position|float-offset|float|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|font|grid-columns|grid-rows|hanging-punctuation|height|hyphenate-after|hyphenate-before|hyphenate-character|hyphenate-lines|hyphenate-resource|hyphens|icon|image-orientation|image-rendering|image-resolution|inline-box-align|left|letter-spacing|line-height|line-stacking-ruby|line-stacking-shift|line-stacking-strategy|line-stacking|list-style-image|list-style-position|list-style-type|list-style|margin-bottom|margin-left|margin-right|margin-top|margin|mark-after|mark-before|mark|marks|marquee-direction|marquee-play-count|marquee-speed|marquee-style|max-height|max-width|min-height|min-width|move-to|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|orphans|outline-color|outline-offset|outline-style|outline-width|outline|overflow-style|overflow-x|overflow-y|overflow|padding-bottom|padding-left|padding-right|padding-top|padding|page-break-after|page-break-before|page-break-inside|page-policy|page|pause-after|pause-before|pause|perspective-origin|perspective|phonemes|pitch-range|pitch|play-during|pointer-events|position|presentation-level|punctuation-trim|quotes|rendering-intent|resize|rest-after|rest-before|rest|richness|right|rotation-point|rotation|ruby-align|ruby-overhang|ruby-position|ruby-span|size|speak-header|speak-numeral|speak-punctuation|speak|speech-rate|stress|string-set|table-layout|target-name|target-new|target-position|target|text-align-last|text-align|text-decoration|text-emphasis|text-height|text-indent|text-justify|text-outline|text-shadow|text-transform|text-wrap|top|transform-origin|transform-style|transform|transition-delay|transition-duration|transition-property|transition-timing-function|transition|unicode-bidi|vertical-align|visibility|voice-balance|voice-duration|voice-family|voice-pitch-range|voice-pitch|voice-rate|voice-stress|voice-volume|volume|white-space-collapse|white-space|widows|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*\\b"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "[0-2][0-7]{0,2}|" + // oct "3[0-6][0-7]?|" + // oct "37[0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ { token : "comment", regex : "\\/\\/", next : "line_comment" }, DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : /\/\*/, next : "comment" }, { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0[xX][0-9a-fA-F]+\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d+(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["punctuation.operator", "support.function"], regex : /(\.)(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : ["punctuation.operator", "support.function.dom"], regex : /(\.)(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : ["punctuation.operator", "support.constant"], regex : /(\.)(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "keyword.operator", regex : /--|\+\+|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\|\||\?\:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment_regex_allowed" }, { token : "comment", regex : "\\/\\/", next : "line_comment_regex_allowed" }, { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment_regex_allowed" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "start"}, {defaultToken : "comment", caseInsensitive: true} ], "line_comment" : [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : "no_regex"}, {defaultToken : "comment", caseInsensitive: true} ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); return "paren"; } if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction", }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ], }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(JavaScriptHighlightRules, "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/php_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules","ace/mode/html_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var PhpLangHighlightRules = function() { var docComment = DocCommentHighlightRules; var builtinFunctions = lang.arrayToMap( ('abs|acos|acosh|addcslashes|addslashes|aggregate|aggregate_info|aggregate_methods|aggregate_methods_by_list|aggregate_methods_by_regexp|' + 'aggregate_properties|aggregate_properties_by_list|aggregate_properties_by_regexp|aggregation_info|amqpconnection|amqpexchange|amqpqueue|' + 'apache_child_terminate|apache_get_modules|apache_get_version|apache_getenv|apache_lookup_uri|apache_note|apache_request_headers|' + 'apache_reset_timeout|apache_response_headers|apache_setenv|apc_add|apc_bin_dump|apc_bin_dumpfile|apc_bin_load|apc_bin_loadfile|' + 'apc_cache_info|apc_cas|apc_clear_cache|apc_compile_file|apc_dec|apc_define_constants|apc_delete|apc_delete_file|apc_exists|apc_fetch|' + 'apc_inc|apc_load_constants|apc_sma_info|apc_store|apciterator|apd_breakpoint|apd_callstack|apd_clunk|apd_continue|apd_croak|' + 'apd_dump_function_table|apd_dump_persistent_resources|apd_dump_regular_resources|apd_echo|apd_get_active_symbols|apd_set_pprof_trace|' + 'apd_set_session|apd_set_session_trace|apd_set_session_trace_socket|appenditerator|array|array_change_key_case|array_chunk|array_combine|' + 'array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_fill_keys|array_filter|' + 'array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|' + 'array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|' + 'array_reduce|array_replace|array_replace_recursive|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|' + 'array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|' + 'array_values|array_walk|array_walk_recursive|arrayaccess|arrayiterator|arrayobject|arsort|asin|asinh|asort|assert|assert_options|atan|' + 'atan2|atanh|audioproperties|badfunctioncallexception|badmethodcallexception|base64_decode|base64_encode|base_convert|basename|' + 'bbcode_add_element|bbcode_add_smiley|bbcode_create|bbcode_destroy|bbcode_parse|bbcode_set_arg_parser|bbcode_set_flags|bcadd|bccomp|bcdiv|' + 'bcmod|bcmul|bcompiler_load|bcompiler_load_exe|bcompiler_parse_class|bcompiler_read|bcompiler_write_class|bcompiler_write_constant|' + 'bcompiler_write_exe_footer|bcompiler_write_file|bcompiler_write_footer|bcompiler_write_function|bcompiler_write_functions_from_file|' + 'bcompiler_write_header|bcompiler_write_included_filename|bcpow|bcpowmod|bcscale|bcsqrt|bcsub|bin2hex|bind_textdomain_codeset|bindec|' + 'bindtextdomain|bson_decode|bson_encode|bumpValue|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|' + 'cachingiterator|cairo|cairo_create|cairo_font_face_get_type|cairo_font_face_status|cairo_font_options_create|cairo_font_options_equal|' + 'cairo_font_options_get_antialias|cairo_font_options_get_hint_metrics|cairo_font_options_get_hint_style|' + 'cairo_font_options_get_subpixel_order|cairo_font_options_hash|cairo_font_options_merge|cairo_font_options_set_antialias|' + 'cairo_font_options_set_hint_metrics|cairo_font_options_set_hint_style|cairo_font_options_set_subpixel_order|cairo_font_options_status|' + 'cairo_format_stride_for_width|cairo_image_surface_create|cairo_image_surface_create_for_data|cairo_image_surface_create_from_png|' + 'cairo_image_surface_get_data|cairo_image_surface_get_format|cairo_image_surface_get_height|cairo_image_surface_get_stride|' + 'cairo_image_surface_get_width|cairo_matrix_create_scale|cairo_matrix_create_translate|cairo_matrix_invert|cairo_matrix_multiply|' + 'cairo_matrix_rotate|cairo_matrix_transform_distance|cairo_matrix_transform_point|cairo_matrix_translate|cairo_pattern_add_color_stop_rgb|' + 'cairo_pattern_add_color_stop_rgba|cairo_pattern_create_for_surface|cairo_pattern_create_linear|cairo_pattern_create_radial|' + 'cairo_pattern_create_rgb|cairo_pattern_create_rgba|cairo_pattern_get_color_stop_count|cairo_pattern_get_color_stop_rgba|' + 'cairo_pattern_get_extend|cairo_pattern_get_filter|cairo_pattern_get_linear_points|cairo_pattern_get_matrix|' + 'cairo_pattern_get_radial_circles|cairo_pattern_get_rgba|cairo_pattern_get_surface|cairo_pattern_get_type|cairo_pattern_set_extend|' + 'cairo_pattern_set_filter|cairo_pattern_set_matrix|cairo_pattern_status|cairo_pdf_surface_create|cairo_pdf_surface_set_size|' + 'cairo_ps_get_levels|cairo_ps_level_to_string|cairo_ps_surface_create|cairo_ps_surface_dsc_begin_page_setup|' + 'cairo_ps_surface_dsc_begin_setup|cairo_ps_surface_dsc_comment|cairo_ps_surface_get_eps|cairo_ps_surface_restrict_to_level|' + 'cairo_ps_surface_set_eps|cairo_ps_surface_set_size|cairo_scaled_font_create|cairo_scaled_font_extents|cairo_scaled_font_get_ctm|' + 'cairo_scaled_font_get_font_face|cairo_scaled_font_get_font_matrix|cairo_scaled_font_get_font_options|cairo_scaled_font_get_scale_matrix|' + 'cairo_scaled_font_get_type|cairo_scaled_font_glyph_extents|cairo_scaled_font_status|cairo_scaled_font_text_extents|' + 'cairo_surface_copy_page|cairo_surface_create_similar|cairo_surface_finish|cairo_surface_flush|cairo_surface_get_content|' + 'cairo_surface_get_device_offset|cairo_surface_get_font_options|cairo_surface_get_type|cairo_surface_mark_dirty|' + 'cairo_surface_mark_dirty_rectangle|cairo_surface_set_device_offset|cairo_surface_set_fallback_resolution|cairo_surface_show_page|' + 'cairo_surface_status|cairo_surface_write_to_png|cairo_svg_surface_create|cairo_svg_surface_restrict_to_version|' + 'cairo_svg_version_to_string|cairoantialias|cairocontent|cairocontext|cairoexception|cairoextend|cairofillrule|cairofilter|cairofontface|' + 'cairofontoptions|cairofontslant|cairofonttype|cairofontweight|cairoformat|cairogradientpattern|cairohintmetrics|cairohintstyle|' + 'cairoimagesurface|cairolineargradient|cairolinecap|cairolinejoin|cairomatrix|cairooperator|cairopath|cairopattern|cairopatterntype|' + 'cairopdfsurface|cairopslevel|cairopssurface|cairoradialgradient|cairoscaledfont|cairosolidpattern|cairostatus|cairosubpixelorder|' + 'cairosurface|cairosurfacepattern|cairosurfacetype|cairosvgsurface|cairosvgversion|cairotoyfontface|cal_days_in_month|cal_from_jd|cal_info|' + 'cal_to_jd|calcul_hmac|calculhmac|call_user_func|call_user_func_array|call_user_method|call_user_method_array|callbackfilteriterator|ceil|' + 'chdb|chdb_create|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_alias|class_exists|class_implements|' + 'class_parents|classkit_import|classkit_method_add|classkit_method_copy|classkit_method_redefine|classkit_method_remove|' + 'classkit_method_rename|clearstatcache|clone|closedir|closelog|collator|com|com_addref|com_create_guid|com_event_sink|com_get|' + 'com_get_active_object|com_invoke|com_isenum|com_load|com_load_typelib|com_message_pump|com_print_typeinfo|com_propget|com_propput|' + 'com_propset|com_release|com_set|compact|connection_aborted|connection_status|connection_timeout|constant|construct|construct|construct|' + 'convert_cyr_string|convert_uudecode|convert_uuencode|copy|cos|cosh|count|count_chars|countable|counter_bump|counter_bump_value|' + 'counter_create|counter_get|counter_get_meta|counter_get_named|counter_get_value|counter_reset|counter_reset_value|crack_check|' + 'crack_closedict|crack_getlastmessage|crack_opendict|crc32|create_function|crypt|ctype_alnum|ctype_alpha|ctype_cntrl|ctype_digit|' + 'ctype_graph|ctype_lower|ctype_print|ctype_punct|ctype_space|ctype_upper|ctype_xdigit|cubrid_affected_rows|cubrid_bind|' + 'cubrid_client_encoding|cubrid_close|cubrid_close_prepare|cubrid_close_request|cubrid_col_get|cubrid_col_size|cubrid_column_names|' + 'cubrid_column_types|cubrid_commit|cubrid_connect|cubrid_connect_with_url|cubrid_current_oid|cubrid_data_seek|cubrid_db_name|' + 'cubrid_disconnect|cubrid_drop|cubrid_errno|cubrid_error|cubrid_error_code|cubrid_error_code_facility|cubrid_error_msg|cubrid_execute|' + 'cubrid_fetch|cubrid_fetch_array|cubrid_fetch_assoc|cubrid_fetch_field|cubrid_fetch_lengths|cubrid_fetch_object|cubrid_fetch_row|' + 'cubrid_field_flags|cubrid_field_len|cubrid_field_name|cubrid_field_seek|cubrid_field_table|cubrid_field_type|cubrid_free_result|' + 'cubrid_get|cubrid_get_autocommit|cubrid_get_charset|cubrid_get_class_name|cubrid_get_client_info|cubrid_get_db_parameter|' + 'cubrid_get_server_info|cubrid_insert_id|cubrid_is_instance|cubrid_list_dbs|cubrid_load_from_glo|cubrid_lob_close|cubrid_lob_export|' + 'cubrid_lob_get|cubrid_lob_send|cubrid_lob_size|cubrid_lock_read|cubrid_lock_write|cubrid_move_cursor|cubrid_new_glo|cubrid_next_result|' + 'cubrid_num_cols|cubrid_num_fields|cubrid_num_rows|cubrid_ping|cubrid_prepare|cubrid_put|cubrid_query|cubrid_real_escape_string|' + 'cubrid_result|cubrid_rollback|cubrid_save_to_glo|cubrid_schema|cubrid_send_glo|cubrid_seq_drop|cubrid_seq_insert|cubrid_seq_put|' + 'cubrid_set_add|cubrid_set_autocommit|cubrid_set_db_parameter|cubrid_set_drop|cubrid_unbuffered_query|cubrid_version|curl_close|' + 'curl_copy_handle|curl_errno|curl_error|curl_exec|curl_getinfo|curl_init|curl_multi_add_handle|curl_multi_close|curl_multi_exec|' + 'curl_multi_getcontent|curl_multi_info_read|curl_multi_init|curl_multi_remove_handle|curl_multi_select|curl_setopt|curl_setopt_array|' + 'curl_version|current|cyrus_authenticate|cyrus_bind|cyrus_close|cyrus_connect|cyrus_query|cyrus_unbind|date|date_add|date_create|' + 'date_create_from_format|date_date_set|date_default_timezone_get|date_default_timezone_set|date_diff|date_format|date_get_last_errors|' + 'date_interval_create_from_date_string|date_interval_format|date_isodate_set|date_modify|date_offset_get|date_parse|date_parse_from_format|' + 'date_sub|date_sun_info|date_sunrise|date_sunset|date_time_set|date_timestamp_get|date_timestamp_set|date_timezone_get|date_timezone_set|' + 'dateinterval|dateperiod|datetime|datetimezone|db2_autocommit|db2_bind_param|db2_client_info|db2_close|db2_column_privileges|db2_columns|' + 'db2_commit|db2_conn_error|db2_conn_errormsg|db2_connect|db2_cursor_type|db2_escape_string|db2_exec|db2_execute|db2_fetch_array|' + 'db2_fetch_assoc|db2_fetch_both|db2_fetch_object|db2_fetch_row|db2_field_display_size|db2_field_name|db2_field_num|db2_field_precision|' + 'db2_field_scale|db2_field_type|db2_field_width|db2_foreign_keys|db2_free_result|db2_free_stmt|db2_get_option|db2_last_insert_id|' + 'db2_lob_read|db2_next_result|db2_num_fields|db2_num_rows|db2_pclose|db2_pconnect|db2_prepare|db2_primary_keys|db2_procedure_columns|' + 'db2_procedures|db2_result|db2_rollback|db2_server_info|db2_set_option|db2_special_columns|db2_statistics|db2_stmt_error|db2_stmt_errormsg|' + 'db2_table_privileges|db2_tables|dba_close|dba_delete|dba_exists|dba_fetch|dba_firstkey|dba_handlers|dba_insert|dba_key_split|dba_list|' + 'dba_nextkey|dba_open|dba_optimize|dba_popen|dba_replace|dba_sync|dbase_add_record|dbase_close|dbase_create|dbase_delete_record|' + 'dbase_get_header_info|dbase_get_record|dbase_get_record_with_names|dbase_numfields|dbase_numrecords|dbase_open|dbase_pack|' + 'dbase_replace_record|dbplus_add|dbplus_aql|dbplus_chdir|dbplus_close|dbplus_curr|dbplus_errcode|dbplus_errno|dbplus_find|dbplus_first|' + 'dbplus_flush|dbplus_freealllocks|dbplus_freelock|dbplus_freerlocks|dbplus_getlock|dbplus_getunique|dbplus_info|dbplus_last|dbplus_lockrel|' + 'dbplus_next|dbplus_open|dbplus_prev|dbplus_rchperm|dbplus_rcreate|dbplus_rcrtexact|dbplus_rcrtlike|dbplus_resolve|dbplus_restorepos|' + 'dbplus_rkeys|dbplus_ropen|dbplus_rquery|dbplus_rrename|dbplus_rsecindex|dbplus_runlink|dbplus_rzap|dbplus_savepos|dbplus_setindex|' + 'dbplus_setindexbynumber|dbplus_sql|dbplus_tcl|dbplus_tremove|dbplus_undo|dbplus_undoprepare|dbplus_unlockrel|dbplus_unselect|' + 'dbplus_update|dbplus_xlockrel|dbplus_xunlockrel|dbx_close|dbx_compare|dbx_connect|dbx_error|dbx_escape_string|dbx_fetch_row|dbx_query|' + 'dbx_sort|dcgettext|dcngettext|deaggregate|debug_backtrace|debug_print_backtrace|debug_zval_dump|decbin|dechex|decoct|define|' + 'define_syslog_variables|defined|deg2rad|delete|dgettext|die|dio_close|dio_fcntl|dio_open|dio_read|dio_seek|dio_stat|dio_tcsetattr|' + 'dio_truncate|dio_write|dir|directoryiterator|dirname|disk_free_space|disk_total_space|diskfreespace|dl|dngettext|dns_check_record|' + 'dns_get_mx|dns_get_record|dom_import_simplexml|domainexception|domattr|domattribute_name|domattribute_set_value|domattribute_specified|' + 'domattribute_value|domcharacterdata|domcomment|domdocument|domdocument_add_root|domdocument_create_attribute|' + 'domdocument_create_cdata_section|domdocument_create_comment|domdocument_create_element|domdocument_create_element_ns|' + 'domdocument_create_entity_reference|domdocument_create_processing_instruction|domdocument_create_text_node|domdocument_doctype|' + 'domdocument_document_element|domdocument_dump_file|domdocument_dump_mem|domdocument_get_element_by_id|domdocument_get_elements_by_tagname|' + 'domdocument_html_dump_mem|domdocument_xinclude|domdocumentfragment|domdocumenttype|domdocumenttype_entities|' + 'domdocumenttype_internal_subset|domdocumenttype_name|domdocumenttype_notations|domdocumenttype_public_id|domdocumenttype_system_id|' + 'domelement|domelement_get_attribute|domelement_get_attribute_node|domelement_get_elements_by_tagname|domelement_has_attribute|' + 'domelement_remove_attribute|domelement_set_attribute|domelement_set_attribute_node|domelement_tagname|domentity|domentityreference|' + 'domexception|domimplementation|domnamednodemap|domnode|domnode_add_namespace|domnode_append_child|domnode_append_sibling|' + 'domnode_attributes|domnode_child_nodes|domnode_clone_node|domnode_dump_node|domnode_first_child|domnode_get_content|' + 'domnode_has_attributes|domnode_has_child_nodes|domnode_insert_before|domnode_is_blank_node|domnode_last_child|domnode_next_sibling|' + 'domnode_node_name|domnode_node_type|domnode_node_value|domnode_owner_document|domnode_parent_node|domnode_prefix|domnode_previous_sibling|' + 'domnode_remove_child|domnode_replace_child|domnode_replace_node|domnode_set_content|domnode_set_name|domnode_set_namespace|' + 'domnode_unlink_node|domnodelist|domnotation|domprocessinginstruction|domprocessinginstruction_data|domprocessinginstruction_target|' + 'domtext|domxml_new_doc|domxml_open_file|domxml_open_mem|domxml_version|domxml_xmltree|domxml_xslt_stylesheet|domxml_xslt_stylesheet_doc|' + 'domxml_xslt_stylesheet_file|domxml_xslt_version|domxpath|domxsltstylesheet_process|domxsltstylesheet_result_dump_file|' + 'domxsltstylesheet_result_dump_mem|dotnet|dotnet_load|doubleval|each|easter_date|easter_days|echo|empty|emptyiterator|' + 'enchant_broker_describe|enchant_broker_dict_exists|enchant_broker_free|enchant_broker_free_dict|enchant_broker_get_error|' + 'enchant_broker_init|enchant_broker_list_dicts|enchant_broker_request_dict|enchant_broker_request_pwl_dict|enchant_broker_set_ordering|' + 'enchant_dict_add_to_personal|enchant_dict_add_to_session|enchant_dict_check|enchant_dict_describe|enchant_dict_get_error|' + 'enchant_dict_is_in_session|enchant_dict_quick_check|enchant_dict_store_replacement|enchant_dict_suggest|end|ereg|ereg_replace|eregi|' + 'eregi_replace|error_get_last|error_log|error_reporting|errorexception|escapeshellarg|escapeshellcmd|eval|event_add|event_base_free|' + 'event_base_loop|event_base_loopbreak|event_base_loopexit|event_base_new|event_base_priority_init|event_base_set|event_buffer_base_set|' + 'event_buffer_disable|event_buffer_enable|event_buffer_fd_set|event_buffer_free|event_buffer_new|event_buffer_priority_set|' + 'event_buffer_read|event_buffer_set_callback|event_buffer_timeout_set|event_buffer_watermark_set|event_buffer_write|event_del|event_free|' + 'event_new|event_set|exception|exec|exif_imagetype|exif_read_data|exif_tagname|exif_thumbnail|exit|exp|expect_expectl|expect_popen|explode|' + 'expm1|export|export|extension_loaded|extract|ezmlm_hash|fam_cancel_monitor|fam_close|fam_monitor_collection|fam_monitor_directory|' + 'fam_monitor_file|fam_next_event|fam_open|fam_pending|fam_resume_monitor|fam_suspend_monitor|fbsql_affected_rows|fbsql_autocommit|' + 'fbsql_blob_size|fbsql_change_user|fbsql_clob_size|fbsql_close|fbsql_commit|fbsql_connect|fbsql_create_blob|fbsql_create_clob|' + 'fbsql_create_db|fbsql_data_seek|fbsql_database|fbsql_database_password|fbsql_db_query|fbsql_db_status|fbsql_drop_db|fbsql_errno|' + 'fbsql_error|fbsql_fetch_array|fbsql_fetch_assoc|fbsql_fetch_field|fbsql_fetch_lengths|fbsql_fetch_object|fbsql_fetch_row|' + 'fbsql_field_flags|fbsql_field_len|fbsql_field_name|fbsql_field_seek|fbsql_field_table|fbsql_field_type|fbsql_free_result|' + 'fbsql_get_autostart_info|fbsql_hostname|fbsql_insert_id|fbsql_list_dbs|fbsql_list_fields|fbsql_list_tables|fbsql_next_result|' + 'fbsql_num_fields|fbsql_num_rows|fbsql_password|fbsql_pconnect|fbsql_query|fbsql_read_blob|fbsql_read_clob|fbsql_result|fbsql_rollback|' + 'fbsql_rows_fetched|fbsql_select_db|fbsql_set_characterset|fbsql_set_lob_mode|fbsql_set_password|fbsql_set_transaction|fbsql_start_db|' + 'fbsql_stop_db|fbsql_table_name|fbsql_tablename|fbsql_username|fbsql_warnings|fclose|fdf_add_doc_javascript|fdf_add_template|fdf_close|' + 'fdf_create|fdf_enum_values|fdf_errno|fdf_error|fdf_get_ap|fdf_get_attachment|fdf_get_encoding|fdf_get_file|fdf_get_flags|fdf_get_opt|' + 'fdf_get_status|fdf_get_value|fdf_get_version|fdf_header|fdf_next_field_name|fdf_open|fdf_open_string|fdf_remove_item|fdf_save|' + 'fdf_save_string|fdf_set_ap|fdf_set_encoding|fdf_set_file|fdf_set_flags|fdf_set_javascript_action|fdf_set_on_import_javascript|fdf_set_opt|' + 'fdf_set_status|fdf_set_submit_form_action|fdf_set_target_frame|fdf_set_value|fdf_set_version|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file|' + 'file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filepro|' + 'filepro_fieldcount|filepro_fieldname|filepro_fieldtype|filepro_fieldwidth|filepro_retrieve|filepro_rowcount|filesize|filesystemiterator|' + 'filetype|filter_has_var|filter_id|filter_input|filter_input_array|filter_list|filter_var|filter_var_array|filteriterator|finfo_buffer|' + 'finfo_close|finfo_file|finfo_open|finfo_set_flags|floatval|flock|floor|flush|fmod|fnmatch|fopen|forward_static_call|' + 'forward_static_call_array|fpassthru|fprintf|fputcsv|fputs|fread|frenchtojd|fribidi_log2vis|fscanf|fseek|fsockopen|fstat|ftell|ftok|' + 'ftp_alloc|ftp_cdup|ftp_chdir|ftp_chmod|ftp_close|ftp_connect|ftp_delete|ftp_exec|ftp_fget|ftp_fput|ftp_get|ftp_get_option|ftp_login|' + 'ftp_mdtm|ftp_mkdir|ftp_nb_continue|ftp_nb_fget|ftp_nb_fput|ftp_nb_get|ftp_nb_put|ftp_nlist|ftp_pasv|ftp_put|ftp_pwd|ftp_quit|ftp_raw|' + 'ftp_rawlist|ftp_rename|ftp_rmdir|ftp_set_option|ftp_site|ftp_size|ftp_ssl_connect|ftp_systype|ftruncate|func_get_arg|func_get_args|' + 'func_num_args|function_exists|fwrite|gc_collect_cycles|gc_disable|gc_enable|gc_enabled|gd_info|gearmanclient|gearmanjob|gearmantask|' + 'gearmanworker|geoip_continent_code_by_name|geoip_country_code3_by_name|geoip_country_code_by_name|geoip_country_name_by_name|' + 'geoip_database_info|geoip_db_avail|geoip_db_filename|geoip_db_get_all_info|geoip_id_by_name|geoip_isp_by_name|geoip_org_by_name|' + 'geoip_record_by_name|geoip_region_by_name|geoip_region_name_by_code|geoip_time_zone_by_country_and_region|getMeta|getNamed|getValue|' + 'get_browser|get_called_class|get_cfg_var|get_class|get_class_methods|get_class_vars|get_current_user|get_declared_classes|' + 'get_declared_interfaces|get_defined_constants|get_defined_functions|get_defined_vars|get_extension_funcs|get_headers|' + 'get_html_translation_table|get_include_path|get_included_files|get_loaded_extensions|get_magic_quotes_gpc|get_magic_quotes_runtime|' + 'get_meta_tags|get_object_vars|get_parent_class|get_required_files|get_resource_type|getallheaders|getconstant|getconstants|getconstructor|' + 'getcwd|getdate|getdefaultproperties|getdoccomment|getendline|getenv|getextension|getextensionname|getfilename|gethostbyaddr|gethostbyname|' + 'gethostbynamel|gethostname|getimagesize|getinterfacenames|getinterfaces|getlastmod|getmethod|getmethods|getmodifiers|getmxrr|getmygid|' + 'getmyinode|getmypid|getmyuid|getname|getnamespacename|getopt|getparentclass|getproperties|getproperty|getprotobyname|getprotobynumber|' + 'getrandmax|getrusage|getservbyname|getservbyport|getshortname|getstartline|getstaticproperties|getstaticpropertyvalue|gettext|' + 'gettimeofday|gettype|glob|globiterator|gmagick|gmagickdraw|gmagickpixel|gmdate|gmmktime|gmp_abs|gmp_add|gmp_and|gmp_clrbit|gmp_cmp|' + 'gmp_com|gmp_div|gmp_div_q|gmp_div_qr|gmp_div_r|gmp_divexact|gmp_fact|gmp_gcd|gmp_gcdext|gmp_hamdist|gmp_init|gmp_intval|gmp_invert|' + 'gmp_jacobi|gmp_legendre|gmp_mod|gmp_mul|gmp_neg|gmp_nextprime|gmp_or|gmp_perfect_square|gmp_popcount|gmp_pow|gmp_powm|gmp_prob_prime|' + 'gmp_random|gmp_scan0|gmp_scan1|gmp_setbit|gmp_sign|gmp_sqrt|gmp_sqrtrem|gmp_strval|gmp_sub|gmp_testbit|gmp_xor|gmstrftime|' + 'gnupg_adddecryptkey|gnupg_addencryptkey|gnupg_addsignkey|gnupg_cleardecryptkeys|gnupg_clearencryptkeys|gnupg_clearsignkeys|gnupg_decrypt|' + 'gnupg_decryptverify|gnupg_encrypt|gnupg_encryptsign|gnupg_export|gnupg_geterror|gnupg_getprotocol|gnupg_import|gnupg_init|gnupg_keyinfo|' + 'gnupg_setarmor|gnupg_seterrormode|gnupg_setsignmode|gnupg_sign|gnupg_verify|gopher_parsedir|grapheme_extract|grapheme_stripos|' + 'grapheme_stristr|grapheme_strlen|grapheme_strpos|grapheme_strripos|grapheme_strrpos|grapheme_strstr|grapheme_substr|gregoriantojd|' + 'gupnp_context_get_host_ip|gupnp_context_get_port|gupnp_context_get_subscription_timeout|gupnp_context_host_path|gupnp_context_new|' + 'gupnp_context_set_subscription_timeout|gupnp_context_timeout_add|gupnp_context_unhost_path|gupnp_control_point_browse_start|' + 'gupnp_control_point_browse_stop|gupnp_control_point_callback_set|gupnp_control_point_new|gupnp_device_action_callback_set|' + 'gupnp_device_info_get|gupnp_device_info_get_service|gupnp_root_device_get_available|gupnp_root_device_get_relative_location|' + 'gupnp_root_device_new|gupnp_root_device_set_available|gupnp_root_device_start|gupnp_root_device_stop|gupnp_service_action_get|' + 'gupnp_service_action_return|gupnp_service_action_return_error|gupnp_service_action_set|gupnp_service_freeze_notify|gupnp_service_info_get|' + 'gupnp_service_info_get_introspection|gupnp_service_introspection_get_state_variable|gupnp_service_notify|gupnp_service_proxy_action_get|' + 'gupnp_service_proxy_action_set|gupnp_service_proxy_add_notify|gupnp_service_proxy_callback_set|gupnp_service_proxy_get_subscribed|' + 'gupnp_service_proxy_remove_notify|gupnp_service_proxy_set_subscribed|gupnp_service_thaw_notify|gzclose|gzcompress|gzdecode|gzdeflate|' + 'gzencode|gzeof|gzfile|gzgetc|gzgets|gzgetss|gzinflate|gzopen|gzpassthru|gzputs|gzread|gzrewind|gzseek|gztell|gzuncompress|gzwrite|' + 'halt_compiler|haruannotation|haruannotation_setborderstyle|haruannotation_sethighlightmode|haruannotation_seticon|' + 'haruannotation_setopened|harudestination|harudestination_setfit|harudestination_setfitb|harudestination_setfitbh|harudestination_setfitbv|' + 'harudestination_setfith|harudestination_setfitr|harudestination_setfitv|harudestination_setxyz|harudoc|harudoc_addpage|' + 'harudoc_addpagelabel|harudoc_construct|harudoc_createoutline|harudoc_getcurrentencoder|harudoc_getcurrentpage|harudoc_getencoder|' + 'harudoc_getfont|harudoc_getinfoattr|harudoc_getpagelayout|harudoc_getpagemode|harudoc_getstreamsize|harudoc_insertpage|harudoc_loadjpeg|' + 'harudoc_loadpng|harudoc_loadraw|harudoc_loadttc|harudoc_loadttf|harudoc_loadtype1|harudoc_output|harudoc_readfromstream|' + 'harudoc_reseterror|harudoc_resetstream|harudoc_save|harudoc_savetostream|harudoc_setcompressionmode|harudoc_setcurrentencoder|' + 'harudoc_setencryptionmode|harudoc_setinfoattr|harudoc_setinfodateattr|harudoc_setopenaction|harudoc_setpagelayout|harudoc_setpagemode|' + 'harudoc_setpagesconfiguration|harudoc_setpassword|harudoc_setpermission|harudoc_usecnsencodings|harudoc_usecnsfonts|' + 'harudoc_usecntencodings|harudoc_usecntfonts|harudoc_usejpencodings|harudoc_usejpfonts|harudoc_usekrencodings|harudoc_usekrfonts|' + 'haruencoder|haruencoder_getbytetype|haruencoder_gettype|haruencoder_getunicode|haruencoder_getwritingmode|haruexception|harufont|' + 'harufont_getascent|harufont_getcapheight|harufont_getdescent|harufont_getencodingname|harufont_getfontname|harufont_gettextwidth|' + 'harufont_getunicodewidth|harufont_getxheight|harufont_measuretext|haruimage|haruimage_getbitspercomponent|haruimage_getcolorspace|' + 'haruimage_getheight|haruimage_getsize|haruimage_getwidth|haruimage_setcolormask|haruimage_setmaskimage|haruoutline|' + 'haruoutline_setdestination|haruoutline_setopened|harupage|harupage_arc|harupage_begintext|harupage_circle|harupage_closepath|' + 'harupage_concat|harupage_createdestination|harupage_createlinkannotation|harupage_createtextannotation|harupage_createurlannotation|' + 'harupage_curveto|harupage_curveto2|harupage_curveto3|harupage_drawimage|harupage_ellipse|harupage_endpath|harupage_endtext|' + 'harupage_eofill|harupage_eofillstroke|harupage_fill|harupage_fillstroke|harupage_getcharspace|harupage_getcmykfill|harupage_getcmykstroke|' + 'harupage_getcurrentfont|harupage_getcurrentfontsize|harupage_getcurrentpos|harupage_getcurrenttextpos|harupage_getdash|' + 'harupage_getfillingcolorspace|harupage_getflatness|harupage_getgmode|harupage_getgrayfill|harupage_getgraystroke|harupage_getheight|' + 'harupage_gethorizontalscaling|harupage_getlinecap|harupage_getlinejoin|harupage_getlinewidth|harupage_getmiterlimit|harupage_getrgbfill|' + 'harupage_getrgbstroke|harupage_getstrokingcolorspace|harupage_gettextleading|harupage_gettextmatrix|harupage_gettextrenderingmode|' + 'harupage_gettextrise|harupage_gettextwidth|harupage_gettransmatrix|harupage_getwidth|harupage_getwordspace|harupage_lineto|' + 'harupage_measuretext|harupage_movetextpos|harupage_moveto|harupage_movetonextline|harupage_rectangle|harupage_setcharspace|' + 'harupage_setcmykfill|harupage_setcmykstroke|harupage_setdash|harupage_setflatness|harupage_setfontandsize|harupage_setgrayfill|' + 'harupage_setgraystroke|harupage_setheight|harupage_sethorizontalscaling|harupage_setlinecap|harupage_setlinejoin|harupage_setlinewidth|' + 'harupage_setmiterlimit|harupage_setrgbfill|harupage_setrgbstroke|harupage_setrotate|harupage_setsize|harupage_setslideshow|' + 'harupage_settextleading|harupage_settextmatrix|harupage_settextrenderingmode|harupage_settextrise|harupage_setwidth|harupage_setwordspace|' + 'harupage_showtext|harupage_showtextnextline|harupage_stroke|harupage_textout|harupage_textrect|hasconstant|hash|hash_algos|hash_copy|' + 'hash_file|hash_final|hash_hmac|hash_hmac_file|hash_init|hash_update|hash_update_file|hash_update_stream|hasmethod|hasproperty|header|' + 'header_register_callback|header_remove|headers_list|headers_sent|hebrev|hebrevc|hex2bin|hexdec|highlight_file|highlight_string|' + 'html_entity_decode|htmlentities|htmlspecialchars|htmlspecialchars_decode|http_build_cookie|http_build_query|http_build_str|http_build_url|' + 'http_cache_etag|http_cache_last_modified|http_chunked_decode|http_date|http_deflate|http_get|http_get_request_body|' + 'http_get_request_body_stream|http_get_request_headers|http_head|http_inflate|http_match_etag|http_match_modified|' + 'http_match_request_header|http_negotiate_charset|http_negotiate_content_type|http_negotiate_language|http_parse_cookie|http_parse_headers|' + 'http_parse_message|http_parse_params|http_persistent_handles_clean|http_persistent_handles_count|http_persistent_handles_ident|' + 'http_post_data|http_post_fields|http_put_data|http_put_file|http_put_stream|http_redirect|http_request|http_request_body_encode|' + 'http_request_method_exists|http_request_method_name|http_request_method_register|http_request_method_unregister|http_response_code|' + 'http_send_content_disposition|http_send_content_type|http_send_data|http_send_file|http_send_last_modified|http_send_status|' + 'http_send_stream|http_support|http_throttle|httpdeflatestream|httpdeflatestream_construct|httpdeflatestream_factory|' + 'httpdeflatestream_finish|httpdeflatestream_flush|httpdeflatestream_update|httpinflatestream|httpinflatestream_construct|' + 'httpinflatestream_factory|httpinflatestream_finish|httpinflatestream_flush|httpinflatestream_update|httpmessage|httpmessage_addheaders|' + 'httpmessage_construct|httpmessage_detach|httpmessage_factory|httpmessage_fromenv|httpmessage_fromstring|httpmessage_getbody|' + 'httpmessage_getheader|httpmessage_getheaders|httpmessage_gethttpversion|httpmessage_getparentmessage|httpmessage_getrequestmethod|' + 'httpmessage_getrequesturl|httpmessage_getresponsecode|httpmessage_getresponsestatus|httpmessage_gettype|httpmessage_guesscontenttype|' + 'httpmessage_prepend|httpmessage_reverse|httpmessage_send|httpmessage_setbody|httpmessage_setheaders|httpmessage_sethttpversion|' + 'httpmessage_setrequestmethod|httpmessage_setrequesturl|httpmessage_setresponsecode|httpmessage_setresponsestatus|httpmessage_settype|' + 'httpmessage_tomessagetypeobject|httpmessage_tostring|httpquerystring|httpquerystring_construct|httpquerystring_get|httpquerystring_mod|' + 'httpquerystring_set|httpquerystring_singleton|httpquerystring_toarray|httpquerystring_tostring|httpquerystring_xlate|httprequest|' + 'httprequest_addcookies|httprequest_addheaders|httprequest_addpostfields|httprequest_addpostfile|httprequest_addputdata|' + 'httprequest_addquerydata|httprequest_addrawpostdata|httprequest_addssloptions|httprequest_clearhistory|httprequest_construct|' + 'httprequest_enablecookies|httprequest_getcontenttype|httprequest_getcookies|httprequest_getheaders|httprequest_gethistory|' + 'httprequest_getmethod|httprequest_getoptions|httprequest_getpostfields|httprequest_getpostfiles|httprequest_getputdata|' + 'httprequest_getputfile|httprequest_getquerydata|httprequest_getrawpostdata|httprequest_getrawrequestmessage|' + 'httprequest_getrawresponsemessage|httprequest_getrequestmessage|httprequest_getresponsebody|httprequest_getresponsecode|' + 'httprequest_getresponsecookies|httprequest_getresponsedata|httprequest_getresponseheader|httprequest_getresponseinfo|' + 'httprequest_getresponsemessage|httprequest_getresponsestatus|httprequest_getssloptions|httprequest_geturl|httprequest_resetcookies|' + 'httprequest_send|httprequest_setcontenttype|httprequest_setcookies|httprequest_setheaders|httprequest_setmethod|httprequest_setoptions|' + 'httprequest_setpostfields|httprequest_setpostfiles|httprequest_setputdata|httprequest_setputfile|httprequest_setquerydata|' + 'httprequest_setrawpostdata|httprequest_setssloptions|httprequest_seturl|httprequestpool|httprequestpool_attach|httprequestpool_construct|' + 'httprequestpool_destruct|httprequestpool_detach|httprequestpool_getattachedrequests|httprequestpool_getfinishedrequests|' + 'httprequestpool_reset|httprequestpool_send|httprequestpool_socketperform|httprequestpool_socketselect|httpresponse|httpresponse_capture|' + 'httpresponse_getbuffersize|httpresponse_getcache|httpresponse_getcachecontrol|httpresponse_getcontentdisposition|' + 'httpresponse_getcontenttype|httpresponse_getdata|httpresponse_getetag|httpresponse_getfile|httpresponse_getgzip|httpresponse_getheader|' + 'httpresponse_getlastmodified|httpresponse_getrequestbody|httpresponse_getrequestbodystream|httpresponse_getrequestheaders|' + 'httpresponse_getstream|httpresponse_getthrottledelay|httpresponse_guesscontenttype|httpresponse_redirect|httpresponse_send|' + 'httpresponse_setbuffersize|httpresponse_setcache|httpresponse_setcachecontrol|httpresponse_setcontentdisposition|' + 'httpresponse_setcontenttype|httpresponse_setdata|httpresponse_setetag|httpresponse_setfile|httpresponse_setgzip|httpresponse_setheader|' + 'httpresponse_setlastmodified|httpresponse_setstream|httpresponse_setthrottledelay|httpresponse_status|hw_array2objrec|hw_changeobject|' + 'hw_children|hw_childrenobj|hw_close|hw_connect|hw_connection_info|hw_cp|hw_deleteobject|hw_docbyanchor|hw_docbyanchorobj|' + 'hw_document_attributes|hw_document_bodytag|hw_document_content|hw_document_setcontent|hw_document_size|hw_dummy|hw_edittext|hw_error|' + 'hw_errormsg|hw_free_document|hw_getanchors|hw_getanchorsobj|hw_getandlock|hw_getchildcoll|hw_getchildcollobj|hw_getchilddoccoll|' + 'hw_getchilddoccollobj|hw_getobject|hw_getobjectbyquery|hw_getobjectbyquerycoll|hw_getobjectbyquerycollobj|hw_getobjectbyqueryobj|' + 'hw_getparents|hw_getparentsobj|hw_getrellink|hw_getremote|hw_getremotechildren|hw_getsrcbydestobj|hw_gettext|hw_getusername|hw_identify|' + 'hw_incollections|hw_info|hw_inscoll|hw_insdoc|hw_insertanchors|hw_insertdocument|hw_insertobject|hw_mapid|hw_modifyobject|hw_mv|' + 'hw_new_document|hw_objrec2array|hw_output_document|hw_pconnect|hw_pipedocument|hw_root|hw_setlinkroot|hw_stat|hw_unlock|hw_who|' + 'hwapi_attribute|hwapi_attribute_key|hwapi_attribute_langdepvalue|hwapi_attribute_value|hwapi_attribute_values|hwapi_checkin|' + 'hwapi_checkout|hwapi_children|hwapi_content|hwapi_content_mimetype|hwapi_content_read|hwapi_copy|hwapi_dbstat|hwapi_dcstat|' + 'hwapi_dstanchors|hwapi_dstofsrcanchor|hwapi_error_count|hwapi_error_reason|hwapi_find|hwapi_ftstat|hwapi_hgcsp|hwapi_hwstat|' + 'hwapi_identify|hwapi_info|hwapi_insert|hwapi_insertanchor|hwapi_insertcollection|hwapi_insertdocument|hwapi_link|hwapi_lock|hwapi_move|' + 'hwapi_new_content|hwapi_object|hwapi_object_assign|hwapi_object_attreditable|hwapi_object_count|hwapi_object_insert|hwapi_object_new|' + 'hwapi_object_remove|hwapi_object_title|hwapi_object_value|hwapi_objectbyanchor|hwapi_parents|hwapi_reason_description|hwapi_reason_type|' + 'hwapi_remove|hwapi_replace|hwapi_setcommittedversion|hwapi_srcanchors|hwapi_srcsofdst|hwapi_unlock|hwapi_user|hwapi_userlist|hypot|' + 'ibase_add_user|ibase_affected_rows|ibase_backup|ibase_blob_add|ibase_blob_cancel|ibase_blob_close|ibase_blob_create|ibase_blob_echo|' + 'ibase_blob_get|ibase_blob_import|ibase_blob_info|ibase_blob_open|ibase_close|ibase_commit|ibase_commit_ret|ibase_connect|ibase_db_info|' + 'ibase_delete_user|ibase_drop_db|ibase_errcode|ibase_errmsg|ibase_execute|ibase_fetch_assoc|ibase_fetch_object|ibase_fetch_row|' + 'ibase_field_info|ibase_free_event_handler|ibase_free_query|ibase_free_result|ibase_gen_id|ibase_maintain_db|ibase_modify_user|' + 'ibase_name_result|ibase_num_fields|ibase_num_params|ibase_param_info|ibase_pconnect|ibase_prepare|ibase_query|ibase_restore|' + 'ibase_rollback|ibase_rollback_ret|ibase_server_info|ibase_service_attach|ibase_service_detach|ibase_set_event_handler|ibase_timefmt|' + 'ibase_trans|ibase_wait_event|iconv|iconv_get_encoding|iconv_mime_decode|iconv_mime_decode_headers|iconv_mime_encode|iconv_set_encoding|' + 'iconv_strlen|iconv_strpos|iconv_strrpos|iconv_substr|id3_get_frame_long_name|id3_get_frame_short_name|id3_get_genre_id|id3_get_genre_list|' + 'id3_get_genre_name|id3_get_tag|id3_get_version|id3_remove_tag|id3_set_tag|id3v2attachedpictureframe|id3v2frame|id3v2tag|idate|' + 'idn_to_ascii|idn_to_unicode|idn_to_utf8|ifx_affected_rows|ifx_blobinfile_mode|ifx_byteasvarchar|ifx_close|ifx_connect|ifx_copy_blob|' + 'ifx_create_blob|ifx_create_char|ifx_do|ifx_error|ifx_errormsg|ifx_fetch_row|ifx_fieldproperties|ifx_fieldtypes|ifx_free_blob|' + 'ifx_free_char|ifx_free_result|ifx_get_blob|ifx_get_char|ifx_getsqlca|ifx_htmltbl_result|ifx_nullformat|ifx_num_fields|ifx_num_rows|' + 'ifx_pconnect|ifx_prepare|ifx_query|ifx_textasvarchar|ifx_update_blob|ifx_update_char|ifxus_close_slob|ifxus_create_slob|ifxus_free_slob|' + 'ifxus_open_slob|ifxus_read_slob|ifxus_seek_slob|ifxus_tell_slob|ifxus_write_slob|ignore_user_abort|iis_add_server|iis_get_dir_security|' + 'iis_get_script_map|iis_get_server_by_comment|iis_get_server_by_path|iis_get_server_rights|iis_get_service_state|iis_remove_server|' + 'iis_set_app_settings|iis_set_dir_security|iis_set_script_map|iis_set_server_rights|iis_start_server|iis_start_service|iis_stop_server|' + 'iis_stop_service|image2wbmp|image_type_to_extension|image_type_to_mime_type|imagealphablending|imageantialias|imagearc|imagechar|' + 'imagecharup|imagecolorallocate|imagecolorallocatealpha|imagecolorat|imagecolorclosest|imagecolorclosestalpha|imagecolorclosesthwb|' + 'imagecolordeallocate|imagecolorexact|imagecolorexactalpha|imagecolormatch|imagecolorresolve|imagecolorresolvealpha|imagecolorset|' + 'imagecolorsforindex|imagecolorstotal|imagecolortransparent|imageconvolution|imagecopy|imagecopymerge|imagecopymergegray|' + 'imagecopyresampled|imagecopyresized|imagecreate|imagecreatefromgd|imagecreatefromgd2|imagecreatefromgd2part|imagecreatefromgif|' + 'imagecreatefromjpeg|imagecreatefrompng|imagecreatefromstring|imagecreatefromwbmp|imagecreatefromxbm|imagecreatefromxpm|' + 'imagecreatetruecolor|imagedashedline|imagedestroy|imageellipse|imagefill|imagefilledarc|imagefilledellipse|imagefilledpolygon|' + 'imagefilledrectangle|imagefilltoborder|imagefilter|imagefontheight|imagefontwidth|imageftbbox|imagefttext|imagegammacorrect|imagegd|' + 'imagegd2|imagegif|imagegrabscreen|imagegrabwindow|imageinterlace|imageistruecolor|imagejpeg|imagelayereffect|imageline|imageloadfont|' + 'imagepalettecopy|imagepng|imagepolygon|imagepsbbox|imagepsencodefont|imagepsextendfont|imagepsfreefont|imagepsloadfont|imagepsslantfont|' + 'imagepstext|imagerectangle|imagerotate|imagesavealpha|imagesetbrush|imagesetpixel|imagesetstyle|imagesetthickness|imagesettile|' + 'imagestring|imagestringup|imagesx|imagesy|imagetruecolortopalette|imagettfbbox|imagettftext|imagetypes|imagewbmp|imagexbm|imagick|' + 'imagick_adaptiveblurimage|imagick_adaptiveresizeimage|imagick_adaptivesharpenimage|imagick_adaptivethresholdimage|imagick_addimage|' + 'imagick_addnoiseimage|imagick_affinetransformimage|imagick_animateimages|imagick_annotateimage|imagick_appendimages|imagick_averageimages|' + 'imagick_blackthresholdimage|imagick_blurimage|imagick_borderimage|imagick_charcoalimage|imagick_chopimage|imagick_clear|imagick_clipimage|' + 'imagick_clippathimage|imagick_clone|imagick_clutimage|imagick_coalesceimages|imagick_colorfloodfillimage|imagick_colorizeimage|' + 'imagick_combineimages|imagick_commentimage|imagick_compareimagechannels|imagick_compareimagelayers|imagick_compareimages|' + 'imagick_compositeimage|imagick_construct|imagick_contrastimage|imagick_contraststretchimage|imagick_convolveimage|imagick_cropimage|' + 'imagick_cropthumbnailimage|imagick_current|imagick_cyclecolormapimage|imagick_decipherimage|imagick_deconstructimages|' + 'imagick_deleteimageartifact|imagick_despeckleimage|imagick_destroy|imagick_displayimage|imagick_displayimages|imagick_distortimage|' + 'imagick_drawimage|imagick_edgeimage|imagick_embossimage|imagick_encipherimage|imagick_enhanceimage|imagick_equalizeimage|' + 'imagick_evaluateimage|imagick_extentimage|imagick_flattenimages|imagick_flipimage|imagick_floodfillpaintimage|imagick_flopimage|' + 'imagick_frameimage|imagick_fximage|imagick_gammaimage|imagick_gaussianblurimage|imagick_getcolorspace|imagick_getcompression|' + 'imagick_getcompressionquality|imagick_getcopyright|imagick_getfilename|imagick_getfont|imagick_getformat|imagick_getgravity|' + 'imagick_gethomeurl|imagick_getimage|imagick_getimagealphachannel|imagick_getimageartifact|imagick_getimagebackgroundcolor|' + 'imagick_getimageblob|imagick_getimageblueprimary|imagick_getimagebordercolor|imagick_getimagechanneldepth|' + 'imagick_getimagechanneldistortion|imagick_getimagechanneldistortions|imagick_getimagechannelextrema|imagick_getimagechannelmean|' + 'imagick_getimagechannelrange|imagick_getimagechannelstatistics|imagick_getimageclipmask|imagick_getimagecolormapcolor|' + 'imagick_getimagecolors|imagick_getimagecolorspace|imagick_getimagecompose|imagick_getimagecompression|imagick_getimagecompressionquality|' + 'imagick_getimagedelay|imagick_getimagedepth|imagick_getimagedispose|imagick_getimagedistortion|imagick_getimageextrema|' + 'imagick_getimagefilename|imagick_getimageformat|imagick_getimagegamma|imagick_getimagegeometry|imagick_getimagegravity|' + 'imagick_getimagegreenprimary|imagick_getimageheight|imagick_getimagehistogram|imagick_getimageindex|imagick_getimageinterlacescheme|' + 'imagick_getimageinterpolatemethod|imagick_getimageiterations|imagick_getimagelength|imagick_getimagemagicklicense|imagick_getimagematte|' + 'imagick_getimagemattecolor|imagick_getimageorientation|imagick_getimagepage|imagick_getimagepixelcolor|imagick_getimageprofile|' + 'imagick_getimageprofiles|imagick_getimageproperties|imagick_getimageproperty|imagick_getimageredprimary|imagick_getimageregion|' + 'imagick_getimagerenderingintent|imagick_getimageresolution|imagick_getimagesblob|imagick_getimagescene|imagick_getimagesignature|' + 'imagick_getimagesize|imagick_getimagetickspersecond|imagick_getimagetotalinkdensity|imagick_getimagetype|imagick_getimageunits|' + 'imagick_getimagevirtualpixelmethod|imagick_getimagewhitepoint|imagick_getimagewidth|imagick_getinterlacescheme|imagick_getiteratorindex|' + 'imagick_getnumberimages|imagick_getoption|imagick_getpackagename|imagick_getpage|imagick_getpixeliterator|imagick_getpixelregioniterator|' + 'imagick_getpointsize|imagick_getquantumdepth|imagick_getquantumrange|imagick_getreleasedate|imagick_getresource|imagick_getresourcelimit|' + 'imagick_getsamplingfactors|imagick_getsize|imagick_getsizeoffset|imagick_getversion|imagick_hasnextimage|imagick_haspreviousimage|' + 'imagick_identifyimage|imagick_implodeimage|imagick_labelimage|imagick_levelimage|imagick_linearstretchimage|imagick_liquidrescaleimage|' + 'imagick_magnifyimage|imagick_mapimage|imagick_mattefloodfillimage|imagick_medianfilterimage|imagick_mergeimagelayers|imagick_minifyimage|' + 'imagick_modulateimage|imagick_montageimage|imagick_morphimages|imagick_mosaicimages|imagick_motionblurimage|imagick_negateimage|' + 'imagick_newimage|imagick_newpseudoimage|imagick_nextimage|imagick_normalizeimage|imagick_oilpaintimage|imagick_opaquepaintimage|' + 'imagick_optimizeimagelayers|imagick_orderedposterizeimage|imagick_paintfloodfillimage|imagick_paintopaqueimage|' + 'imagick_painttransparentimage|imagick_pingimage|imagick_pingimageblob|imagick_pingimagefile|imagick_polaroidimage|imagick_posterizeimage|' + 'imagick_previewimages|imagick_previousimage|imagick_profileimage|imagick_quantizeimage|imagick_quantizeimages|imagick_queryfontmetrics|' + 'imagick_queryfonts|imagick_queryformats|imagick_radialblurimage|imagick_raiseimage|imagick_randomthresholdimage|imagick_readimage|' + 'imagick_readimageblob|imagick_readimagefile|imagick_recolorimage|imagick_reducenoiseimage|imagick_removeimage|imagick_removeimageprofile|' + 'imagick_render|imagick_resampleimage|imagick_resetimagepage|imagick_resizeimage|imagick_rollimage|imagick_rotateimage|' + 'imagick_roundcorners|imagick_sampleimage|imagick_scaleimage|imagick_separateimagechannel|imagick_sepiatoneimage|' + 'imagick_setbackgroundcolor|imagick_setcolorspace|imagick_setcompression|imagick_setcompressionquality|imagick_setfilename|' + 'imagick_setfirstiterator|imagick_setfont|imagick_setformat|imagick_setgravity|imagick_setimage|imagick_setimagealphachannel|' + 'imagick_setimageartifact|imagick_setimagebackgroundcolor|imagick_setimagebias|imagick_setimageblueprimary|imagick_setimagebordercolor|' + 'imagick_setimagechanneldepth|imagick_setimageclipmask|imagick_setimagecolormapcolor|imagick_setimagecolorspace|imagick_setimagecompose|' + 'imagick_setimagecompression|imagick_setimagecompressionquality|imagick_setimagedelay|imagick_setimagedepth|imagick_setimagedispose|' + 'imagick_setimageextent|imagick_setimagefilename|imagick_setimageformat|imagick_setimagegamma|imagick_setimagegravity|' + 'imagick_setimagegreenprimary|imagick_setimageindex|imagick_setimageinterlacescheme|imagick_setimageinterpolatemethod|' + 'imagick_setimageiterations|imagick_setimagematte|imagick_setimagemattecolor|imagick_setimageopacity|imagick_setimageorientation|' + 'imagick_setimagepage|imagick_setimageprofile|imagick_setimageproperty|imagick_setimageredprimary|imagick_setimagerenderingintent|' + 'imagick_setimageresolution|imagick_setimagescene|imagick_setimagetickspersecond|imagick_setimagetype|imagick_setimageunits|' + 'imagick_setimagevirtualpixelmethod|imagick_setimagewhitepoint|imagick_setinterlacescheme|imagick_setiteratorindex|imagick_setlastiterator|' + 'imagick_setoption|imagick_setpage|imagick_setpointsize|imagick_setresolution|imagick_setresourcelimit|imagick_setsamplingfactors|' + 'imagick_setsize|imagick_setsizeoffset|imagick_settype|imagick_shadeimage|imagick_shadowimage|imagick_sharpenimage|imagick_shaveimage|' + 'imagick_shearimage|imagick_sigmoidalcontrastimage|imagick_sketchimage|imagick_solarizeimage|imagick_spliceimage|imagick_spreadimage|' + 'imagick_steganoimage|imagick_stereoimage|imagick_stripimage|imagick_swirlimage|imagick_textureimage|imagick_thresholdimage|' + 'imagick_thumbnailimage|imagick_tintimage|imagick_transformimage|imagick_transparentpaintimage|imagick_transposeimage|' + 'imagick_transverseimage|imagick_trimimage|imagick_uniqueimagecolors|imagick_unsharpmaskimage|imagick_valid|imagick_vignetteimage|' + 'imagick_waveimage|imagick_whitethresholdimage|imagick_writeimage|imagick_writeimagefile|imagick_writeimages|imagick_writeimagesfile|' + 'imagickdraw|imagickdraw_affine|imagickdraw_annotation|imagickdraw_arc|imagickdraw_bezier|imagickdraw_circle|imagickdraw_clear|' + 'imagickdraw_clone|imagickdraw_color|imagickdraw_comment|imagickdraw_composite|imagickdraw_construct|imagickdraw_destroy|' + 'imagickdraw_ellipse|imagickdraw_getclippath|imagickdraw_getcliprule|imagickdraw_getclipunits|imagickdraw_getfillcolor|' + 'imagickdraw_getfillopacity|imagickdraw_getfillrule|imagickdraw_getfont|imagickdraw_getfontfamily|imagickdraw_getfontsize|' + 'imagickdraw_getfontstyle|imagickdraw_getfontweight|imagickdraw_getgravity|imagickdraw_getstrokeantialias|imagickdraw_getstrokecolor|' + 'imagickdraw_getstrokedasharray|imagickdraw_getstrokedashoffset|imagickdraw_getstrokelinecap|imagickdraw_getstrokelinejoin|' + 'imagickdraw_getstrokemiterlimit|imagickdraw_getstrokeopacity|imagickdraw_getstrokewidth|imagickdraw_gettextalignment|' + 'imagickdraw_gettextantialias|imagickdraw_gettextdecoration|imagickdraw_gettextencoding|imagickdraw_gettextundercolor|' + 'imagickdraw_getvectorgraphics|imagickdraw_line|imagickdraw_matte|imagickdraw_pathclose|imagickdraw_pathcurvetoabsolute|' + 'imagickdraw_pathcurvetoquadraticbezierabsolute|imagickdraw_pathcurvetoquadraticbezierrelative|' + 'imagickdraw_pathcurvetoquadraticbeziersmoothabsolute|imagickdraw_pathcurvetoquadraticbeziersmoothrelative|imagickdraw_pathcurvetorelative|' + 'imagickdraw_pathcurvetosmoothabsolute|imagickdraw_pathcurvetosmoothrelative|imagickdraw_pathellipticarcabsolute|' + 'imagickdraw_pathellipticarcrelative|imagickdraw_pathfinish|imagickdraw_pathlinetoabsolute|imagickdraw_pathlinetohorizontalabsolute|' + 'imagickdraw_pathlinetohorizontalrelative|imagickdraw_pathlinetorelative|imagickdraw_pathlinetoverticalabsolute|' + 'imagickdraw_pathlinetoverticalrelative|imagickdraw_pathmovetoabsolute|imagickdraw_pathmovetorelative|imagickdraw_pathstart|' + 'imagickdraw_point|imagickdraw_polygon|imagickdraw_polyline|imagickdraw_pop|imagickdraw_popclippath|imagickdraw_popdefs|' + 'imagickdraw_poppattern|imagickdraw_push|imagickdraw_pushclippath|imagickdraw_pushdefs|imagickdraw_pushpattern|imagickdraw_rectangle|' + 'imagickdraw_render|imagickdraw_rotate|imagickdraw_roundrectangle|imagickdraw_scale|imagickdraw_setclippath|imagickdraw_setcliprule|' + 'imagickdraw_setclipunits|imagickdraw_setfillalpha|imagickdraw_setfillcolor|imagickdraw_setfillopacity|imagickdraw_setfillpatternurl|' + 'imagickdraw_setfillrule|imagickdraw_setfont|imagickdraw_setfontfamily|imagickdraw_setfontsize|imagickdraw_setfontstretch|' + 'imagickdraw_setfontstyle|imagickdraw_setfontweight|imagickdraw_setgravity|imagickdraw_setstrokealpha|imagickdraw_setstrokeantialias|' + 'imagickdraw_setstrokecolor|imagickdraw_setstrokedasharray|imagickdraw_setstrokedashoffset|imagickdraw_setstrokelinecap|' + 'imagickdraw_setstrokelinejoin|imagickdraw_setstrokemiterlimit|imagickdraw_setstrokeopacity|imagickdraw_setstrokepatternurl|' + 'imagickdraw_setstrokewidth|imagickdraw_settextalignment|imagickdraw_settextantialias|imagickdraw_settextdecoration|' + 'imagickdraw_settextencoding|imagickdraw_settextundercolor|imagickdraw_setvectorgraphics|imagickdraw_setviewbox|imagickdraw_skewx|' + 'imagickdraw_skewy|imagickdraw_translate|imagickpixel|imagickpixel_clear|imagickpixel_construct|imagickpixel_destroy|imagickpixel_getcolor|' + 'imagickpixel_getcolorasstring|imagickpixel_getcolorcount|imagickpixel_getcolorvalue|imagickpixel_gethsl|imagickpixel_issimilar|' + 'imagickpixel_setcolor|imagickpixel_setcolorvalue|imagickpixel_sethsl|imagickpixeliterator|imagickpixeliterator_clear|' + 'imagickpixeliterator_construct|imagickpixeliterator_destroy|imagickpixeliterator_getcurrentiteratorrow|' + 'imagickpixeliterator_getiteratorrow|imagickpixeliterator_getnextiteratorrow|imagickpixeliterator_getpreviousiteratorrow|' + 'imagickpixeliterator_newpixeliterator|imagickpixeliterator_newpixelregioniterator|imagickpixeliterator_resetiterator|' + 'imagickpixeliterator_setiteratorfirstrow|imagickpixeliterator_setiteratorlastrow|imagickpixeliterator_setiteratorrow|' + 'imagickpixeliterator_synciterator|imap_8bit|imap_alerts|imap_append|imap_base64|imap_binary|imap_body|imap_bodystruct|imap_check|' + 'imap_clearflag_full|imap_close|imap_create|imap_createmailbox|imap_delete|imap_deletemailbox|imap_errors|imap_expunge|imap_fetch_overview|' + 'imap_fetchbody|imap_fetchheader|imap_fetchmime|imap_fetchstructure|imap_fetchtext|imap_gc|imap_get_quota|imap_get_quotaroot|imap_getacl|' + 'imap_getmailboxes|imap_getsubscribed|imap_header|imap_headerinfo|imap_headers|imap_last_error|imap_list|imap_listmailbox|imap_listscan|' + 'imap_listsubscribed|imap_lsub|imap_mail|imap_mail_compose|imap_mail_copy|imap_mail_move|imap_mailboxmsginfo|imap_mime_header_decode|' + 'imap_msgno|imap_num_msg|imap_num_recent|imap_open|imap_ping|imap_qprint|imap_rename|imap_renamemailbox|imap_reopen|' + 'imap_rfc822_parse_adrlist|imap_rfc822_parse_headers|imap_rfc822_write_address|imap_savebody|imap_scan|imap_scanmailbox|imap_search|' + 'imap_set_quota|imap_setacl|imap_setflag_full|imap_sort|imap_status|imap_subscribe|imap_thread|imap_timeout|imap_uid|imap_undelete|' + 'imap_unsubscribe|imap_utf7_decode|imap_utf7_encode|imap_utf8|implementsinterface|implode|import_request_variables|in_array|include|' + 'include_once|inclued_get_data|inet_ntop|inet_pton|infiniteiterator|ingres_autocommit|ingres_autocommit_state|ingres_charset|ingres_close|' + 'ingres_commit|ingres_connect|ingres_cursor|ingres_errno|ingres_error|ingres_errsqlstate|ingres_escape_string|ingres_execute|' + 'ingres_fetch_array|ingres_fetch_assoc|ingres_fetch_object|ingres_fetch_proc_return|ingres_fetch_row|ingres_field_length|ingres_field_name|' + 'ingres_field_nullable|ingres_field_precision|ingres_field_scale|ingres_field_type|ingres_free_result|ingres_next_error|ingres_num_fields|' + 'ingres_num_rows|ingres_pconnect|ingres_prepare|ingres_query|ingres_result_seek|ingres_rollback|ingres_set_environment|' + 'ingres_unbuffered_query|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|innamespace|inotify_add_watch|inotify_init|inotify_queue_len|' + 'inotify_read|inotify_rm_watch|interface_exists|intl_error_name|intl_get_error_code|intl_get_error_message|intl_is_failure|' + 'intldateformatter|intval|invalidargumentexception|invoke|invokeargs|ip2long|iptcembed|iptcparse|is_a|is_array|is_bool|is_callable|is_dir|' + 'is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|' + 'is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|isabstract|' + 'iscloneable|isdisabled|isfinal|isinstance|isinstantiable|isinterface|isinternal|isiterateable|isset|issubclassof|isuserdefined|iterator|' + 'iterator_apply|iterator_count|iterator_to_array|iteratoraggregate|iteratoriterator|java_last_exception_clear|java_last_exception_get|' + 'jddayofweek|jdmonthname|jdtofrench|jdtogregorian|jdtojewish|jdtojulian|jdtounix|jewishtojd|join|jpeg2wbmp|json_decode|json_encode|' + 'json_last_error|jsonserializable|judy|judy_type|judy_version|juliantojd|kadm5_chpass_principal|kadm5_create_principal|' + 'kadm5_delete_principal|kadm5_destroy|kadm5_flush|kadm5_get_policies|kadm5_get_principal|kadm5_get_principals|kadm5_init_with_password|' + 'kadm5_modify_principal|key|krsort|ksort|lcfirst|lcg_value|lchgrp|lchown|ldap_8859_to_t61|ldap_add|ldap_bind|ldap_close|ldap_compare|' + 'ldap_connect|ldap_count_entries|ldap_delete|ldap_dn2ufn|ldap_err2str|ldap_errno|ldap_error|ldap_explode_dn|ldap_first_attribute|' + 'ldap_first_entry|ldap_first_reference|ldap_free_result|ldap_get_attributes|ldap_get_dn|ldap_get_entries|ldap_get_option|ldap_get_values|' + 'ldap_get_values_len|ldap_list|ldap_mod_add|ldap_mod_del|ldap_mod_replace|ldap_modify|ldap_next_attribute|ldap_next_entry|' + 'ldap_next_reference|ldap_parse_reference|ldap_parse_result|ldap_read|ldap_rename|ldap_sasl_bind|ldap_search|ldap_set_option|' + 'ldap_set_rebind_proc|ldap_sort|ldap_start_tls|ldap_t61_to_8859|ldap_unbind|lengthexception|levenshtein|libxml_clear_errors|' + 'libxml_disable_entity_loader|libxml_get_errors|libxml_get_last_error|libxml_set_streams_context|libxml_use_internal_errors|libxmlerror|' + 'limititerator|link|linkinfo|list|locale|localeconv|localtime|log|log10|log1p|logicexception|long2ip|lstat|ltrim|lzf_compress|' + 'lzf_decompress|lzf_optimized_for|m_checkstatus|m_completeauthorizations|m_connect|m_connectionerror|m_deletetrans|m_destroyconn|' + 'm_destroyengine|m_getcell|m_getcellbynum|m_getcommadelimited|m_getheader|m_initconn|m_initengine|m_iscommadelimited|m_maxconntimeout|' + 'm_monitor|m_numcolumns|m_numrows|m_parsecommadelimited|m_responsekeys|m_responseparam|m_returnstatus|m_setblocking|m_setdropfile|m_setip|' + 'm_setssl|m_setssl_cafile|m_setssl_files|m_settimeout|m_sslcert_gen_hash|m_transactionssent|m_transinqueue|m_transkeyval|m_transnew|' + 'm_transsend|m_uwait|m_validateidentifier|m_verifyconnection|m_verifysslcert|magic_quotes_runtime|mail|' + 'mailparse_determine_best_xfer_encoding|mailparse_msg_create|mailparse_msg_extract_part|mailparse_msg_extract_part_file|' + 'mailparse_msg_extract_whole_part_file|mailparse_msg_free|mailparse_msg_get_part|mailparse_msg_get_part_data|mailparse_msg_get_structure|' + 'mailparse_msg_parse|mailparse_msg_parse_file|mailparse_rfc822_parse_addresses|mailparse_stream_encode|mailparse_uudecode_all|main|max|' + 'maxdb_affected_rows|maxdb_autocommit|maxdb_bind_param|maxdb_bind_result|maxdb_change_user|maxdb_character_set_name|maxdb_client_encoding|' + 'maxdb_close|maxdb_close_long_data|maxdb_commit|maxdb_connect|maxdb_connect_errno|maxdb_connect_error|maxdb_data_seek|maxdb_debug|' + 'maxdb_disable_reads_from_master|maxdb_disable_rpl_parse|maxdb_dump_debug_info|maxdb_embedded_connect|maxdb_enable_reads_from_master|' + 'maxdb_enable_rpl_parse|maxdb_errno|maxdb_error|maxdb_escape_string|maxdb_execute|maxdb_fetch|maxdb_fetch_array|maxdb_fetch_assoc|' + 'maxdb_fetch_field|maxdb_fetch_field_direct|maxdb_fetch_fields|maxdb_fetch_lengths|maxdb_fetch_object|maxdb_fetch_row|maxdb_field_count|' + 'maxdb_field_seek|maxdb_field_tell|maxdb_free_result|maxdb_get_client_info|maxdb_get_client_version|maxdb_get_host_info|maxdb_get_metadata|' + 'maxdb_get_proto_info|maxdb_get_server_info|maxdb_get_server_version|maxdb_info|maxdb_init|maxdb_insert_id|maxdb_kill|maxdb_master_query|' + 'maxdb_more_results|maxdb_multi_query|maxdb_next_result|maxdb_num_fields|maxdb_num_rows|maxdb_options|maxdb_param_count|maxdb_ping|' + 'maxdb_prepare|maxdb_query|maxdb_real_connect|maxdb_real_escape_string|maxdb_real_query|maxdb_report|maxdb_rollback|' + 'maxdb_rpl_parse_enabled|maxdb_rpl_probe|maxdb_rpl_query_type|maxdb_select_db|maxdb_send_long_data|maxdb_send_query|maxdb_server_end|' + 'maxdb_server_init|maxdb_set_opt|maxdb_sqlstate|maxdb_ssl_set|maxdb_stat|maxdb_stmt_affected_rows|maxdb_stmt_bind_param|' + 'maxdb_stmt_bind_result|maxdb_stmt_close|maxdb_stmt_close_long_data|maxdb_stmt_data_seek|maxdb_stmt_errno|maxdb_stmt_error|' + 'maxdb_stmt_execute|maxdb_stmt_fetch|maxdb_stmt_free_result|maxdb_stmt_init|maxdb_stmt_num_rows|maxdb_stmt_param_count|maxdb_stmt_prepare|' + 'maxdb_stmt_reset|maxdb_stmt_result_metadata|maxdb_stmt_send_long_data|maxdb_stmt_sqlstate|maxdb_stmt_store_result|maxdb_store_result|' + 'maxdb_thread_id|maxdb_thread_safe|maxdb_use_result|maxdb_warning_count|mb_check_encoding|mb_convert_case|mb_convert_encoding|' + 'mb_convert_kana|mb_convert_variables|mb_decode_mimeheader|mb_decode_numericentity|mb_detect_encoding|mb_detect_order|mb_encode_mimeheader|' + 'mb_encode_numericentity|mb_encoding_aliases|mb_ereg|mb_ereg_match|mb_ereg_replace|mb_ereg_search|mb_ereg_search_getpos|' + 'mb_ereg_search_getregs|mb_ereg_search_init|mb_ereg_search_pos|mb_ereg_search_regs|mb_ereg_search_setpos|mb_eregi|mb_eregi_replace|' + 'mb_get_info|mb_http_input|mb_http_output|mb_internal_encoding|mb_language|mb_list_encodings|mb_output_handler|mb_parse_str|' + 'mb_preferred_mime_name|mb_regex_encoding|mb_regex_set_options|mb_send_mail|mb_split|mb_strcut|mb_strimwidth|mb_stripos|mb_stristr|' + 'mb_strlen|mb_strpos|mb_strrchr|mb_strrichr|mb_strripos|mb_strrpos|mb_strstr|mb_strtolower|mb_strtoupper|mb_strwidth|' + 'mb_substitute_character|mb_substr|mb_substr_count|mcrypt_cbc|mcrypt_cfb|mcrypt_create_iv|mcrypt_decrypt|mcrypt_ecb|' + 'mcrypt_enc_get_algorithms_name|mcrypt_enc_get_block_size|mcrypt_enc_get_iv_size|mcrypt_enc_get_key_size|mcrypt_enc_get_modes_name|' + 'mcrypt_enc_get_supported_key_sizes|mcrypt_enc_is_block_algorithm|mcrypt_enc_is_block_algorithm_mode|mcrypt_enc_is_block_mode|' + 'mcrypt_enc_self_test|mcrypt_encrypt|mcrypt_generic|mcrypt_generic_deinit|mcrypt_generic_end|mcrypt_generic_init|mcrypt_get_block_size|' + 'mcrypt_get_cipher_name|mcrypt_get_iv_size|mcrypt_get_key_size|mcrypt_list_algorithms|mcrypt_list_modes|mcrypt_module_close|' + 'mcrypt_module_get_algo_block_size|mcrypt_module_get_algo_key_size|mcrypt_module_get_supported_key_sizes|mcrypt_module_is_block_algorithm|' + 'mcrypt_module_is_block_algorithm_mode|mcrypt_module_is_block_mode|mcrypt_module_open|mcrypt_module_self_test|mcrypt_ofb|md5|md5_file|' + 'mdecrypt_generic|memcache|memcache_debug|memcached|memory_get_peak_usage|memory_get_usage|messageformatter|metaphone|method_exists|mhash|' + 'mhash_count|mhash_get_block_size|mhash_get_hash_name|mhash_keygen_s2k|microtime|mime_content_type|min|ming_keypress|' + 'ming_setcubicthreshold|ming_setscale|ming_setswfcompression|ming_useconstants|ming_useswfversion|mkdir|mktime|money_format|mongo|' + 'mongobindata|mongocode|mongocollection|mongoconnectionexception|mongocursor|mongocursorexception|mongocursortimeoutexception|mongodate|' + 'mongodb|mongodbref|mongoexception|mongogridfs|mongogridfscursor|mongogridfsexception|mongogridfsfile|mongoid|mongoint32|mongoint64|' + 'mongomaxkey|mongominkey|mongoregex|mongotimestamp|move_uploaded_file|mpegfile|mqseries_back|mqseries_begin|mqseries_close|mqseries_cmit|' + 'mqseries_conn|mqseries_connx|mqseries_disc|mqseries_get|mqseries_inq|mqseries_open|mqseries_put|mqseries_put1|mqseries_set|' + 'mqseries_strerror|msession_connect|msession_count|msession_create|msession_destroy|msession_disconnect|msession_find|msession_get|' + 'msession_get_array|msession_get_data|msession_inc|msession_list|msession_listvar|msession_lock|msession_plugin|msession_randstr|' + 'msession_set|msession_set_array|msession_set_data|msession_timeout|msession_uniq|msession_unlock|msg_get_queue|msg_queue_exists|' + 'msg_receive|msg_remove_queue|msg_send|msg_set_queue|msg_stat_queue|msql|msql_affected_rows|msql_close|msql_connect|msql_create_db|' + 'msql_createdb|msql_data_seek|msql_db_query|msql_dbname|msql_drop_db|msql_error|msql_fetch_array|msql_fetch_field|msql_fetch_object|' + 'msql_fetch_row|msql_field_flags|msql_field_len|msql_field_name|msql_field_seek|msql_field_table|msql_field_type|msql_fieldflags|' + 'msql_fieldlen|msql_fieldname|msql_fieldtable|msql_fieldtype|msql_free_result|msql_list_dbs|msql_list_fields|msql_list_tables|' + 'msql_num_fields|msql_num_rows|msql_numfields|msql_numrows|msql_pconnect|msql_query|msql_regcase|msql_result|msql_select_db|msql_tablename|' + 'mssql_bind|mssql_close|mssql_connect|mssql_data_seek|mssql_execute|mssql_fetch_array|mssql_fetch_assoc|mssql_fetch_batch|' + 'mssql_fetch_field|mssql_fetch_object|mssql_fetch_row|mssql_field_length|mssql_field_name|mssql_field_seek|mssql_field_type|' + 'mssql_free_result|mssql_free_statement|mssql_get_last_message|mssql_guid_string|mssql_init|mssql_min_error_severity|' + 'mssql_min_message_severity|mssql_next_result|mssql_num_fields|mssql_num_rows|mssql_pconnect|mssql_query|mssql_result|mssql_rows_affected|' + 'mssql_select_db|mt_getrandmax|mt_rand|mt_srand|multipleiterator|mysql_affected_rows|mysql_client_encoding|mysql_close|mysql_connect|' + 'mysql_create_db|mysql_data_seek|mysql_db_name|mysql_db_query|mysql_drop_db|mysql_errno|mysql_error|mysql_escape_string|mysql_fetch_array|' + 'mysql_fetch_assoc|mysql_fetch_field|mysql_fetch_lengths|mysql_fetch_object|mysql_fetch_row|mysql_field_flags|mysql_field_len|' + 'mysql_field_name|mysql_field_seek|mysql_field_table|mysql_field_type|mysql_free_result|mysql_get_client_info|mysql_get_host_info|' + 'mysql_get_proto_info|mysql_get_server_info|mysql_info|mysql_insert_id|mysql_list_dbs|mysql_list_fields|mysql_list_processes|' + 'mysql_list_tables|mysql_num_fields|mysql_num_rows|mysql_pconnect|mysql_ping|mysql_query|mysql_real_escape_string|mysql_result|' + 'mysql_select_db|mysql_set_charset|mysql_stat|mysql_tablename|mysql_thread_id|mysql_unbuffered_query|mysqli|mysqli_bind_param|' + 'mysqli_bind_result|mysqli_client_encoding|mysqli_connect|mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_driver|' + 'mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_escape_string|mysqli_execute|mysqli_fetch|mysqli_get_metadata|' + 'mysqli_master_query|mysqli_param_count|mysqli_report|mysqli_result|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' + 'mysqli_send_long_data|mysqli_send_query|mysqli_set_opt|mysqli_slave_query|mysqli_stmt|mysqli_warning|mysqlnd_ms_get_stats|' + 'mysqlnd_ms_query_is_select|mysqlnd_ms_set_user_pick_server|mysqlnd_qc_change_handler|mysqlnd_qc_clear_cache|mysqlnd_qc_get_cache_info|' + 'mysqlnd_qc_get_core_stats|mysqlnd_qc_get_handler|mysqlnd_qc_get_query_trace_log|mysqlnd_qc_set_user_handlers|natcasesort|natsort|' + 'ncurses_addch|ncurses_addchnstr|ncurses_addchstr|ncurses_addnstr|ncurses_addstr|ncurses_assume_default_colors|ncurses_attroff|' + 'ncurses_attron|ncurses_attrset|ncurses_baudrate|ncurses_beep|ncurses_bkgd|ncurses_bkgdset|ncurses_border|ncurses_bottom_panel|' + 'ncurses_can_change_color|ncurses_cbreak|ncurses_clear|ncurses_clrtobot|ncurses_clrtoeol|ncurses_color_content|ncurses_color_set|' + 'ncurses_curs_set|ncurses_def_prog_mode|ncurses_def_shell_mode|ncurses_define_key|ncurses_del_panel|ncurses_delay_output|ncurses_delch|' + 'ncurses_deleteln|ncurses_delwin|ncurses_doupdate|ncurses_echo|ncurses_echochar|ncurses_end|ncurses_erase|ncurses_erasechar|ncurses_filter|' + 'ncurses_flash|ncurses_flushinp|ncurses_getch|ncurses_getmaxyx|ncurses_getmouse|ncurses_getyx|ncurses_halfdelay|ncurses_has_colors|' + 'ncurses_has_ic|ncurses_has_il|ncurses_has_key|ncurses_hide_panel|ncurses_hline|ncurses_inch|ncurses_init|ncurses_init_color|' + 'ncurses_init_pair|ncurses_insch|ncurses_insdelln|ncurses_insertln|ncurses_insstr|ncurses_instr|ncurses_isendwin|ncurses_keyok|' + 'ncurses_keypad|ncurses_killchar|ncurses_longname|ncurses_meta|ncurses_mouse_trafo|ncurses_mouseinterval|ncurses_mousemask|ncurses_move|' + 'ncurses_move_panel|ncurses_mvaddch|ncurses_mvaddchnstr|ncurses_mvaddchstr|ncurses_mvaddnstr|ncurses_mvaddstr|ncurses_mvcur|' + 'ncurses_mvdelch|ncurses_mvgetch|ncurses_mvhline|ncurses_mvinch|ncurses_mvvline|ncurses_mvwaddstr|ncurses_napms|ncurses_new_panel|' + 'ncurses_newpad|ncurses_newwin|ncurses_nl|ncurses_nocbreak|ncurses_noecho|ncurses_nonl|ncurses_noqiflush|ncurses_noraw|' + 'ncurses_pair_content|ncurses_panel_above|ncurses_panel_below|ncurses_panel_window|ncurses_pnoutrefresh|ncurses_prefresh|ncurses_putp|' + 'ncurses_qiflush|ncurses_raw|ncurses_refresh|ncurses_replace_panel|ncurses_reset_prog_mode|ncurses_reset_shell_mode|ncurses_resetty|' + 'ncurses_savetty|ncurses_scr_dump|ncurses_scr_init|ncurses_scr_restore|ncurses_scr_set|ncurses_scrl|ncurses_show_panel|ncurses_slk_attr|' + 'ncurses_slk_attroff|ncurses_slk_attron|ncurses_slk_attrset|ncurses_slk_clear|ncurses_slk_color|ncurses_slk_init|ncurses_slk_noutrefresh|' + 'ncurses_slk_refresh|ncurses_slk_restore|ncurses_slk_set|ncurses_slk_touch|ncurses_standend|ncurses_standout|ncurses_start_color|' + 'ncurses_termattrs|ncurses_termname|ncurses_timeout|ncurses_top_panel|ncurses_typeahead|ncurses_ungetch|ncurses_ungetmouse|' + 'ncurses_update_panels|ncurses_use_default_colors|ncurses_use_env|ncurses_use_extended_names|ncurses_vidattr|ncurses_vline|ncurses_waddch|' + 'ncurses_waddstr|ncurses_wattroff|ncurses_wattron|ncurses_wattrset|ncurses_wborder|ncurses_wclear|ncurses_wcolor_set|ncurses_werase|' + 'ncurses_wgetch|ncurses_whline|ncurses_wmouse_trafo|ncurses_wmove|ncurses_wnoutrefresh|ncurses_wrefresh|ncurses_wstandend|' + 'ncurses_wstandout|ncurses_wvline|newinstance|newinstanceargs|newt_bell|newt_button|newt_button_bar|newt_centered_window|newt_checkbox|' + 'newt_checkbox_get_value|newt_checkbox_set_flags|newt_checkbox_set_value|newt_checkbox_tree|newt_checkbox_tree_add_item|' + 'newt_checkbox_tree_find_item|newt_checkbox_tree_get_current|newt_checkbox_tree_get_entry_value|newt_checkbox_tree_get_multi_selection|' + 'newt_checkbox_tree_get_selection|newt_checkbox_tree_multi|newt_checkbox_tree_set_current|newt_checkbox_tree_set_entry|' + 'newt_checkbox_tree_set_entry_value|newt_checkbox_tree_set_width|newt_clear_key_buffer|newt_cls|newt_compact_button|' + 'newt_component_add_callback|newt_component_takes_focus|newt_create_grid|newt_cursor_off|newt_cursor_on|newt_delay|newt_draw_form|' + 'newt_draw_root_text|newt_entry|newt_entry_get_value|newt_entry_set|newt_entry_set_filter|newt_entry_set_flags|newt_finished|newt_form|' + 'newt_form_add_component|newt_form_add_components|newt_form_add_hot_key|newt_form_destroy|newt_form_get_current|newt_form_run|' + 'newt_form_set_background|newt_form_set_height|newt_form_set_size|newt_form_set_timer|newt_form_set_width|newt_form_watch_fd|' + 'newt_get_screen_size|newt_grid_add_components_to_form|newt_grid_basic_window|newt_grid_free|newt_grid_get_size|newt_grid_h_close_stacked|' + 'newt_grid_h_stacked|newt_grid_place|newt_grid_set_field|newt_grid_simple_window|newt_grid_v_close_stacked|newt_grid_v_stacked|' + 'newt_grid_wrapped_window|newt_grid_wrapped_window_at|newt_init|newt_label|newt_label_set_text|newt_listbox|newt_listbox_append_entry|' + 'newt_listbox_clear|newt_listbox_clear_selection|newt_listbox_delete_entry|newt_listbox_get_current|newt_listbox_get_selection|' + 'newt_listbox_insert_entry|newt_listbox_item_count|newt_listbox_select_item|newt_listbox_set_current|newt_listbox_set_current_by_key|' + 'newt_listbox_set_data|newt_listbox_set_entry|newt_listbox_set_width|newt_listitem|newt_listitem_get_data|newt_listitem_set|' + 'newt_open_window|newt_pop_help_line|newt_pop_window|newt_push_help_line|newt_radio_get_current|newt_radiobutton|newt_redraw_help_line|' + 'newt_reflow_text|newt_refresh|newt_resize_screen|newt_resume|newt_run_form|newt_scale|newt_scale_set|newt_scrollbar_set|' + 'newt_set_help_callback|newt_set_suspend_callback|newt_suspend|newt_textbox|newt_textbox_get_num_lines|newt_textbox_reflowed|' + 'newt_textbox_set_height|newt_textbox_set_text|newt_vertical_scrollbar|newt_wait_for_key|newt_win_choice|newt_win_entries|newt_win_menu|' + 'newt_win_message|newt_win_messagev|newt_win_ternary|next|ngettext|nl2br|nl_langinfo|norewinditerator|normalizer|notes_body|notes_copy_db|' + 'notes_create_db|notes_create_note|notes_drop_db|notes_find_note|notes_header_info|notes_list_msgs|notes_mark_read|notes_mark_unread|' + 'notes_nav_create|notes_search|notes_unread|notes_version|nsapi_request_headers|nsapi_response_headers|nsapi_virtual|nthmac|number_format|' + 'numberformatter|oauth|oauth_get_sbs|oauth_urlencode|oauthexception|oauthprovider|ob_clean|ob_deflatehandler|ob_end_clean|ob_end_flush|' + 'ob_etaghandler|ob_flush|ob_get_clean|ob_get_contents|ob_get_flush|ob_get_length|ob_get_level|ob_get_status|ob_gzhandler|ob_iconv_handler|' + 'ob_implicit_flush|ob_inflatehandler|ob_list_handlers|ob_start|ob_tidyhandler|oci_bind_array_by_name|oci_bind_by_name|oci_cancel|' + 'oci_client_version|oci_close|oci_collection_append|oci_collection_assign|oci_collection_element_assign|oci_collection_element_get|' + 'oci_collection_free|oci_collection_max|oci_collection_size|oci_collection_trim|oci_commit|oci_connect|oci_define_by_name|oci_error|' + 'oci_execute|oci_fetch|oci_fetch_all|oci_fetch_array|oci_fetch_assoc|oci_fetch_object|oci_fetch_row|oci_field_is_null|oci_field_name|' + 'oci_field_precision|oci_field_scale|oci_field_size|oci_field_type|oci_field_type_raw|oci_free_statement|oci_internal_debug|oci_lob_append|' + 'oci_lob_close|oci_lob_copy|oci_lob_eof|oci_lob_erase|oci_lob_export|oci_lob_flush|oci_lob_free|oci_lob_getbuffering|oci_lob_import|' + 'oci_lob_is_equal|oci_lob_load|oci_lob_read|oci_lob_rewind|oci_lob_save|oci_lob_savefile|oci_lob_seek|oci_lob_setbuffering|oci_lob_size|' + 'oci_lob_tell|oci_lob_truncate|oci_lob_write|oci_lob_writetemporary|oci_lob_writetofile|oci_new_collection|oci_new_connect|oci_new_cursor|' + 'oci_new_descriptor|oci_num_fields|oci_num_rows|oci_parse|oci_password_change|oci_pconnect|oci_result|oci_rollback|oci_server_version|' + 'oci_set_action|oci_set_client_identifier|oci_set_client_info|oci_set_edition|oci_set_module_name|oci_set_prefetch|oci_statement_type|' + 'ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|' + 'ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|' + 'ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|' + 'ociloadlob|ocilogoff|ocilogon|ocinewcollection|ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|' + 'ocirollback|ocirowcount|ocisavelob|ocisavelobfile|ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|' + 'octdec|odbc_autocommit|odbc_binmode|odbc_close|odbc_close_all|odbc_columnprivileges|odbc_columns|odbc_commit|odbc_connect|odbc_cursor|' + 'odbc_data_source|odbc_do|odbc_error|odbc_errormsg|odbc_exec|odbc_execute|odbc_fetch_array|odbc_fetch_into|odbc_fetch_object|' + 'odbc_fetch_row|odbc_field_len|odbc_field_name|odbc_field_num|odbc_field_precision|odbc_field_scale|odbc_field_type|odbc_foreignkeys|' + 'odbc_free_result|odbc_gettypeinfo|odbc_longreadlen|odbc_next_result|odbc_num_fields|odbc_num_rows|odbc_pconnect|odbc_prepare|' + 'odbc_primarykeys|odbc_procedurecolumns|odbc_procedures|odbc_result|odbc_result_all|odbc_rollback|odbc_setoption|odbc_specialcolumns|' + 'odbc_statistics|odbc_tableprivileges|odbc_tables|openal_buffer_create|openal_buffer_data|openal_buffer_destroy|openal_buffer_get|' + 'openal_buffer_loadwav|openal_context_create|openal_context_current|openal_context_destroy|openal_context_process|openal_context_suspend|' + 'openal_device_close|openal_device_open|openal_listener_get|openal_listener_set|openal_source_create|openal_source_destroy|' + 'openal_source_get|openal_source_pause|openal_source_play|openal_source_rewind|openal_source_set|openal_source_stop|openal_stream|opendir|' + 'openlog|openssl_cipher_iv_length|openssl_csr_export|openssl_csr_export_to_file|openssl_csr_get_public_key|openssl_csr_get_subject|' + 'openssl_csr_new|openssl_csr_sign|openssl_decrypt|openssl_dh_compute_key|openssl_digest|openssl_encrypt|openssl_error_string|' + 'openssl_free_key|openssl_get_cipher_methods|openssl_get_md_methods|openssl_get_privatekey|openssl_get_publickey|openssl_open|' + 'openssl_pkcs12_export|openssl_pkcs12_export_to_file|openssl_pkcs12_read|openssl_pkcs7_decrypt|openssl_pkcs7_encrypt|openssl_pkcs7_sign|' + 'openssl_pkcs7_verify|openssl_pkey_export|openssl_pkey_export_to_file|openssl_pkey_free|openssl_pkey_get_details|openssl_pkey_get_private|' + 'openssl_pkey_get_public|openssl_pkey_new|openssl_private_decrypt|openssl_private_encrypt|openssl_public_decrypt|openssl_public_encrypt|' + 'openssl_random_pseudo_bytes|openssl_seal|openssl_sign|openssl_verify|openssl_x509_check_private_key|openssl_x509_checkpurpose|' + 'openssl_x509_export|openssl_x509_export_to_file|openssl_x509_free|openssl_x509_parse|openssl_x509_read|ord|outeriterator|' + 'outofboundsexception|outofrangeexception|output_add_rewrite_var|output_reset_rewrite_vars|overflowexception|overload|override_function|' + 'ovrimos_close|ovrimos_commit|ovrimos_connect|ovrimos_cursor|ovrimos_exec|ovrimos_execute|ovrimos_fetch_into|ovrimos_fetch_row|' + 'ovrimos_field_len|ovrimos_field_name|ovrimos_field_num|ovrimos_field_type|ovrimos_free_result|ovrimos_longreadlen|ovrimos_num_fields|' + 'ovrimos_num_rows|ovrimos_prepare|ovrimos_result|ovrimos_result_all|ovrimos_rollback|pack|parentiterator|parse_ini_file|parse_ini_string|' + 'parse_str|parse_url|parsekit_compile_file|parsekit_compile_string|parsekit_func_arginfo|passthru|pathinfo|pclose|pcntl_alarm|pcntl_exec|' + 'pcntl_fork|pcntl_getpriority|pcntl_setpriority|pcntl_signal|pcntl_signal_dispatch|pcntl_sigprocmask|pcntl_sigtimedwait|pcntl_sigwaitinfo|' + 'pcntl_wait|pcntl_waitpid|pcntl_wexitstatus|pcntl_wifexited|pcntl_wifsignaled|pcntl_wifstopped|pcntl_wstopsig|pcntl_wtermsig|' + 'pdf_activate_item|pdf_add_annotation|pdf_add_bookmark|pdf_add_launchlink|pdf_add_locallink|pdf_add_nameddest|pdf_add_note|pdf_add_outline|' + 'pdf_add_pdflink|pdf_add_table_cell|pdf_add_textflow|pdf_add_thumbnail|pdf_add_weblink|pdf_arc|pdf_arcn|pdf_attach_file|pdf_begin_document|' + 'pdf_begin_font|pdf_begin_glyph|pdf_begin_item|pdf_begin_layer|pdf_begin_page|pdf_begin_page_ext|pdf_begin_pattern|pdf_begin_template|' + 'pdf_begin_template_ext|pdf_circle|pdf_clip|pdf_close|pdf_close_image|pdf_close_pdi|pdf_close_pdi_page|pdf_closepath|' + 'pdf_closepath_fill_stroke|pdf_closepath_stroke|pdf_concat|pdf_continue_text|pdf_create_3dview|pdf_create_action|pdf_create_annotation|' + 'pdf_create_bookmark|pdf_create_field|pdf_create_fieldgroup|pdf_create_gstate|pdf_create_pvf|pdf_create_textflow|pdf_curveto|' + 'pdf_define_layer|pdf_delete|pdf_delete_pvf|pdf_delete_table|pdf_delete_textflow|pdf_encoding_set_char|pdf_end_document|pdf_end_font|' + 'pdf_end_glyph|pdf_end_item|pdf_end_layer|pdf_end_page|pdf_end_page_ext|pdf_end_pattern|pdf_end_template|pdf_endpath|pdf_fill|' + 'pdf_fill_imageblock|pdf_fill_pdfblock|pdf_fill_stroke|pdf_fill_textblock|pdf_findfont|pdf_fit_image|pdf_fit_pdi_page|pdf_fit_table|' + 'pdf_fit_textflow|pdf_fit_textline|pdf_get_apiname|pdf_get_buffer|pdf_get_errmsg|pdf_get_errnum|pdf_get_font|pdf_get_fontname|' + 'pdf_get_fontsize|pdf_get_image_height|pdf_get_image_width|pdf_get_majorversion|pdf_get_minorversion|pdf_get_parameter|' + 'pdf_get_pdi_parameter|pdf_get_pdi_value|pdf_get_value|pdf_info_font|pdf_info_matchbox|pdf_info_table|pdf_info_textflow|pdf_info_textline|' + 'pdf_initgraphics|pdf_lineto|pdf_load_3ddata|pdf_load_font|pdf_load_iccprofile|pdf_load_image|pdf_makespotcolor|pdf_moveto|pdf_new|' + 'pdf_open_ccitt|pdf_open_file|pdf_open_gif|pdf_open_image|pdf_open_image_file|pdf_open_jpeg|pdf_open_memory_image|pdf_open_pdi|' + 'pdf_open_pdi_document|pdf_open_pdi_page|pdf_open_tiff|pdf_pcos_get_number|pdf_pcos_get_stream|pdf_pcos_get_string|pdf_place_image|' + 'pdf_place_pdi_page|pdf_process_pdi|pdf_rect|pdf_restore|pdf_resume_page|pdf_rotate|pdf_save|pdf_scale|pdf_set_border_color|' + 'pdf_set_border_dash|pdf_set_border_style|pdf_set_char_spacing|pdf_set_duration|pdf_set_gstate|pdf_set_horiz_scaling|pdf_set_info|' + 'pdf_set_info_author|pdf_set_info_creator|pdf_set_info_keywords|pdf_set_info_subject|pdf_set_info_title|pdf_set_layer_dependency|' + 'pdf_set_leading|pdf_set_parameter|pdf_set_text_matrix|pdf_set_text_pos|pdf_set_text_rendering|pdf_set_text_rise|pdf_set_value|' + 'pdf_set_word_spacing|pdf_setcolor|pdf_setdash|pdf_setdashpattern|pdf_setflat|pdf_setfont|pdf_setgray|pdf_setgray_fill|pdf_setgray_stroke|' + 'pdf_setlinecap|pdf_setlinejoin|pdf_setlinewidth|pdf_setmatrix|pdf_setmiterlimit|pdf_setpolydash|pdf_setrgbcolor|pdf_setrgbcolor_fill|' + 'pdf_setrgbcolor_stroke|pdf_shading|pdf_shading_pattern|pdf_shfill|pdf_show|pdf_show_boxed|pdf_show_xy|pdf_skew|pdf_stringwidth|pdf_stroke|' + 'pdf_suspend_page|pdf_translate|pdf_utf16_to_utf8|pdf_utf32_to_utf16|pdf_utf8_to_utf16|pdo|pdo_cubrid_schema|pdo_pgsqllobcreate|' + 'pdo_pgsqllobopen|pdo_pgsqllobunlink|pdo_sqlitecreateaggregate|pdo_sqlitecreatefunction|pdoexception|pdostatement|pfsockopen|' + 'pg_affected_rows|pg_cancel_query|pg_client_encoding|pg_close|pg_connect|pg_connection_busy|pg_connection_reset|pg_connection_status|' + 'pg_convert|pg_copy_from|pg_copy_to|pg_dbname|pg_delete|pg_end_copy|pg_escape_bytea|pg_escape_string|pg_execute|pg_fetch_all|' + 'pg_fetch_all_columns|pg_fetch_array|pg_fetch_assoc|pg_fetch_object|pg_fetch_result|pg_fetch_row|pg_field_is_null|pg_field_name|' + 'pg_field_num|pg_field_prtlen|pg_field_size|pg_field_table|pg_field_type|pg_field_type_oid|pg_free_result|pg_get_notify|pg_get_pid|' + 'pg_get_result|pg_host|pg_insert|pg_last_error|pg_last_notice|pg_last_oid|pg_lo_close|pg_lo_create|pg_lo_export|pg_lo_import|pg_lo_open|' + 'pg_lo_read|pg_lo_read_all|pg_lo_seek|pg_lo_tell|pg_lo_unlink|pg_lo_write|pg_meta_data|pg_num_fields|pg_num_rows|pg_options|' + 'pg_parameter_status|pg_pconnect|pg_ping|pg_port|pg_prepare|pg_put_line|pg_query|pg_query_params|pg_result_error|pg_result_error_field|' + 'pg_result_seek|pg_result_status|pg_select|pg_send_execute|pg_send_prepare|pg_send_query|pg_send_query_params|pg_set_client_encoding|' + 'pg_set_error_verbosity|pg_trace|pg_transaction_status|pg_tty|pg_unescape_bytea|pg_untrace|pg_update|pg_version|php_check_syntax|' + 'php_ini_loaded_file|php_ini_scanned_files|php_logo_guid|php_sapi_name|php_strip_whitespace|php_uname|phpcredits|phpinfo|phpversion|pi|' + 'png2wbmp|popen|pos|posix_access|posix_ctermid|posix_errno|posix_get_last_error|posix_getcwd|posix_getegid|posix_geteuid|posix_getgid|' + 'posix_getgrgid|posix_getgrnam|posix_getgroups|posix_getlogin|posix_getpgid|posix_getpgrp|posix_getpid|posix_getppid|posix_getpwnam|' + 'posix_getpwuid|posix_getrlimit|posix_getsid|posix_getuid|posix_initgroups|posix_isatty|posix_kill|posix_mkfifo|posix_mknod|posix_setegid|' + 'posix_seteuid|posix_setgid|posix_setpgid|posix_setsid|posix_setuid|posix_strerror|posix_times|posix_ttyname|posix_uname|pow|preg_filter|' + 'preg_grep|preg_last_error|preg_match|preg_match_all|preg_quote|preg_replace|preg_replace_callback|preg_split|prev|print|print_r|' + 'printer_abort|printer_close|printer_create_brush|printer_create_dc|printer_create_font|printer_create_pen|printer_delete_brush|' + 'printer_delete_dc|printer_delete_font|printer_delete_pen|printer_draw_bmp|printer_draw_chord|printer_draw_elipse|printer_draw_line|' + 'printer_draw_pie|printer_draw_rectangle|printer_draw_roundrect|printer_draw_text|printer_end_doc|printer_end_page|printer_get_option|' + 'printer_list|printer_logical_fontheight|printer_open|printer_select_brush|printer_select_font|printer_select_pen|printer_set_option|' + 'printer_start_doc|printer_start_page|printer_write|printf|proc_close|proc_get_status|proc_nice|proc_open|proc_terminate|property_exists|' + 'ps_add_bookmark|ps_add_launchlink|ps_add_locallink|ps_add_note|ps_add_pdflink|ps_add_weblink|ps_arc|ps_arcn|ps_begin_page|' + 'ps_begin_pattern|ps_begin_template|ps_circle|ps_clip|ps_close|ps_close_image|ps_closepath|ps_closepath_stroke|ps_continue_text|ps_curveto|' + 'ps_delete|ps_end_page|ps_end_pattern|ps_end_template|ps_fill|ps_fill_stroke|ps_findfont|ps_get_buffer|ps_get_parameter|ps_get_value|' + 'ps_hyphenate|ps_include_file|ps_lineto|ps_makespotcolor|ps_moveto|ps_new|ps_open_file|ps_open_image|ps_open_image_file|' + 'ps_open_memory_image|ps_place_image|ps_rect|ps_restore|ps_rotate|ps_save|ps_scale|ps_set_border_color|ps_set_border_dash|' + 'ps_set_border_style|ps_set_info|ps_set_parameter|ps_set_text_pos|ps_set_value|ps_setcolor|ps_setdash|ps_setflat|ps_setfont|ps_setgray|' + 'ps_setlinecap|ps_setlinejoin|ps_setlinewidth|ps_setmiterlimit|ps_setoverprintmode|ps_setpolydash|ps_shading|ps_shading_pattern|ps_shfill|' + 'ps_show|ps_show2|ps_show_boxed|ps_show_xy|ps_show_xy2|ps_string_geometry|ps_stringwidth|ps_stroke|ps_symbol|ps_symbol_name|' + 'ps_symbol_width|ps_translate|pspell_add_to_personal|pspell_add_to_session|pspell_check|pspell_clear_session|pspell_config_create|' + 'pspell_config_data_dir|pspell_config_dict_dir|pspell_config_ignore|pspell_config_mode|pspell_config_personal|pspell_config_repl|' + 'pspell_config_runtogether|pspell_config_save_repl|pspell_new|pspell_new_config|pspell_new_personal|pspell_save_wordlist|' + 'pspell_store_replacement|pspell_suggest|putenv|px_close|px_create_fp|px_date2string|px_delete|px_delete_record|px_get_field|px_get_info|' + 'px_get_parameter|px_get_record|px_get_schema|px_get_value|px_insert_record|px_new|px_numfields|px_numrecords|px_open_fp|px_put_record|' + 'px_retrieve_record|px_set_blob_file|px_set_parameter|px_set_tablename|px_set_targetencoding|px_set_value|px_timestamp2string|' + 'px_update_record|qdom_error|qdom_tree|quoted_printable_decode|quoted_printable_encode|quotemeta|rad2deg|radius_acct_open|' + 'radius_add_server|radius_auth_open|radius_close|radius_config|radius_create_request|radius_cvt_addr|radius_cvt_int|radius_cvt_string|' + 'radius_demangle|radius_demangle_mppe_key|radius_get_attr|radius_get_vendor_attr|radius_put_addr|radius_put_attr|radius_put_int|' + 'radius_put_string|radius_put_vendor_addr|radius_put_vendor_attr|radius_put_vendor_int|radius_put_vendor_string|' + 'radius_request_authenticator|radius_send_request|radius_server_secret|radius_strerror|rand|range|rangeexception|rar_wrapper_cache_stats|' + 'rararchive|rarentry|rarexception|rawurldecode|rawurlencode|read_exif_data|readdir|readfile|readgzfile|readline|readline_add_history|' + 'readline_callback_handler_install|readline_callback_handler_remove|readline_callback_read_char|readline_clear_history|' + 'readline_completion_function|readline_info|readline_list_history|readline_on_new_line|readline_read_history|readline_redisplay|' + 'readline_write_history|readlink|realpath|realpath_cache_get|realpath_cache_size|recode|recode_file|recode_string|recursivearrayiterator|' + 'recursivecachingiterator|recursivecallbackfilteriterator|recursivedirectoryiterator|recursivefilteriterator|recursiveiterator|' + 'recursiveiteratoriterator|recursiveregexiterator|recursivetreeiterator|reflection|reflectionclass|reflectionexception|reflectionextension|' + 'reflectionfunction|reflectionfunctionabstract|reflectionmethod|reflectionobject|reflectionparameter|reflectionproperty|reflector|' + 'regexiterator|register_shutdown_function|register_tick_function|rename|rename_function|require|require_once|reset|resetValue|' + 'resourcebundle|restore_error_handler|restore_exception_handler|restore_include_path|return|rewind|rewinddir|rmdir|round|rpm_close|' + 'rpm_get_tag|rpm_is_valid|rpm_open|rpm_version|rrd_create|rrd_error|rrd_fetch|rrd_first|rrd_graph|rrd_info|rrd_last|rrd_lastupdate|' + 'rrd_restore|rrd_tune|rrd_update|rrd_xport|rrdcreator|rrdgraph|rrdupdater|rsort|rtrim|runkit_class_adopt|runkit_class_emancipate|' + 'runkit_constant_add|runkit_constant_redefine|runkit_constant_remove|runkit_function_add|runkit_function_copy|runkit_function_redefine|' + 'runkit_function_remove|runkit_function_rename|runkit_import|runkit_lint|runkit_lint_file|runkit_method_add|runkit_method_copy|' + 'runkit_method_redefine|runkit_method_remove|runkit_method_rename|runkit_return_value_used|runkit_sandbox_output_handler|' + 'runkit_superglobals|runtimeexception|samconnection_commit|samconnection_connect|samconnection_constructor|samconnection_disconnect|' + 'samconnection_errno|samconnection_error|samconnection_isconnected|samconnection_peek|samconnection_peekall|samconnection_receive|' + 'samconnection_remove|samconnection_rollback|samconnection_send|samconnection_setDebug|samconnection_subscribe|samconnection_unsubscribe|' + 'sammessage_body|sammessage_constructor|sammessage_header|sca_createdataobject|sca_getservice|sca_localproxy_createdataobject|' + 'sca_soapproxy_createdataobject|scandir|sdo_das_changesummary_beginlogging|sdo_das_changesummary_endlogging|' + 'sdo_das_changesummary_getchangeddataobjects|sdo_das_changesummary_getchangetype|sdo_das_changesummary_getoldcontainer|' + 'sdo_das_changesummary_getoldvalues|sdo_das_changesummary_islogging|sdo_das_datafactory_addpropertytotype|sdo_das_datafactory_addtype|' + 'sdo_das_datafactory_getdatafactory|sdo_das_dataobject_getchangesummary|sdo_das_relational_applychanges|sdo_das_relational_construct|' + 'sdo_das_relational_createrootdataobject|sdo_das_relational_executepreparedquery|sdo_das_relational_executequery|' + 'sdo_das_setting_getlistindex|sdo_das_setting_getpropertyindex|sdo_das_setting_getpropertyname|sdo_das_setting_getvalue|' + 'sdo_das_setting_isset|sdo_das_xml_addtypes|sdo_das_xml_create|sdo_das_xml_createdataobject|sdo_das_xml_createdocument|' + 'sdo_das_xml_document_getrootdataobject|sdo_das_xml_document_getrootelementname|sdo_das_xml_document_getrootelementuri|' + 'sdo_das_xml_document_setencoding|sdo_das_xml_document_setxmldeclaration|sdo_das_xml_document_setxmlversion|sdo_das_xml_loadfile|' + 'sdo_das_xml_loadstring|sdo_das_xml_savefile|sdo_das_xml_savestring|sdo_datafactory_create|sdo_dataobject_clear|' + 'sdo_dataobject_createdataobject|sdo_dataobject_getcontainer|sdo_dataobject_getsequence|sdo_dataobject_gettypename|' + 'sdo_dataobject_gettypenamespaceuri|sdo_exception_getcause|sdo_list_insert|sdo_model_property_getcontainingtype|' + 'sdo_model_property_getdefault|sdo_model_property_getname|sdo_model_property_gettype|sdo_model_property_iscontainment|' + 'sdo_model_property_ismany|sdo_model_reflectiondataobject_construct|sdo_model_reflectiondataobject_export|' + 'sdo_model_reflectiondataobject_getcontainmentproperty|sdo_model_reflectiondataobject_getinstanceproperties|' + 'sdo_model_reflectiondataobject_gettype|sdo_model_type_getbasetype|sdo_model_type_getname|sdo_model_type_getnamespaceuri|' + 'sdo_model_type_getproperties|sdo_model_type_getproperty|sdo_model_type_isabstracttype|sdo_model_type_isdatatype|sdo_model_type_isinstance|' + 'sdo_model_type_isopentype|sdo_model_type_issequencedtype|sdo_sequence_getproperty|sdo_sequence_insert|sdo_sequence_move|seekableiterator|' + 'sem_acquire|sem_get|sem_release|sem_remove|serializable|serialize|session_cache_expire|session_cache_limiter|session_commit|' + 'session_decode|session_destroy|session_encode|session_get_cookie_params|session_id|session_is_registered|session_module_name|session_name|' + 'session_pgsql_add_error|session_pgsql_get_error|session_pgsql_get_field|session_pgsql_reset|session_pgsql_set_field|session_pgsql_status|' + 'session_regenerate_id|session_register|session_save_path|session_set_cookie_params|session_set_save_handler|session_start|' + 'session_unregister|session_unset|session_write_close|setCounterClass|set_error_handler|set_exception_handler|set_file_buffer|' + 'set_include_path|set_magic_quotes_runtime|set_socket_blocking|set_time_limit|setcookie|setlocale|setproctitle|setrawcookie|' + 'setstaticpropertyvalue|setthreadtitle|settype|sha1|sha1_file|shell_exec|shm_attach|shm_detach|shm_get_var|shm_has_var|shm_put_var|' + 'shm_remove|shm_remove_var|shmop_close|shmop_delete|shmop_open|shmop_read|shmop_size|shmop_write|show_source|shuffle|signeurlpaiement|' + 'similar_text|simplexml_import_dom|simplexml_load_file|simplexml_load_string|simplexmlelement|simplexmliterator|sin|sinh|sizeof|sleep|snmp|' + 'snmp2_get|snmp2_getnext|snmp2_real_walk|snmp2_set|snmp2_walk|snmp3_get|snmp3_getnext|snmp3_real_walk|snmp3_set|snmp3_walk|' + 'snmp_get_quick_print|snmp_get_valueretrieval|snmp_read_mib|snmp_set_enum_print|snmp_set_oid_numeric_print|snmp_set_oid_output_format|' + 'snmp_set_quick_print|snmp_set_valueretrieval|snmpget|snmpgetnext|snmprealwalk|snmpset|snmpwalk|snmpwalkoid|soapclient|soapfault|' + 'soapheader|soapparam|soapserver|soapvar|socket_accept|socket_bind|socket_clear_error|socket_close|socket_connect|socket_create|' + 'socket_create_listen|socket_create_pair|socket_get_option|socket_get_status|socket_getpeername|socket_getsockname|socket_last_error|' + 'socket_listen|socket_read|socket_recv|socket_recvfrom|socket_select|socket_send|socket_sendto|socket_set_block|socket_set_blocking|' + 'socket_set_nonblock|socket_set_option|socket_set_timeout|socket_shutdown|socket_strerror|socket_write|solr_get_version|solrclient|' + 'solrclientexception|solrdocument|solrdocumentfield|solrexception|solrgenericresponse|solrillegalargumentexception|' + 'solrillegaloperationexception|solrinputdocument|solrmodifiableparams|solrobject|solrparams|solrpingresponse|solrquery|solrqueryresponse|' + 'solrresponse|solrupdateresponse|solrutils|sort|soundex|sphinxclient|spl_autoload|spl_autoload_call|spl_autoload_extensions|' + 'spl_autoload_functions|spl_autoload_register|spl_autoload_unregister|spl_classes|spl_object_hash|splbool|spldoublylinkedlist|splenum|' + 'splfileinfo|splfileobject|splfixedarray|splfloat|splheap|splint|split|spliti|splmaxheap|splminheap|splobjectstorage|splobserver|' + 'splpriorityqueue|splqueue|splstack|splstring|splsubject|spltempfileobject|spoofchecker|sprintf|sql_regcase|sqlite3|sqlite3result|' + 'sqlite3stmt|sqlite_array_query|sqlite_busy_timeout|sqlite_changes|sqlite_close|sqlite_column|sqlite_create_aggregate|' + 'sqlite_create_function|sqlite_current|sqlite_error_string|sqlite_escape_string|sqlite_exec|sqlite_factory|sqlite_fetch_all|' + 'sqlite_fetch_array|sqlite_fetch_column_types|sqlite_fetch_object|sqlite_fetch_single|sqlite_fetch_string|sqlite_field_name|' + 'sqlite_has_more|sqlite_has_prev|sqlite_key|sqlite_last_error|sqlite_last_insert_rowid|sqlite_libencoding|sqlite_libversion|sqlite_next|' + 'sqlite_num_fields|sqlite_num_rows|sqlite_open|sqlite_popen|sqlite_prev|sqlite_query|sqlite_rewind|sqlite_seek|sqlite_single_query|' + 'sqlite_udf_decode_binary|sqlite_udf_encode_binary|sqlite_unbuffered_query|sqlite_valid|sqrt|srand|sscanf|ssdeep_fuzzy_compare|' + 'ssdeep_fuzzy_hash|ssdeep_fuzzy_hash_filename|ssh2_auth_hostbased_file|ssh2_auth_none|ssh2_auth_password|ssh2_auth_pubkey_file|' + 'ssh2_connect|ssh2_exec|ssh2_fetch_stream|ssh2_fingerprint|ssh2_methods_negotiated|ssh2_publickey_add|ssh2_publickey_init|' + 'ssh2_publickey_list|ssh2_publickey_remove|ssh2_scp_recv|ssh2_scp_send|ssh2_sftp|ssh2_sftp_lstat|ssh2_sftp_mkdir|ssh2_sftp_readlink|' + 'ssh2_sftp_realpath|ssh2_sftp_rename|ssh2_sftp_rmdir|ssh2_sftp_stat|ssh2_sftp_symlink|ssh2_sftp_unlink|ssh2_shell|ssh2_tunnel|stat|' + 'stats_absolute_deviation|stats_cdf_beta|stats_cdf_binomial|stats_cdf_cauchy|stats_cdf_chisquare|stats_cdf_exponential|stats_cdf_f|' + 'stats_cdf_gamma|stats_cdf_laplace|stats_cdf_logistic|stats_cdf_negative_binomial|stats_cdf_noncentral_chisquare|stats_cdf_noncentral_f|' + 'stats_cdf_poisson|stats_cdf_t|stats_cdf_uniform|stats_cdf_weibull|stats_covariance|stats_den_uniform|stats_dens_beta|stats_dens_cauchy|' + 'stats_dens_chisquare|stats_dens_exponential|stats_dens_f|stats_dens_gamma|stats_dens_laplace|stats_dens_logistic|' + 'stats_dens_negative_binomial|stats_dens_normal|stats_dens_pmf_binomial|stats_dens_pmf_hypergeometric|stats_dens_pmf_poisson|stats_dens_t|' + 'stats_dens_weibull|stats_harmonic_mean|stats_kurtosis|stats_rand_gen_beta|stats_rand_gen_chisquare|stats_rand_gen_exponential|' + 'stats_rand_gen_f|stats_rand_gen_funiform|stats_rand_gen_gamma|stats_rand_gen_ibinomial|stats_rand_gen_ibinomial_negative|' + 'stats_rand_gen_int|stats_rand_gen_ipoisson|stats_rand_gen_iuniform|stats_rand_gen_noncenral_chisquare|stats_rand_gen_noncentral_f|' + 'stats_rand_gen_noncentral_t|stats_rand_gen_normal|stats_rand_gen_t|stats_rand_get_seeds|stats_rand_phrase_to_seeds|stats_rand_ranf|' + 'stats_rand_setall|stats_skew|stats_standard_deviation|stats_stat_binomial_coef|stats_stat_correlation|stats_stat_gennch|' + 'stats_stat_independent_t|stats_stat_innerproduct|stats_stat_noncentral_t|stats_stat_paired_t|stats_stat_percentile|stats_stat_powersum|' + 'stats_variance|stomp|stomp_connect_error|stomp_version|stompexception|stompframe|str_getcsv|str_ireplace|str_pad|str_repeat|str_replace|' + 'str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|stream_bucket_append|stream_bucket_make_writeable|' + 'stream_bucket_new|stream_bucket_prepend|stream_context_create|stream_context_get_default|stream_context_get_options|' + 'stream_context_get_params|stream_context_set_default|stream_context_set_option|stream_context_set_params|stream_copy_to_stream|' + 'stream_encoding|stream_filter_append|stream_filter_prepend|stream_filter_register|stream_filter_remove|stream_get_contents|' + 'stream_get_filters|stream_get_line|stream_get_meta_data|stream_get_transports|stream_get_wrappers|stream_is_local|' + 'stream_notification_callback|stream_register_wrapper|stream_resolve_include_path|stream_select|stream_set_blocking|stream_set_read_buffer|' + 'stream_set_timeout|stream_set_write_buffer|stream_socket_accept|stream_socket_client|stream_socket_enable_crypto|stream_socket_get_name|' + 'stream_socket_pair|stream_socket_recvfrom|stream_socket_sendto|stream_socket_server|stream_socket_shutdown|stream_supports_lock|' + 'stream_wrapper_register|stream_wrapper_restore|stream_wrapper_unregister|streamwrapper|strftime|strip_tags|stripcslashes|stripos|' + 'stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|' + 'strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare|substr_count|substr_replace|svm|svmmodel|svn_add|' + 'svn_auth_get_parameter|svn_auth_set_parameter|svn_blame|svn_cat|svn_checkout|svn_cleanup|svn_client_version|svn_commit|svn_delete|' + 'svn_diff|svn_export|svn_fs_abort_txn|svn_fs_apply_text|svn_fs_begin_txn2|svn_fs_change_node_prop|svn_fs_check_path|' + 'svn_fs_contents_changed|svn_fs_copy|svn_fs_delete|svn_fs_dir_entries|svn_fs_file_contents|svn_fs_file_length|svn_fs_is_dir|svn_fs_is_file|' + 'svn_fs_make_dir|svn_fs_make_file|svn_fs_node_created_rev|svn_fs_node_prop|svn_fs_props_changed|svn_fs_revision_prop|svn_fs_revision_root|' + 'svn_fs_txn_root|svn_fs_youngest_rev|svn_import|svn_log|svn_ls|svn_mkdir|svn_repos_create|svn_repos_fs|svn_repos_fs_begin_txn_for_commit|' + 'svn_repos_fs_commit_txn|svn_repos_hotcopy|svn_repos_open|svn_repos_recover|svn_revert|svn_status|svn_update|swf_actiongeturl|' + 'swf_actiongotoframe|swf_actiongotolabel|swf_actionnextframe|swf_actionplay|swf_actionprevframe|swf_actionsettarget|swf_actionstop|' + 'swf_actiontogglequality|swf_actionwaitforframe|swf_addbuttonrecord|swf_addcolor|swf_closefile|swf_definebitmap|swf_definefont|' + 'swf_defineline|swf_definepoly|swf_definerect|swf_definetext|swf_endbutton|swf_enddoaction|swf_endshape|swf_endsymbol|swf_fontsize|' + 'swf_fontslant|swf_fonttracking|swf_getbitmapinfo|swf_getfontinfo|swf_getframe|swf_labelframe|swf_lookat|swf_modifyobject|swf_mulcolor|' + 'swf_nextid|swf_oncondition|swf_openfile|swf_ortho|swf_ortho2|swf_perspective|swf_placeobject|swf_polarview|swf_popmatrix|swf_posround|' + 'swf_pushmatrix|swf_removeobject|swf_rotate|swf_scale|swf_setfont|swf_setframe|swf_shapearc|swf_shapecurveto|swf_shapecurveto3|' + 'swf_shapefillbitmapclip|swf_shapefillbitmaptile|swf_shapefilloff|swf_shapefillsolid|swf_shapelinesolid|swf_shapelineto|swf_shapemoveto|' + 'swf_showframe|swf_startbutton|swf_startdoaction|swf_startshape|swf_startsymbol|swf_textwidth|swf_translate|swf_viewport|swfaction|' + 'swfbitmap|swfbutton|swfdisplayitem|swffill|swffont|swffontchar|swfgradient|swfmorph|swfmovie|swfprebuiltclip|swfshape|swfsound|' + 'swfsoundinstance|swfsprite|swftext|swftextfield|swfvideostream|swish_construct|swish_getmetalist|swish_getpropertylist|swish_prepare|' + 'swish_query|swishresult_getmetalist|swishresult_stem|swishresults_getparsedwords|swishresults_getremovedstopwords|swishresults_nextresult|' + 'swishresults_seekresult|swishsearch_execute|swishsearch_resetlimit|swishsearch_setlimit|swishsearch_setphrasedelimiter|' + 'swishsearch_setsort|swishsearch_setstructure|sybase_affected_rows|sybase_close|sybase_connect|sybase_data_seek|' + 'sybase_deadlock_retry_count|sybase_fetch_array|sybase_fetch_assoc|sybase_fetch_field|sybase_fetch_object|sybase_fetch_row|' + 'sybase_field_seek|sybase_free_result|sybase_get_last_message|sybase_min_client_severity|sybase_min_error_severity|' + 'sybase_min_message_severity|sybase_min_server_severity|sybase_num_fields|sybase_num_rows|sybase_pconnect|sybase_query|sybase_result|' + 'sybase_select_db|sybase_set_message_handler|sybase_unbuffered_query|symlink|sys_get_temp_dir|sys_getloadavg|syslog|system|tag|tan|tanh|' + 'tcpwrap_check|tempnam|textdomain|tidy|tidy_access_count|tidy_config_count|tidy_diagnose|tidy_error_count|tidy_get_error_buffer|' + 'tidy_get_output|tidy_load_config|tidy_reset_config|tidy_save_config|tidy_set_encoding|tidy_setopt|tidy_warning_count|tidynode|time|' + 'time_nanosleep|time_sleep_until|timezone_abbreviations_list|timezone_identifiers_list|timezone_location_get|timezone_name_from_abbr|' + 'timezone_name_get|timezone_offset_get|timezone_open|timezone_transitions_get|timezone_version_get|tmpfile|token_get_all|token_name|' + 'tokyotyrant|tokyotyrantquery|tokyotyranttable|tostring|tostring|touch|transliterator|traversable|trigger_error|trim|uasort|ucfirst|' + 'ucwords|udm_add_search_limit|udm_alloc_agent|udm_alloc_agent_array|udm_api_version|udm_cat_list|udm_cat_path|udm_check_charset|' + 'udm_check_stored|udm_clear_search_limits|udm_close_stored|udm_crc32|udm_errno|udm_error|udm_find|udm_free_agent|udm_free_ispell_data|' + 'udm_free_res|udm_get_doc_count|udm_get_res_field|udm_get_res_param|udm_hash32|udm_load_ispell_data|udm_open_stored|udm_set_agent_param|' + 'uksort|umask|underflowexception|unexpectedvalueexception|uniqid|unixtojd|unlink|unpack|unregister_tick_function|unserialize|unset|' + 'urldecode|urlencode|use_soap_error_handler|user_error|usleep|usort|utf8_decode|utf8_encode|v8js|v8jsexception|var_dump|var_export|variant|' + 'variant_abs|variant_add|variant_and|variant_cast|variant_cat|variant_cmp|variant_date_from_timestamp|variant_date_to_timestamp|' + 'variant_div|variant_eqv|variant_fix|variant_get_type|variant_idiv|variant_imp|variant_int|variant_mod|variant_mul|variant_neg|variant_not|' + 'variant_or|variant_pow|variant_round|variant_set|variant_set_type|variant_sub|variant_xor|version_compare|vfprintf|virtual|' + 'vpopmail_add_alias_domain|vpopmail_add_alias_domain_ex|vpopmail_add_domain|vpopmail_add_domain_ex|vpopmail_add_user|vpopmail_alias_add|' + 'vpopmail_alias_del|vpopmail_alias_del_domain|vpopmail_alias_get|vpopmail_alias_get_all|vpopmail_auth_user|vpopmail_del_domain|' + 'vpopmail_del_domain_ex|vpopmail_del_user|vpopmail_error|vpopmail_passwd|vpopmail_set_user_quota|vprintf|vsprintf|w32api_deftype|' + 'w32api_init_dtype|w32api_invoke_function|w32api_register_function|w32api_set_call_method|wddx_add_vars|wddx_deserialize|wddx_packet_end|' + 'wddx_packet_start|wddx_serialize_value|wddx_serialize_vars|win32_continue_service|win32_create_service|win32_delete_service|' + 'win32_get_last_control_message|win32_pause_service|win32_ps_list_procs|win32_ps_stat_mem|win32_ps_stat_proc|win32_query_service_status|' + 'win32_set_service_status|win32_start_service|win32_start_service_ctrl_dispatcher|win32_stop_service|wincache_fcache_fileinfo|' + 'wincache_fcache_meminfo|wincache_lock|wincache_ocache_fileinfo|wincache_ocache_meminfo|wincache_refresh_if_changed|' + 'wincache_rplist_fileinfo|wincache_rplist_meminfo|wincache_scache_info|wincache_scache_meminfo|wincache_ucache_add|wincache_ucache_cas|' + 'wincache_ucache_clear|wincache_ucache_dec|wincache_ucache_delete|wincache_ucache_exists|wincache_ucache_get|wincache_ucache_inc|' + 'wincache_ucache_info|wincache_ucache_meminfo|wincache_ucache_set|wincache_unlock|wordwrap|xattr_get|xattr_list|xattr_remove|xattr_set|' + 'xattr_supported|xdiff_file_bdiff|xdiff_file_bdiff_size|xdiff_file_bpatch|xdiff_file_diff|xdiff_file_diff_binary|xdiff_file_merge3|' + 'xdiff_file_patch|xdiff_file_patch_binary|xdiff_file_rabdiff|xdiff_string_bdiff|xdiff_string_bdiff_size|xdiff_string_bpatch|' + 'xdiff_string_diff|xdiff_string_diff_binary|xdiff_string_merge3|xdiff_string_patch|xdiff_string_patch_binary|xdiff_string_rabdiff|' + 'xhprof_disable|xhprof_enable|xhprof_sample_disable|xhprof_sample_enable|xml_error_string|xml_get_current_byte_index|' + 'xml_get_current_column_number|xml_get_current_line_number|xml_get_error_code|xml_parse|xml_parse_into_struct|xml_parser_create|' + 'xml_parser_create_ns|xml_parser_free|xml_parser_get_option|xml_parser_set_option|xml_set_character_data_handler|xml_set_default_handler|' + 'xml_set_element_handler|xml_set_end_namespace_decl_handler|xml_set_external_entity_ref_handler|xml_set_notation_decl_handler|' + 'xml_set_object|xml_set_processing_instruction_handler|xml_set_start_namespace_decl_handler|xml_set_unparsed_entity_decl_handler|xmlreader|' + 'xmlrpc_decode|xmlrpc_decode_request|xmlrpc_encode|xmlrpc_encode_request|xmlrpc_get_type|xmlrpc_is_fault|xmlrpc_parse_method_descriptions|' + 'xmlrpc_server_add_introspection_data|xmlrpc_server_call_method|xmlrpc_server_create|xmlrpc_server_destroy|' + 'xmlrpc_server_register_introspection_callback|xmlrpc_server_register_method|xmlrpc_set_type|xmlwriter_end_attribute|xmlwriter_end_cdata|' + 'xmlwriter_end_comment|xmlwriter_end_document|xmlwriter_end_dtd|xmlwriter_end_dtd_attlist|xmlwriter_end_dtd_element|' + 'xmlwriter_end_dtd_entity|xmlwriter_end_element|xmlwriter_end_pi|xmlwriter_flush|xmlwriter_full_end_element|xmlwriter_open_memory|' + 'xmlwriter_open_uri|xmlwriter_output_memory|xmlwriter_set_indent|xmlwriter_set_indent_string|xmlwriter_start_attribute|' + 'xmlwriter_start_attribute_ns|xmlwriter_start_cdata|xmlwriter_start_comment|xmlwriter_start_document|xmlwriter_start_dtd|' + 'xmlwriter_start_dtd_attlist|xmlwriter_start_dtd_element|xmlwriter_start_dtd_entity|xmlwriter_start_element|xmlwriter_start_element_ns|' + 'xmlwriter_start_pi|xmlwriter_text|xmlwriter_write_attribute|xmlwriter_write_attribute_ns|xmlwriter_write_cdata|xmlwriter_write_comment|' + 'xmlwriter_write_dtd|xmlwriter_write_dtd_attlist|xmlwriter_write_dtd_element|xmlwriter_write_dtd_entity|xmlwriter_write_element|' + 'xmlwriter_write_element_ns|xmlwriter_write_pi|xmlwriter_write_raw|xpath_eval|xpath_eval_expression|xpath_new_context|xpath_register_ns|' + 'xpath_register_ns_auto|xptr_eval|xptr_new_context|xslt_backend_info|xslt_backend_name|xslt_backend_version|xslt_create|xslt_errno|' + 'xslt_error|xslt_free|xslt_getopt|xslt_process|xslt_set_base|xslt_set_encoding|xslt_set_error_handler|xslt_set_log|xslt_set_object|' + 'xslt_set_sax_handler|xslt_set_sax_handlers|xslt_set_scheme_handler|xslt_set_scheme_handlers|xslt_setopt|xsltprocessor|yaml_emit|' + 'yaml_emit_file|yaml_parse|yaml_parse_file|yaml_parse_url|yaz_addinfo|yaz_ccl_conf|yaz_ccl_parse|yaz_close|yaz_connect|yaz_database|' + 'yaz_element|yaz_errno|yaz_error|yaz_es|yaz_es_result|yaz_get_option|yaz_hits|yaz_itemorder|yaz_present|yaz_range|yaz_record|yaz_scan|' + 'yaz_scan_result|yaz_schema|yaz_search|yaz_set_option|yaz_sort|yaz_syntax|yaz_wait|yp_all|yp_cat|yp_err_string|yp_errno|yp_first|' + 'yp_get_default_domain|yp_master|yp_match|yp_next|yp_order|zend_logo_guid|zend_thread_id|zend_version|zip_close|zip_entry_close|' + 'zip_entry_compressedsize|zip_entry_compressionmethod|zip_entry_filesize|zip_entry_name|zip_entry_open|zip_entry_read|zip_open|zip_read|' + 'ziparchive|ziparchive_addemptydir|ziparchive_addfile|ziparchive_addfromstring|ziparchive_close|ziparchive_deleteindex|' + 'ziparchive_deletename|ziparchive_extractto|ziparchive_getarchivecomment|ziparchive_getcommentindex|ziparchive_getcommentname|' + 'ziparchive_getfromindex|ziparchive_getfromname|ziparchive_getnameindex|ziparchive_getstatusstring|ziparchive_getstream|' + 'ziparchive_locatename|ziparchive_open|ziparchive_renameindex|ziparchive_renamename|ziparchive_setCommentName|ziparchive_setarchivecomment|' + 'ziparchive_setcommentindex|ziparchive_statindex|ziparchive_statname|ziparchive_unchangeall|ziparchive_unchangearchive|' + 'ziparchive_unchangeindex|ziparchive_unchangename|zlib_get_coding_type').split('|') ); var keywords = lang.arrayToMap( ('abstract|and|array|as|break|case|catch|class|clone|const|continue|declare|default|do|else|elseif|enddeclare|endfor|endforeach|endif|' + 'endswitch|endwhile|extends|final|for|foreach|function|global|goto|if|implements|interface|instanceof|namespace|new|or|private|protected|' + 'public|static|switch|throw|try|use|var|while|xor').split('|') ); var languageConstructs = lang.arrayToMap( ('die|echo|empty|exit|eval|include|include_once|isset|list|require|require_once|return|print|unset').split('|') ); var builtinConstants = lang.arrayToMap( ('true|false|null|__CLASS__|__DIR__|__FILE__|__LINE__|__METHOD__|__FUNCTION__|__NAMESPACE__').split('|') ); var builtinVariables = lang.arrayToMap( ('$GLOBALS|$_SERVER|$_GET|$_POST|$_FILES|$_REQUEST|$_SESSION|$_ENV|$_COOKIE|$php_errormsg|$HTTP_RAW_POST_DATA|' + '$http_response_header|$argc|$argv').split('|') ); var builtinFunctionsDeprecated = lang.arrayToMap( ('key_exists|cairo_matrix_create_scale|cairo_matrix_create_translate|call_user_method|call_user_method_array|com_addref|com_get|' + 'com_invoke|com_isenum|com_load|com_release|com_set|connection_timeout|cubrid_load_from_glo|cubrid_new_glo|cubrid_save_to_glo|' + 'cubrid_send_glo|define_syslog_variables|dl|ereg|ereg_replace|eregi|eregi_replace|hw_documentattributes|hw_documentbodytag|' + 'hw_documentsize|hw_outputdocument|imagedashedline|maxdb_bind_param|maxdb_bind_result|maxdb_client_encoding|maxdb_close_long_data|' + 'maxdb_execute|maxdb_fetch|maxdb_get_metadata|maxdb_param_count|maxdb_send_long_data|mcrypt_ecb|mcrypt_generic_end|mime_content_type|' + 'mysql_createdb|mysql_dbname|mysql_db_query|mysql_drop_db|mysql_dropdb|mysql_escape_string|mysql_fieldflags|mysql_fieldflags|' + 'mysql_fieldname|mysql_fieldtable|mysql_fieldtype|mysql_freeresult|mysql_listdbs|mysql_list_fields|mysql_listfields|mysql_list_tables|' + 'mysql_listtables|mysql_numfields|mysql_numrows|mysql_selectdb|mysql_tablename|mysqli_bind_param|mysqli_bind_result|' + 'mysqli_disable_reads_from_master|mysqli_disable_rpl_parse|mysqli_enable_reads_from_master|mysqli_enable_rpl_parse|mysqli_execute|' + 'mysqli_fetch|mysqli_get_metadata|mysqli_master_query|mysqli_param_count|mysqli_rpl_parse_enabled|mysqli_rpl_probe|mysqli_rpl_query_type|' + 'mysqli_send_long_data|mysqli_send_query|mysqli_slave_query|ocibindbyname|ocicancel|ocicloselob|ocicollappend|ocicollassign|' + 'ocicollassignelem|ocicollgetelem|ocicollmax|ocicollsize|ocicolltrim|ocicolumnisnull|ocicolumnname|ocicolumnprecision|ocicolumnscale|' + 'ocicolumnsize|ocicolumntype|ocicolumntyperaw|ocicommit|ocidefinebyname|ocierror|ociexecute|ocifetch|ocifetchinto|ocifetchstatement|' + 'ocifreecollection|ocifreecursor|ocifreedesc|ocifreestatement|ociinternaldebug|ociloadlob|ocilogoff|ocilogon|ocinewcollection|' + 'ocinewcursor|ocinewdescriptor|ocinlogon|ocinumcols|ociparse|ociplogon|ociresult|ocirollback|ocirowcount|ocisavelob|ocisavelobfile|' + 'ociserverversion|ocisetprefetch|ocistatementtype|ociwritelobtofile|ociwritetemporarylob|PDF_add_annotation|PDF_add_bookmark|' + 'PDF_add_launchlink|PDF_add_locallink|PDF_add_note|PDF_add_outline|PDF_add_pdflink|PDF_add_weblink|PDF_attach_file|PDF_begin_page|' + 'PDF_begin_template|PDF_close_pdi|PDF_close|PDF_findfont|PDF_get_font|PDF_get_fontname|PDF_get_fontsize|PDF_get_image_height|' + 'PDF_get_image_width|PDF_get_majorversion|PDF_get_minorversion|PDF_get_pdi_parameter|PDF_get_pdi_value|PDF_open_ccitt|PDF_open_file|' + 'PDF_open_gif|PDF_open_image_file|PDF_open_image|PDF_open_jpeg|PDF_open_pdi|PDF_open_tiff|PDF_place_image|PDF_place_pdi_page|' + 'PDF_set_border_color|PDF_set_border_dash|PDF_set_border_style|PDF_set_char_spacing|PDF_set_duration|PDF_set_horiz_scaling|' + 'PDF_set_info_author|PDF_set_info_creator|PDF_set_info_keywords|PDF_set_info_subject|PDF_set_info_title|PDF_set_leading|' + 'PDF_set_text_matrix|PDF_set_text_rendering|PDF_set_text_rise|PDF_set_word_spacing|PDF_setgray_fill|PDF_setgray_stroke|PDF_setgray|' + 'PDF_setpolydash|PDF_setrgbcolor_fill|PDF_setrgbcolor_stroke|PDF_setrgbcolor|PDF_show_boxed|php_check_syntax|px_set_tablename|' + 'px_set_targetencoding|runkit_sandbox_output_handler|session_is_registered|session_register|session_unregister' + 'set_magic_quotes_runtime|magic_quotes_runtime|set_socket_blocking|socket_set_blocking|set_socket_timeout|socket_set_timeout|split|spliti|' + 'sql_regcase').split('|') ); var keywordsDeprecated = lang.arrayToMap( ('cfunction|old_function').split('|') ); var futureReserved = lang.arrayToMap([]); this.$rules = { "start" : [ { token : "comment", regex : /(?:#|\/\/)(?:[^?]|\?[^>])*/ }, docComment.getStartRule("doc-start"), { token : "comment", // multi line comment regex : "\\/\\*", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/][gimy]*\\s*(?=[).,;]|$)" }, { token : "string", // " string start regex : '"', next : "qqstring" }, { token : "string", // ' string start regex : "'", next : "qstring" }, { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F]+\\b" }, { token : "constant.numeric", // float regex : "[+-]?\\d+(?:(?:\\.\\d*)?(?:[eE][+-]?\\d+)?)?\\b" }, { token : "constant.language", // constants regex : "\\b(?:DEFAULT_INCLUDE_PATH|E_(?:ALL|CO(?:MPILE_(?:ERROR|WARNING)|RE_(?:ERROR|WARNING))|" + "ERROR|NOTICE|PARSE|STRICT|USER_(?:ERROR|NOTICE|WARNING)|WARNING)|P(?:EAR_(?:EXTENSION_DIR|INSTALL_DIR)|" + "HP_(?:BINDIR|CONFIG_FILE_(?:PATH|SCAN_DIR)|DATADIR|E(?:OL|XTENSION_DIR)|INT_(?:MAX|SIZE)|" + "L(?:IBDIR|OCALSTATEDIR)|O(?:S|UTPUT_HANDLER_(?:CONT|END|START))|PREFIX|S(?:API|HLIB_SUFFIX|YSCONFDIR)|" + "VERSION))|__COMPILER_HALT_OFFSET__)\\b" }, { token : ["keyword", "text", "support.class"], regex : "\\b(new)(\\s+)(\\w+)" }, { token : ["support.class", "keyword.operator"], regex : "\\b(\\w+)(::)" }, { token : "constant.language", // constants regex : "\\b(?:A(?:B(?:DAY_(?:1|2|3|4|5|6|7)|MON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9))|LT_DIGITS|M_STR|" + "SSERT_(?:ACTIVE|BAIL|CALLBACK|QUIET_EVAL|WARNING))|C(?:ASE_(?:LOWER|UPPER)|HAR_MAX|" + "O(?:DESET|NNECTION_(?:ABORTED|NORMAL|TIMEOUT)|UNT_(?:NORMAL|RECURSIVE))|" + "R(?:EDITS_(?:ALL|DOCS|FULLPAGE|G(?:ENERAL|ROUP)|MODULES|QA|SAPI)|NCYSTR|" + "YPT_(?:BLOWFISH|EXT_DES|MD5|S(?:ALT_LENGTH|TD_DES)))|URRENCY_SYMBOL)|D(?:AY_(?:1|2|3|4|5|6|7)|" + "ECIMAL_POINT|IRECTORY_SEPARATOR|_(?:FMT|T_FMT))|E(?:NT_(?:COMPAT|NOQUOTES|QUOTES)|RA(?:_(?:D_(?:FMT|T_FMT)|" + "T_FMT|YEAR)|)|XTR_(?:IF_EXISTS|OVERWRITE|PREFIX_(?:ALL|I(?:F_EXISTS|NVALID)|SAME)|SKIP))|FRAC_DIGITS|GROUPING|" + "HTML_(?:ENTITIES|SPECIALCHARS)|IN(?:FO_(?:ALL|C(?:ONFIGURATION|REDITS)|ENVIRONMENT|GENERAL|LICENSE|MODULES|VARIABLES)|" + "I_(?:ALL|PERDIR|SYSTEM|USER)|T_(?:CURR_SYMBOL|FRAC_DIGITS))|L(?:C_(?:ALL|C(?:OLLATE|TYPE)|M(?:ESSAGES|ONETARY)|NUMERIC|TIME)|" + "O(?:CK_(?:EX|NB|SH|UN)|G_(?:A(?:LERT|UTH(?:PRIV|))|C(?:ONS|R(?:IT|ON))|D(?:AEMON|EBUG)|E(?:MERG|RR)|INFO|KERN|" + "L(?:OCAL(?:0|1|2|3|4|5|6|7)|PR)|MAIL|N(?:DELAY|EWS|O(?:TICE|WAIT))|ODELAY|P(?:ERROR|ID)|SYSLOG|U(?:SER|UCP)|WARNING)))|" + "M(?:ON_(?:1(?:0|1|2|)|2|3|4|5|6|7|8|9|DECIMAL_POINT|GROUPING|THOUSANDS_SEP)|_(?:1_PI|2_(?:PI|SQRTPI)|E|L(?:N(?:10|2)|" + "OG(?:10E|2E))|PI(?:_(?:2|4)|)|SQRT(?:1_2|2)))|N(?:EGATIVE_SIGN|O(?:EXPR|STR)|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "P(?:ATH(?:INFO_(?:BASENAME|DIRNAME|EXTENSION)|_SEPARATOR)|M_STR|OSITIVE_SIGN|_(?:CS_PRECEDES|S(?:EP_BY_SPACE|IGN_POSN)))|" + "RADIXCHAR|S(?:EEK_(?:CUR|END|SET)|ORT_(?:ASC|DESC|NUMERIC|REGULAR|STRING)|TR_PAD_(?:BOTH|LEFT|RIGHT))|" + "T(?:HOUS(?:ANDS_SEP|EP)|_FMT(?:_AMPM|))|YES(?:EXPR|STR)|STD(?:IN|OUT|ERR))\\b" }, { token : function(value) { if (keywords.hasOwnProperty(value)) return "keyword"; else if (builtinConstants.hasOwnProperty(value)) return "constant.language"; else if (builtinVariables.hasOwnProperty(value)) return "variable.language"; else if (futureReserved.hasOwnProperty(value)) return "invalid.illegal"; else if (builtinFunctions.hasOwnProperty(value)) return "support.function"; else if (value == "debugger") return "invalid.deprecated"; else if(value.match(/^(\$[a-zA-Z_\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*|self|parent)$/)) return "variable"; return "identifier"; }, regex : /[a-zA-Z_$\x7f-\uffff][a-zA-Z0-9_\x7f-\uffff]*/ }, { onMatch : function(value, currentSate, state) { value = value.substr(3); if (value[0] == "'" || value[0] == '"') value = value.slice(1, -1); state.unshift(this.next, value); return "markup.list"; }, regex : /<<<(?:\w+|'\w+'|"\w+")$/, next: "heredoc" }, { token : "keyword.operator", regex : "::|!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|!=|!==|<=|>=|=>|<<=|>>=|>>>=|<>|<|>|=|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "heredoc" : [ { onMatch : function(value, currentSate, stack) { if (stack[1] != value) return "string"; stack.shift(); stack.shift(); return "markup.list"; }, regex : "^\\w+(?=;?$)", next: "start" }, { token: "string", regex : ".*" } ], "comment" : [ { token : "comment", regex : "\\*\\/", next : "start" }, { defaultToken : "comment" } ], "qqstring" : [ { token : "constant.language.escape", regex : '\\\\(?:[nrtvef\\\\"$]|[0-7]{1,3}|x[0-9A-Fa-f]{1,2})' }, { token : "variable", regex : /\$[\w]+(?:\[[\w\]+]|[=\-]>\w+)?/ }, { token : "variable", regex : /\$\{[^"\}]+\}?/ // this is wrong but ok for now }, {token : "string", regex : '"', next : "start"}, {defaultToken : "string"} ], "qstring" : [ {token : "constant.language.escape", regex : /\\['\\]/}, {token : "string", regex : "'", next : "start"}, {defaultToken : "string"} ] }; this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("start") ]); }; oop.inherits(PhpLangHighlightRules, TextHighlightRules); var PhpHighlightRules = function() { HtmlHighlightRules.call(this); var startRules = [ { token : "support.php_tag", // php open tag regex : "<\\?(?:php|=)?", push : "php-start" } ]; var endRules = [ { token : "support.php_tag", // php close tag regex : "\\?>", next : "pop" } ]; for (var key in this.$rules) this.$rules[key].unshift.apply(this.$rules[key], startRules); this.embedRules(PhpLangHighlightRules, "php-", endRules, ["start"]); this.normalizeRules(); }; oop.inherits(PhpHighlightRules, HtmlHighlightRules); exports.PhpHighlightRules = PhpHighlightRules; exports.PhpLangHighlightRules = PhpLangHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var getWrapped = function(selection, selected, opening, closing) { var rowDiff = selection.end.row - selection.start.row; return { text: opening + selected + closing, selection: [ 0, selection.start.column + 1, rowDiff, selection.end.column + (rowDiff ? 0 : 1) ] }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '{', '}'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '(', ')'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '[', ']'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, quote, quote); } else if (!selected) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); var rightChar = line.substring(cursor.column, cursor.column + 1); var token = session.getTokenAt(cursor.row, cursor.column); var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); if (leftChar == "\\" && token && /escape/.test(token.type)) return null; var stringBefore = token && /string|escape/.test(token.type); var stringAfter = !rightToken || /string|escape/.test(rightToken.type); var pair; if (rightChar == quote) { pair = stringBefore !== stringAfter; } else { if (stringBefore && !stringAfter) return null; // wrap string with different quote if (stringBefore && stringAfter) return null; // do not pair quotes inside strings var wordRe = session.$mode.tokenRe; wordRe.lastIndex = 0; var isWordBefore = wordRe.test(leftChar); wordRe.lastIndex = 0; var isWordAfter = wordRe.test(leftChar); if (isWordBefore || isWordAfter) return null; // before or after alphanumeric if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) return null; // there is rightChar and it isn't closing pair = true; } return { text: pair ? quote + quote : "", selection: [1,1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*\:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getCursorPosition(); var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": ["manifest"], "head": [], "title": [], "base": ["href", "target"], "link": ["href", "hreflang", "rel", "media", "type", "sizes"], "meta": ["http-equiv", "name", "content", "charset"], "style": ["type", "media", "scoped"], "script": ["charset", "type", "src", "defer", "async"], "noscript": ["href"], "body": ["onafterprint", "onbeforeprint", "onbeforeunload", "onhashchange", "onmessage", "onoffline", "onpopstate", "onredo", "onresize", "onstorage", "onundo", "onunload"], "section": [], "nav": [], "article": ["pubdate"], "aside": [], "h1": [], "h2": [], "h3": [], "h4": [], "h5": [], "h6": [], "header": [], "footer": [], "address": [], "main": [], "p": [], "hr": [], "pre": [], "blockquote": ["cite"], "ol": ["start", "reversed"], "ul": [], "li": ["value"], "dl": [], "dt": [], "dd": [], "figure": [], "figcaption": [], "div": [], "a": ["href", "target", "ping", "rel", "media", "hreflang", "type"], "em": [], "strong": [], "small": [], "s": [], "cite": [], "q": ["cite"], "dfn": [], "abbr": [], "data": [], "time": ["datetime"], "code": [], "var": [], "samp": [], "kbd": [], "sub": [], "sup": [], "i": [], "b": [], "u": [], "mark": [], "ruby": [], "rt": [], "rp": [], "bdi": [], "bdo": [], "span": [], "br": [], "wbr": [], "ins": ["cite", "datetime"], "del": ["cite", "datetime"], "img": ["alt", "src", "height", "width", "usemap", "ismap"], "iframe": ["name", "src", "height", "width", "sandbox", "seamless"], "embed": ["src", "height", "width", "type"], "object": ["param", "data", "type", "height" , "width", "usemap", "name", "form", "classid"], "param": ["name", "value"], "video": ["src", "autobuffer", "autoplay", "loop", "controls", "width", "height", "poster"], "audio": ["src", "autobuffer", "autoplay", "loop", "controls"], "source": ["src", "type", "media"], "track": ["kind", "src", "srclang", "label", "default"], "canvas": ["width", "height"], "map": ["name"], "area": ["shape", "coords", "href", "hreflang", "alt", "target", "media", "rel", "ping", "type"], "svg": [], "math": [], "table": ["summary"], "caption": [], "colgroup": ["span"], "col": ["span"], "tbody": [], "thead": [], "tfoot": [], "tr": [], "td": ["headers", "rowspan", "colspan"], "th": ["headers", "rowspan", "colspan", "scope"], "form": ["accept-charset", "action", "autocomplete", "enctype", "method", "name", "novalidate", "target"], "fieldset": ["disabled", "form", "name"], "legend": [], "label": ["form", "for"], "input": ["type", "accept", "alt", "autocomplete", "checked", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "height", "list", "max", "maxlength", "min", "multiple", "pattern", "placeholder", "readonly", "required", "size", "src", "step", "width", "files", "value"], "button": ["autofocus", "disabled", "form", "formaction", "formenctype", "formmethod", "formnovalidate", "formtarget", "name", "value", "type"], "select": ["autofocus", "disabled", "form", "multiple", "name", "size"], "datalist": [], "optgroup": ["disabled", "label"], "option": ["disabled", "selected", "label", "value"], "textarea": ["autofocus", "disabled", "form", "maxlength", "name", "placeholder", "readonly", "required", "rows", "cols", "wrap"], "keygen": ["autofocus", "challenge", "disabled", "form", "keytype", "name"], "output": ["for", "form", "name"], "progress": ["value", "max"], "meter": ["value", "min", "max", "low", "high", "optimum"], "details": ["open"], "summary": [], "command": ["type", "label", "icon", "disabled", "checked", "radiogroup", "command"], "menu": ["type", "label"], "dialog": ["open"] }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompetions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompetions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(attributeMap[tagName]); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/php",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/php_highlight_rules","ace/mode/php_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle","ace/unicode","ace/mode/html","ace/mode/javascript","ace/mode/css"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var PhpHighlightRules = require("./php_highlight_rules").PhpHighlightRules; var PhpLangHighlightRules = require("./php_highlight_rules").PhpLangHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var unicode = require("../unicode"); var HtmlMode = require("./html").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var PhpMode = function(opts) { this.HighlightRules = PhpLangHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(PhpMode, TextMode); (function() { this.tokenRe = new RegExp("^[" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\_]+", "g" ); this.nonTokenRe = new RegExp("^(?:[^" + unicode.packages.L + unicode.packages.Mn + unicode.packages.Mc + unicode.packages.Nd + unicode.packages.Pc + "\_]|\s])+", "g" ); this.lineCommentStart = ["//", "#"]; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[\:]\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState != "doc-start") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.$id = "ace/mode/php-inline"; }).call(PhpMode.prototype); var Mode = function(opts) { if (opts && opts.inline) { var mode = new PhpMode(); mode.createWorker = this.createWorker; mode.inlinePhp = true; return mode; } HtmlMode.call(this); this.HighlightRules = PhpHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode, "php-": PhpMode }); this.foldingRules.subModes["php-"] = new CStyleFoldMode(); }; oop.inherits(Mode, HtmlMode); (function() { this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/php_worker", "PhpWorker"); worker.attachToDocument(session.getDocument()); if (this.inlinePhp) worker.call("setOptions", [{inline: true}]); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/php"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/libs/pdfjs-1.6.210p2/pdf.js
11,515
/* Copyright 2012 Mozilla Foundation * * 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. */ /* jshint globalstrict: false */ /* umdutils ignore */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define('pdfjs-dist/build/pdf', ['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.pdfjsDistBuildPdf = {})); } }(this, function (exports) { // Use strict in our context only - users might not want it 'use strict'; var pdfjsVersion = '1.6.210'; var pdfjsBuild = '4ce2356'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { (function (root, factory) { { factory((root.pdfjsSharedUtil = {})); } }(this, function (exports) { var globalScope = (typeof window !== 'undefined') ? window : (typeof global !== 'undefined') ? global : (typeof self !== 'undefined') ? self : this; var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { TEXT: 1, LINK: 2, FREETEXT: 3, LINE: 4, SQUARE: 5, CIRCLE: 6, POLYGON: 7, POLYLINE: 8, HIGHLIGHT: 9, UNDERLINE: 10, SQUIGGLY: 11, STRIKEOUT: 12, STAMP: 13, CARET: 14, INK: 15, POPUP: 16, FILEATTACHMENT: 17, SOUND: 18, MOVIE: 19, WIDGET: 20, SCREEN: 21, PRINTERMARK: 22, TRAPNET: 23, WATERMARK: 24, THREED: 25, REDACT: 26 }; var AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, PRINT: 0x04, NOZOOM: 0x08, NOROTATE: 0x10, NOVIEW: 0x20, READONLY: 0x40, LOCKED: 0x80, TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; var AnnotationFieldFlag = { READONLY: 0x0000001, REQUIRED: 0x0000002, NOEXPORT: 0x0000004, MULTILINE: 0x0001000, PASSWORD: 0x0002000, NOTOGGLETOOFF: 0x0004000, RADIO: 0x0008000, PUSHBUTTON: 0x0010000, COMBO: 0x0020000, EDIT: 0x0040000, SORT: 0x0080000, FILESELECT: 0x0100000, MULTISELECT: 0x0200000, DONOTSPELLCHECK: 0x0400000, DONOTSCROLL: 0x0800000, COMB: 0x1000000, RICHTEXT: 0x2000000, RADIOSINUNISON: 0x2000000, COMMITONSELCHANGE: 0x4000000, }; var AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, BEVELED: 3, INSET: 4, UNDERLINE: 5 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; var VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; var verbosity = VERBOSITY_LEVELS.warnings; function setVerbosityLevel(level) { verbosity = level; } function getVerbosityLevel() { return verbosity; } // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (verbosity >= VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (verbosity >= VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Deprecated API function -- display regardless of the PDFJS.verbosity setting. function deprecated(details) { console.log('Deprecated API usage: ' + details); } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { if (verbosity >= VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; // Checks if URLs have the same origin. For non-HTTP based URLs, returns false. function isSameOrigin(baseUrl, otherUrl) { try { var base = new URL(baseUrl); if (!base.origin || base.origin === 'null') { return false; // non-HTTP url } } catch (e) { return false; } var other = new URL(otherUrl, base); return base.origin === other.origin; } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url || typeof url !== 'string') { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': case 'tel': return true; default: return false; } } function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } function getLookupTableFactory(initializer) { var lookup; return function () { if (initializer) { lookup = Object.create(null); initializer(lookup); initializer = null; } return lookup; }; } var PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); var UnexpectedResponseException = (function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; })(); var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); var NullCharactersRegExp = /\x00/g; function removeNullCharacters(str) { if (typeof str !== 'string') { warn('The argument for removeNullCharacters must be a string.'); return str; } return str.replace(NullCharactersRegExp, ''); } function bytesToString(bytes) { assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } /** * Gets length of the array (Array, Uint8Array, or string) in bytes. * @param {Array|Uint8Array|string} arr * @returns {number} */ function arrayByteLength(arr) { if (arr.length !== undefined) { return arr.length; } assert(arr.byteLength !== undefined); return arr.byteLength; } /** * Combines array items (arrays) into single Uint8Array object. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string). * @returns {Uint8Array} */ function arraysToBytes(arr) { // Shortcut: if first and only item is Uint8Array, return it. if (arr.length === 1 && (arr[0] instanceof Uint8Array)) { return arr[0]; } var resultLength = 0; var i, ii = arr.length; var item, itemLength ; for (i = 0; i < ii; i++) { item = arr[i]; itemLength = arrayByteLength(item); resultLength += itemLength; } var pos = 0; var data = new Uint8Array(resultLength); for (i = 0; i < ii; i++) { item = arr[i]; if (!(item instanceof Uint8Array)) { if (typeof item === 'string') { item = stringToBytes(item); } else { item = new Uint8Array(item); } } itemLength = item.byteLength; data.set(item, pos); pos += itemLength; } return data; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return (data[start] << 24) >> 24; } function readUint16(data, offset) { return (data[offset] << 8) | data[offset + 1]; } function readUint32(data, offset) { return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } // Checks if it's possible to eval JS expressions. function isEvalSupported() { try { /* jshint evil: true */ new Function(''); return true; } catch (e) { return false; } } var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); exports.Uint32ArrayView = Uint32ArrayView; var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = (function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; var ROMAN_NUMBER_MAP = [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX' ]; /** * Converts positive integers to (upper case) Roman numerals. * @param {integer} number - The number that should be converted. * @param {boolean} lowerCase - Indicates if the result should be converted * to lower case letters. The default is false. * @return {string} The resulting Roman number. */ Util.toRoman = function Util_toRoman(number, lowerCase) { assert(isInt(number) && number > 0, 'The number should be a positive integer.'); var pos, romanBuf = []; // Thousands while (number >= 1000) { number -= 1000; romanBuf.push('M'); } // Hundreds pos = (number / 100) | 0; number %= 100; romanBuf.push(ROMAN_NUMBER_MAP[pos]); // Tens pos = (number / 10) | 0; number %= 10; romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]); // Ones romanBuf.push(ROMAN_NUMBER_MAP[20 + number]); var romanStr = romanBuf.join(''); return (lowerCase ? romanStr.toLowerCase() : romanStr); }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); /** * PDF page viewport created based on scale, rotation and offset. * @class * @alias PageViewport */ var PageViewport = (function PageViewportClosure() { /** * @constructor * @private * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. * @param scale {number} scale of the viewport. * @param rotation {number} rotations of the viewport in degrees. * @param offsetX {number} offset X * @param offsetY {number} offset Y * @param dontFlip {boolean} if true, axis Y will not be flipped. */ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = /** @lends PageViewport.prototype */ { /** * Clones viewport with additional properties. * @param args {Object} (optional) If specified, may contain the 'scale' or * 'rotation' properties to override the corresponding properties in * the cloned viewport. * @returns {PageViewport} Cloned viewport. */ clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, /** * Converts PDF rectangle to the viewport coordinates. * @param rect {Array} xMin, yMin, xMax and yMax coordinates. * @returns {Array} Contains corresponding coordinates of the rectangle * in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isInt(v) { return typeof v === 'number' && ((v | 0) === v); } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isArray(v) { return v instanceof Array; } function isArrayBuffer(v) { return typeof v === 'object' && v !== null && v.byteLength !== undefined; } // Checks if ch is one of the following characters: SPACE, TAB, CR or LF. function isSpace(ch) { return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A); } /** * Promise Capability object. * * @typedef {Object} PromiseCapability * @property {Promise} promise - A promise object. * @property {function} resolve - Fulfills the promise. * @property {function} reject - Rejects the promise. */ /** * Creates a promise capability object. * @alias createPromiseCapability * * @return {PromiseCapability} A capability object contains: * - a Promise, resolve and reject methods. */ function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } /** * Polyfill for Promises: * The following promise implementation tries to generally implement the * Promise/A+ spec. Some notable differences from other promise libraries are: * - There currently isn't a separate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (value) { return new globalScope.Promise(function (resolve) { resolve(value); }); }; } if (typeof globalScope.Promise.reject !== 'function') { globalScope.Promise.reject = function (reason) { return new globalScope.Promise(function (resolve, reject) { reject(reason); }); }; } if (typeof globalScope.Promise.prototype.catch !== 'function') { globalScope.Promise.prototype.catch = function (onReject) { return globalScope.Promise.prototype.then(undefined, onReject); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status === STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof handler.onResolve === 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof handler.onReject === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; try { resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } catch (e) { this._reject(e); } } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} promises array of data and/or promises to wait for. * @return {Promise} New dependent promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if value is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param value resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(value) { return new Promise(function (resolve) { resolve(value); }); }; /** * Creates rejected promise * @param reason rejection value * @returns {Promise} */ Promise.reject = function Promise_reject(reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status === STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = resolve; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; }, catch: function Promise_catch(onReject) { return this.then(undefined, onReject); } }; globalScope.Promise = Promise; })(); (function WeakMapClosure() { if (globalScope.WeakMap) { return; } var id = 0; function WeakMap() { this.id = '$weakmap' + (id++); } WeakMap.prototype = { has: function(obj) { return !!Object.getOwnPropertyDescriptor(obj, this.id); }, get: function(obj, defaultValue) { return this.has(obj) ? obj[this.id] : defaultValue; }, set: function(obj, value) { Object.defineProperty(obj, this.id, { value: value, enumerable: false, configurable: true }); }, delete: function(obj) { delete obj[this.id]; } }; globalScope.WeakMap = WeakMap; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = Object.create(null); this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); var createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } warn('The "Blob" constructor is not supported.'); }; var createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType, forceDataSchema) { if (!forceDataSchema && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(sourceName, targetName, comObj) { this.sourceName = sourceName; this.targetName = targetName; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacksCapabilities = this.callbacksCapabilities = Object.create(null); var ah = this.actionHandler = Object.create(null); this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.targetName !== this.sourceName) { return; } if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(data.error); } else { callback.resolve(data.data); } } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var sourceName = this.sourceName; var targetName = data.sourceName; Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { if (reason instanceof Error) { // Serialize error to avoid "DataCloneError" reason = reason + ''; } comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, error: reason }); }); } else { action[0].call(action[1], data.data); } } else { error('Unknown action from worker: ' + data.action); } }.bind(this); comObj.addEventListener('message', this._onComObjOnMessage); } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, transfers) { var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data }; this.postMessage(message, transfers); }, /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that other side will callback with the response. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) { var callbackId = this.callbackIndex++; var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, /** * Sends raw message to the comObj. * @private * @param message {Object} Raw message. * @param transfers List of transfers/ArrayBuffers, or undefined. */ postMessage: function (message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } }, destroy: function () { this.comObj.removeEventListener('message', this._onComObjOnMessage); } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.onerror = (function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }); img.src = imageUrl; } // Polyfill from https://github.com/Polymer/URL /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ (function checkURLConstructor(scope) { // feature detect for URL constructor var hasWorkingUrl = false; try { if (typeof URL === 'function' && typeof URL.prototype === 'object' && ('origin' in URL.prototype)) { var u = new URL('b', 'http://a'); u.pathname = 'c%20d'; hasWorkingUrl = u.href === 'http://a/c%20d'; } } catch(e) { } if (hasWorkingUrl) { return; } var relative = Object.create(null); relative['ftp'] = 21; relative['file'] = 0; relative['gopher'] = 70; relative['http'] = 80; relative['https'] = 443; relative['ws'] = 80; relative['wss'] = 443; var relativePathDotMapping = Object.create(null); relativePathDotMapping['%2e'] = '.'; relativePathDotMapping['.%2e'] = '..'; relativePathDotMapping['%2e.'] = '..'; relativePathDotMapping['%2e%2e'] = '..'; function isRelativeScheme(scheme) { return relative[scheme] !== undefined; } function invalid() { clear.call(this); this._isInvalid = true; } function IDNAToASCII(h) { if ('' === h) { invalid.call(this); } // XXX return h.toLowerCase(); } function percentEscape(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ? ` [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) === -1 ) { return c; } return encodeURIComponent(c); } function percentEscapeQuery(c) { // XXX This actually needs to encode c using encoding and then // convert the bytes one-by-one. var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?') [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) === -1 ) { return c; } return encodeURIComponent(c); } var EOF, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; function parse(input, stateOverride, base) { function err(message) { errors.push(message); } var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = []; loop: while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) { var c = input[cursor]; switch (state) { case 'scheme start': if (c && ALPHA.test(c)) { buffer += c.toLowerCase(); // ASCII-safe state = 'scheme'; } else if (!stateOverride) { buffer = ''; state = 'no scheme'; continue; } else { err('Invalid scheme.'); break loop; } break; case 'scheme': if (c && ALPHANUMERIC.test(c)) { buffer += c.toLowerCase(); // ASCII-safe } else if (':' === c) { this._scheme = buffer; buffer = ''; if (stateOverride) { break loop; } if (isRelativeScheme(this._scheme)) { this._isRelative = true; } if ('file' === this._scheme) { state = 'relative'; } else if (this._isRelative && base && base._scheme === this._scheme) { state = 'relative or authority'; } else if (this._isRelative) { state = 'authority first slash'; } else { state = 'scheme data'; } } else if (!stateOverride) { buffer = ''; cursor = 0; state = 'no scheme'; continue; } else if (EOF === c) { break loop; } else { err('Code point not allowed in scheme: ' + c); break loop; } break; case 'scheme data': if ('?' === c) { this._query = '?'; state = 'query'; } else if ('#' === c) { this._fragment = '#'; state = 'fragment'; } else { // XXX error handling if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) { this._schemeData += percentEscape(c); } } break; case 'no scheme': if (!base || !(isRelativeScheme(base._scheme))) { err('Missing scheme.'); invalid.call(this); } else { state = 'relative'; continue; } break; case 'relative or authority': if ('/' === c && '/' === input[cursor+1]) { state = 'authority ignore slashes'; } else { err('Expected /, got: ' + c); state = 'relative'; continue; } break; case 'relative': this._isRelative = true; if ('file' !== this._scheme) { this._scheme = base._scheme; } if (EOF === c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._username = base._username; this._password = base._password; break loop; } else if ('/' === c || '\\' === c) { if ('\\' === c) { err('\\ is an invalid code point.'); } state = 'relative slash'; } else if ('?' === c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = '?'; this._username = base._username; this._password = base._password; state = 'query'; } else if ('#' === c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._fragment = '#'; this._username = base._username; this._password = base._password; state = 'fragment'; } else { var nextC = input[cursor+1]; var nextNextC = input[cursor+2]; if ('file' !== this._scheme || !ALPHA.test(c) || (nextC !== ':' && nextC !== '|') || (EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC && '?' !== nextNextC && '#' !== nextNextC)) { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; this._path = base._path.slice(); this._path.pop(); } state = 'relative path'; continue; } break; case 'relative slash': if ('/' === c || '\\' === c) { if ('\\' === c) { err('\\ is an invalid code point.'); } if ('file' === this._scheme) { state = 'file host'; } else { state = 'authority ignore slashes'; } } else { if ('file' !== this._scheme) { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; } state = 'relative path'; continue; } break; case 'authority first slash': if ('/' === c) { state = 'authority second slash'; } else { err('Expected \'/\', got: ' + c); state = 'authority ignore slashes'; continue; } break; case 'authority second slash': state = 'authority ignore slashes'; if ('/' !== c) { err('Expected \'/\', got: ' + c); continue; } break; case 'authority ignore slashes': if ('/' !== c && '\\' !== c) { state = 'authority'; continue; } else { err('Expected authority, got: ' + c); } break; case 'authority': if ('@' === c) { if (seenAt) { err('@ already seen.'); buffer += '%40'; } seenAt = true; for (var i = 0; i < buffer.length; i++) { var cp = buffer[i]; if ('\t' === cp || '\n' === cp || '\r' === cp) { err('Invalid whitespace in authority.'); continue; } // XXX check URL code points if (':' === cp && null === this._password) { this._password = ''; continue; } var tempC = percentEscape(cp); if (null !== this._password) { this._password += tempC; } else { this._username += tempC; } } buffer = ''; } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) { cursor -= buffer.length; buffer = ''; state = 'host'; continue; } else { buffer += c; } break; case 'file host': if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) { if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) { state = 'relative path'; } else if (buffer.length === 0) { state = 'relative path start'; } else { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; } continue; } else if ('\t' === c || '\n' === c || '\r' === c) { err('Invalid whitespace in file host.'); } else { buffer += c; } break; case 'host': case 'hostname': if (':' === c && !seenBracket) { // XXX host parsing this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'port'; if ('hostname' === stateOverride) { break loop; } } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; if (stateOverride) { break loop; } continue; } else if ('\t' !== c && '\n' !== c && '\r' !== c) { if ('[' === c) { seenBracket = true; } else if (']' === c) { seenBracket = false; } buffer += c; } else { err('Invalid code point in host/hostname: ' + c); } break; case 'port': if (/[0-9]/.test(c)) { buffer += c; } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c || stateOverride) { if ('' !== buffer) { var temp = parseInt(buffer, 10); if (temp !== relative[this._scheme]) { this._port = temp + ''; } buffer = ''; } if (stateOverride) { break loop; } state = 'relative path start'; continue; } else if ('\t' === c || '\n' === c || '\r' === c) { err('Invalid code point in port: ' + c); } else { invalid.call(this); } break; case 'relative path start': if ('\\' === c) { err('\'\\\' not allowed in path.'); } state = 'relative path'; if ('/' !== c && '\\' !== c) { continue; } break; case 'relative path': if (EOF === c || '/' === c || '\\' === c || (!stateOverride && ('?' === c || '#' === c))) { if ('\\' === c) { err('\\ not allowed in relative path.'); } var tmp; if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { buffer = tmp; } if ('..' === buffer) { this._path.pop(); if ('/' !== c && '\\' !== c) { this._path.push(''); } } else if ('.' === buffer && '/' !== c && '\\' !== c) { this._path.push(''); } else if ('.' !== buffer) { if ('file' === this._scheme && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') { buffer = buffer[0] + ':'; } this._path.push(buffer); } buffer = ''; if ('?' === c) { this._query = '?'; state = 'query'; } else if ('#' === c) { this._fragment = '#'; state = 'fragment'; } } else if ('\t' !== c && '\n' !== c && '\r' !== c) { buffer += percentEscape(c); } break; case 'query': if (!stateOverride && '#' === c) { this._fragment = '#'; state = 'fragment'; } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) { this._query += percentEscapeQuery(c); } break; case 'fragment': if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) { this._fragment += c; } break; } cursor++; } } function clear() { this._scheme = ''; this._schemeData = ''; this._username = ''; this._password = null; this._host = ''; this._port = ''; this._path = []; this._query = ''; this._fragment = ''; this._isInvalid = false; this._isRelative = false; } // Does not process domain names or IP addresses. // Does not handle encoding for the query parameter. function JURL(url, base /* , encoding */) { if (base !== undefined && !(base instanceof JURL)) { base = new JURL(String(base)); } this._url = url; clear.call(this); var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); // encoding = encoding || 'utf-8' parse.call(this, input, null, base); } JURL.prototype = { toString: function() { return this.href; }, get href() { if (this._isInvalid) { return this._url; } var authority = ''; if ('' !== this._username || null !== this._password) { authority = this._username + (null !== this._password ? ':' + this._password : '') + '@'; } return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; }, set href(href) { clear.call(this); parse.call(this, href); }, get protocol() { return this._scheme + ':'; }, set protocol(protocol) { if (this._isInvalid) { return; } parse.call(this, protocol + ':', 'scheme start'); }, get host() { return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; }, set host(host) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, host, 'host'); }, get hostname() { return this._host; }, set hostname(hostname) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, hostname, 'hostname'); }, get port() { return this._port; }, set port(port) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, port, 'port'); }, get pathname() { return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; }, set pathname(pathname) { if (this._isInvalid || !this._isRelative) { return; } this._path = []; parse.call(this, pathname, 'relative path start'); }, get search() { return this._isInvalid || !this._query || '?' === this._query ? '' : this._query; }, set search(search) { if (this._isInvalid || !this._isRelative) { return; } this._query = '?'; if ('?' === search[0]) { search = search.slice(1); } parse.call(this, search, 'query'); }, get hash() { return this._isInvalid || !this._fragment || '#' === this._fragment ? '' : this._fragment; }, set hash(hash) { if (this._isInvalid) { return; } this._fragment = '#'; if ('#' === hash[0]) { hash = hash.slice(1); } parse.call(this, hash, 'fragment'); }, get origin() { var host; if (this._isInvalid || !this._scheme) { return ''; } // javascript: Gecko returns String(""), WebKit/Blink String("null") // Gecko throws error for "data://" // data: Gecko returns "", Blink returns "data://", WebKit returns "null" // Gecko returns String("") for file: mailto: // WebKit/Blink returns String("SCHEME://") for file: mailto: switch (this._scheme) { case 'data': case 'file': case 'javascript': case 'mailto': return 'null'; } host = this.host; if (!host) { return ''; } return this._scheme + '://' + host; } }; // Copy over the static methods var OriginalURL = scope.URL; if (OriginalURL) { JURL.createObjectURL = function(blob) { // IE extension allows a second optional options argument. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx return OriginalURL.createObjectURL.apply(OriginalURL, arguments); }; JURL.revokeObjectURL = function(url) { OriginalURL.revokeObjectURL(url); }; } scope.URL = JURL; })(globalScope); exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; exports.IDENTITY_MATRIX = IDENTITY_MATRIX; exports.OPS = OPS; exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS; exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES; exports.AnnotationBorderStyleType = AnnotationBorderStyleType; exports.AnnotationFieldFlag = AnnotationFieldFlag; exports.AnnotationFlag = AnnotationFlag; exports.AnnotationType = AnnotationType; exports.FontType = FontType; exports.ImageKind = ImageKind; exports.InvalidPDFException = InvalidPDFException; exports.MessageHandler = MessageHandler; exports.MissingDataException = MissingDataException; exports.MissingPDFException = MissingPDFException; exports.NotImplementedException = NotImplementedException; exports.PageViewport = PageViewport; exports.PasswordException = PasswordException; exports.PasswordResponses = PasswordResponses; exports.StatTimer = StatTimer; exports.StreamType = StreamType; exports.TextRenderingMode = TextRenderingMode; exports.UnexpectedResponseException = UnexpectedResponseException; exports.UnknownErrorException = UnknownErrorException; exports.Util = Util; exports.XRefParseException = XRefParseException; exports.arrayByteLength = arrayByteLength; exports.arraysToBytes = arraysToBytes; exports.assert = assert; exports.bytesToString = bytesToString; exports.createBlob = createBlob; exports.createPromiseCapability = createPromiseCapability; exports.createObjectURL = createObjectURL; exports.deprecated = deprecated; exports.error = error; exports.getLookupTableFactory = getLookupTableFactory; exports.getVerbosityLevel = getVerbosityLevel; exports.globalScope = globalScope; exports.info = info; exports.isArray = isArray; exports.isArrayBuffer = isArrayBuffer; exports.isBool = isBool; exports.isEmptyObj = isEmptyObj; exports.isInt = isInt; exports.isNum = isNum; exports.isString = isString; exports.isSpace = isSpace; exports.isSameOrigin = isSameOrigin; exports.isValidUrl = isValidUrl; exports.isLittleEndian = isLittleEndian; exports.isEvalSupported = isEvalSupported; exports.loadJpegStream = loadJpegStream; exports.log2 = log2; exports.readInt8 = readInt8; exports.readUint16 = readUint16; exports.readUint32 = readUint32; exports.removeNullCharacters = removeNullCharacters; exports.setVerbosityLevel = setVerbosityLevel; exports.shadow = shadow; exports.string32 = string32; exports.stringToBytes = stringToBytes; exports.stringToPDFString = stringToPDFString; exports.stringToUTF8String = stringToUTF8String; exports.utf8StringToString = utf8StringToString; exports.warn = warn; })); (function (root, factory) { { factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var removeNullCharacters = sharedUtil.removeNullCharacters; var warn = sharedUtil.warn; /** * Optimised CSS custom property getter/setter. * @class */ var CustomStyle = (function CustomStyleClosure() { // As noted on: http://www.zachstronaut.com/posts/2009/02/17/ // animate-css-transforms-firefox-webkit.html // in some versions of IE9 it is critical that ms appear in this list // before Moz var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var _cache = Object.create(null); function CustomStyle() {} CustomStyle.getProp = function get(propName, element) { // check cache only when no element is given if (arguments.length === 1 && typeof _cache[propName] === 'string') { return _cache[propName]; } element = element || document.documentElement; var style = element.style, prefixed, uPropName; // test standard property first if (typeof style[propName] === 'string') { return (_cache[propName] = propName); } // capitalize uPropName = propName.charAt(0).toUpperCase() + propName.slice(1); // test vendor specific properties for (var i = 0, l = prefixes.length; i < l; i++) { prefixed = prefixes[i] + uPropName; if (typeof style[prefixed] === 'string') { return (_cache[propName] = prefixed); } } //if all fails then set to undefined return (_cache[propName] = 'undefined'); }; CustomStyle.setProp = function set(propName, element, str) { var prop = this.getProp(propName); if (prop !== 'undefined') { element.style[prop] = str; } }; return CustomStyle; })(); function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } var LinkTarget = { NONE: 0, // Default value. SELF: 1, BLANK: 2, PARENT: 3, TOP: 4, }; var LinkTargetStringMap = [ '', '_self', '_blank', '_parent', '_top' ]; /** * @typedef ExternalLinkParameters * @typedef {Object} ExternalLinkParameters * @property {string} url - An absolute URL. * @property {LinkTarget} target - The link target. * @property {string} rel - The link relationship. */ /** * Adds various attributes (href, title, target, rel) to hyperlinks. * @param {HTMLLinkElement} link - The link element. * @param {ExternalLinkParameters} params */ function addLinkAttributes(link, params) { var url = params && params.url; link.href = link.title = (url ? removeNullCharacters(url) : ''); if (url) { var target = params.target; if (typeof target === 'undefined') { target = getDefaultSetting('externalLinkTarget'); } link.target = LinkTargetStringMap[target]; var rel = params.rel; if (typeof rel === 'undefined') { rel = getDefaultSetting('externalLinkRel'); } link.rel = rel; } } // Gets the file name from a given URL. function getFilenameFromUrl(url) { var anchor = url.indexOf('#'); var query = url.indexOf('?'); var end = Math.min( anchor > 0 ? anchor : url.length, query > 0 ? query : url.length); return url.substring(url.lastIndexOf('/', end) + 1, end); } function getDefaultSetting(id) { // The list of the settings and their default is maintained for backward // compatibility and shall not be extended or modified. See also global.js. var globalSettings = sharedUtil.globalScope.PDFJS; switch (id) { case 'pdfBug': return globalSettings ? globalSettings.pdfBug : false; case 'disableAutoFetch': return globalSettings ? globalSettings.disableAutoFetch : false; case 'disableStream': return globalSettings ? globalSettings.disableStream : false; case 'disableRange': return globalSettings ? globalSettings.disableRange : false; case 'disableFontFace': return globalSettings ? globalSettings.disableFontFace : false; case 'disableCreateObjectURL': return globalSettings ? globalSettings.disableCreateObjectURL : false; case 'disableWebGL': return globalSettings ? globalSettings.disableWebGL : true; case 'cMapUrl': return globalSettings ? globalSettings.cMapUrl : null; case 'cMapPacked': return globalSettings ? globalSettings.cMapPacked : false; case 'postMessageTransfers': return globalSettings ? globalSettings.postMessageTransfers : true; case 'workerSrc': return globalSettings ? globalSettings.workerSrc : null; case 'disableWorker': return globalSettings ? globalSettings.disableWorker : false; case 'maxImageSize': return globalSettings ? globalSettings.maxImageSize : -1; case 'imageResourcesPath': return globalSettings ? globalSettings.imageResourcesPath : ''; case 'isEvalSupported': return globalSettings ? globalSettings.isEvalSupported : true; case 'externalLinkTarget': if (!globalSettings) { return LinkTarget.NONE; } switch (globalSettings.externalLinkTarget) { case LinkTarget.NONE: case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return globalSettings.externalLinkTarget; } warn('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget); // Reset the external link target, to suppress further warnings. globalSettings.externalLinkTarget = LinkTarget.NONE; return LinkTarget.NONE; case 'externalLinkRel': return globalSettings ? globalSettings.externalLinkRel : 'noreferrer'; case 'enableStats': return !!(globalSettings && globalSettings.enableStats); default: throw new Error('Unknown default setting: ' + id); } } function isExternalLinkTargetSet() { var externalLinkTarget = getDefaultSetting('externalLinkTarget'); switch (externalLinkTarget) { case LinkTarget.NONE: return false; case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return true; } } exports.CustomStyle = CustomStyle; exports.addLinkAttributes = addLinkAttributes; exports.isExternalLinkTargetSet = isExternalLinkTargetSet; exports.getFilenameFromUrl = getFilenameFromUrl; exports.LinkTarget = LinkTarget; exports.hasCanvasTypedArrays = hasCanvasTypedArrays; exports.getDefaultSetting = getDefaultSetting; })); (function (root, factory) { { factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var assert = sharedUtil.assert; var bytesToString = sharedUtil.bytesToString; var string32 = sharedUtil.string32; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; function FontLoader(docId) { this.docId = docId; this.styleElement = null; this.nativeFontFaces = []; this.loadTestFontId = 0; this.loadingContext = { requests: [], nextRequestId: 0 }; } FontLoader.prototype = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = this.styleElement; if (!styleElement) { styleElement = this.styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = this.styleElement; if (styleElement) { styleElement.parentNode.removeChild(styleElement); styleElement = this.styleElement = null; } this.nativeFontFaces.forEach(function(nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }, bind: function fontLoaderBind(fonts, callback) { var rules = []; var fontsToLoad = []; var fontLoadPromises = []; var getNativeFontPromise = function(nativeFontFace) { // Return a promise that is always fulfilled, even when the font fails to // load. return nativeFontFace.loaded.catch(function(e) { warn('Failed to load font "' + nativeFontFace.family + '": ' + e); }); }; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; if (FontLoader.isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { this.addNativeFontFace(nativeFontFace); fontLoadPromises.push(getNativeFontPromise(nativeFontFace)); } } else { var rule = font.createFontFaceRule(); if (rule) { this.insertRule(rule); rules.push(rule); fontsToLoad.push(font); } } } var request = this.queueLoadingCallback(callback); if (FontLoader.isFontLoadingAPISupported) { Promise.all(fontLoadPromises).then(function() { request.complete(); }); } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) { this.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = this.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; this.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' && !!document.fonts; Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', { get: function () { if (typeof navigator === 'undefined') { // node.js - we can pretend sync font loading is supported. return shadow(FontLoader, 'isSyncFontLoadingSupported', true); } var supported = false; // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent); if (m && m[1] >= 14) { supported = true; } // TODO other browsers return shadow(FontLoader, 'isSyncFontLoadingSupported', supported); }, enumerable: true, configurable: true }); var IsEvalSupportedCached = { get value() { return shadow(this, 'value', sharedUtil.isEvalSupported()); } }; var FontFaceObject = (function FontFaceObjectClosure() { function FontFaceObject(translatedData, options) { this.compiledGlyphs = Object.create(null); // importing translated data for (var i in translatedData) { this[i] = translatedData[i]; } this.options = options; } FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (this.options.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); if (this.options.fontRegistry) { this.options.fontRegistry.registerFont(this); } return nativeFontFace; }, createFontFaceRule: function FontFaceObject_createFontFaceRule() { if (!this.data) { return null; } if (this.options.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; if (this.options.fontRegistry) { this.options.fontRegistry.registerFont(this, url); } return rule; }, getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var cmds = objs.get(this.loadedName + '_path_' + character); var current, i, len; // If we can, compile cmds into JS for MAXIMUM SPEED if (this.options.isEvalSupported && IsEvalSupportedCached.value) { var args, js = ''; for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.args !== undefined) { args = current.args.join(','); } else { args = ''; } js += 'c.' + current.cmd + '(' + args + ');\n'; } /* jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } else { // But fall back on using Function.prototype.apply() if we're // blocked from using eval() for whatever reason (like CSP policies) this.compiledGlyphs[character] = function(c, size) { for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.cmd === 'scale') { current.args = [size, -size]; } c[current.cmd].apply(c, current.args); } }; } } return this.compiledGlyphs[character]; } }; return FontFaceObject; })(); exports.FontFaceObject = FontFaceObject; exports.FontLoader = FontLoader; })); (function (root, factory) { { factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var error = sharedUtil.error; function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = Object.create(null); this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; exports.Metadata = Metadata; })); (function (root, factory) { { factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var Util = sharedUtil.Util; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var warn = sharedUtil.warn; var createObjectURL = sharedUtil.createObjectURL; var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = (function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); } else { c = (c >> 1) & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = (crc >>> 8) ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } function encode(imgData, kind, forceDataSchema) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = (width + 7) >> 3; break; case ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } // prefix every row with predictor 0 var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; // no prediction literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === ImageKind.GRAYSCALE_1BPP) { // inverting for B/W offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; // skipping predictor for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([ width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, // bit depth colorType, // color type 0x00, // compression method 0x00, // filter method 0x00 // interlace method ]); var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; // compression method and flags idat[pi++] = 0x9c; // flags var pos = 0; while (len > maxBlockLength) { // writing non-final DEFLATE blocks type 0 and length of 65535 idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } // writing non-final DEFLATE blocks type 0 idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = (~len & 0xffff) & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); // checksum idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; // PNG will consists: header, IHDR+data, IDAT+data, and IEND. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return createObjectURL(data, 'image/png', forceDataSchema); } return function convertImgDataToPng(imgData, forceDataSchema) { var kind = (imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind); return encode(imgData, kind, forceDataSchema); }; })(); var SVGExtraState = (function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; // Default foreground and background colors this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; // Clipping this.clipId = ''; this.pendingClip = false; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; })(); var SVGGraphics = (function SVGGraphicsClosure() { function createScratchSVG(width, height) { var NS = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(NS, 'svg:svg'); svg.setAttributeNS(null, 'version', '1.1'); svg.setAttributeNS(null, 'width', width + 'px'); svg.setAttributeNS(null, 'height', height + 'px'); svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height); return svg; } function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({'fnId': 92, 'fn': 'group', 'items': []}); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if(opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } /** * Formats float number. * @param value {number} number to format. * @returns {string} */ function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } /** * Formats transform matrix. The standard rotation, scale and translate * matrices are replaced by their shorter forms, and for identity matrix * returns empty string to save the memory. * @param m {Array} matrix to format. * @returns {string} */ function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs, forceDataSchema) { this.current = new SVGExtraState(); this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = Object.create(null); this.cssStyle = null; this.forceDataSchema = !!forceDataSchema; } var NS = 'http://www.w3.org/2000/svg'; var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.pgrp.appendChild(this.tgrp); }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; var self = this; for (var i = 0; i < fnArrayLen; i++) { if (OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function(resolve) { self.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function(resolve) { self.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = Util.transform(this.transformMatrix, transformMatrix); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { this.svg = createScratchSVG(viewport.width, viewport.height); this.viewport = viewport; return this.loadDependencies(operatorList).then(function () { this.transformMatrix = IDENTITY_MATRIX; this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform)); this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.defs = document.createElementNS(NS, 'svg:defs'); this.pgrp.appendChild(this.defs); this.pgrp.appendChild(this.tgrp); this.svg.appendChild(this.pgrp); var opTree = this.convertOpList(operatorList); this.executeOpTree(opTree); return this.svg; }.bind(this)); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in OPS) { REVOPS[OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]}); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for(var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case OPS.beginText: this.beginText(); break; case OPS.setLeading: this.setLeading(args); break; case OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case OPS.setFont: this.setFont(args); break; case OPS.showText: this.showText(args[0]); break; case OPS.showSpacedText: this.showText(args[0]); break; case OPS.endText: this.endText(); break; case OPS.moveText: this.moveText(args[0], args[1]); break; case OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case OPS.setHScale: this.setHScale(args[0]); break; case OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setLineWidth: this.setLineWidth(args[0]); break; case OPS.setLineJoin: this.setLineJoin(args[0]); break; case OPS.setLineCap: this.setLineCap(args[0]); break; case OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case OPS.setDash: this.setDash(args[0], args[1]); break; case OPS.setGState: this.setGState(args[0]); break; case OPS.fill: this.fill(); break; case OPS.eoFill: this.eoFill(); break; case OPS.stroke: this.stroke(); break; case OPS.fillStroke: this.fillStroke(); break; case OPS.eoFillStroke: this.eoFillStroke(); break; case OPS.clip: this.clip('nonzero'); break; case OPS.eoClip: this.clip('evenodd'); break; case OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case OPS.closePath: this.closePath(); break; case OPS.closeStroke: this.closeStroke(); break; case OPS.closeFillStroke: this.closeFillStroke(); break; case OPS.nextLine: this.nextLine(); break; case OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.constructPath: this.constructPath(args[0], args[1]); break; case OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: warn('Unimplemented method '+ fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = document.createElementNS(NS, 'svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = IDENTITY_MATRIX; this.current.lineMatrix = IDENTITY_MATRIX; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.txtElement = document.createElementNS(NS, 'svg:text'); this.current.txtgrp = document.createElementNS(NS, 'svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } current.xcoords.push(current.x + x * textHScale); var width = glyph.width; var character = glyph.fontChar; var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; current.tspan.textContent += character; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)' ); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this.tgrp.appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = document.createElementNS(NS, 'svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() { if (this.current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, // Path properties setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = document.createElementNS(NS, 'svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x) , pf(y)); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.path.setAttributeNS(null, 'fill', 'none'); this.tgrp.appendChild(current.path); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } // Saving a reference in current.element so that it can be addressed // in 'fill' and 'stroke' current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { var current = this.current; if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, clip: function SVGGraphics_clip(type) { var current = this.current; // Add current path to clipping path current.clipId = 'clippath' + clipCount; clipCount++; this.clippath = document.createElementNS(NS, 'svg:clipPath'); this.clippath.setAttributeNS(null, 'id', current.clipId); var clipElement = current.element.cloneNode(); if (type === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.clippath.appendChild(clipElement); this.defs.appendChild(this.clippath); // Create a new group with that attribute current.pendingClip = true; this.cgrp = document.createElementNS(NS, 'svg:g'); this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')'); this.pgrp.appendChild(this.cgrp); }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': break; case 'FL': break; case 'Font': this.setFont(value); break; case 'CA': break; case 'ca': break; case 'BM': break; case 'SMask': break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); }, fillStroke: function SVGGraphics_fillStroke() { // Order is important since stroke wants fill to be none. // First stroke, then if fill needed, it will be overwritten. this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this.tgrp.appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var current = this.current; var imgObj = this.objs.get(objId); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', imgObj.width + 'px'); imgEl.setAttributeNS(null, 'height', imgObj.height + 'px'); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this.tgrp.appendChild(imgEl); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var current = this.current; var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema); var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); current.element = cliprect; this.clip('nonzero'); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this.tgrp.appendChild(imgEl); } if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = document.createElementNS(NS, 'svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')'); this.defs.appendChild(mask); this.tgrp.appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); if (isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() { this.restore(); } }; return SVGGraphics; })(); exports.SVGGraphics = SVGGraphics; })); (function (root, factory) { { factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType; var AnnotationType = sharedUtil.AnnotationType; var Util = sharedUtil.Util; var addLinkAttributes = displayDOMUtils.addLinkAttributes; var LinkTarget = displayDOMUtils.LinkTarget; var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl; var warn = sharedUtil.warn; var CustomStyle = displayDOMUtils.CustomStyle; var getDefaultSetting = displayDOMUtils.getDefaultSetting; /** * @typedef {Object} AnnotationElementParameters * @property {Object} data * @property {HTMLDivElement} layer * @property {PDFPage} page * @property {PageViewport} viewport * @property {IPDFLinkService} linkService * @property {DownloadManager} downloadManager * @property {string} imageResourcesPath * @property {boolean} renderInteractiveForms */ /** * @class * @alias AnnotationElementFactory */ function AnnotationElementFactory() {} AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */ { /** * @param {AnnotationElementParameters} parameters * @returns {AnnotationElement} */ create: function AnnotationElementFactory_create(parameters) { var subtype = parameters.data.annotationType; switch (subtype) { case AnnotationType.LINK: return new LinkAnnotationElement(parameters); case AnnotationType.TEXT: return new TextAnnotationElement(parameters); case AnnotationType.WIDGET: var fieldType = parameters.data.fieldType; switch (fieldType) { case 'Tx': return new TextWidgetAnnotationElement(parameters); } return new WidgetAnnotationElement(parameters); case AnnotationType.POPUP: return new PopupAnnotationElement(parameters); case AnnotationType.HIGHLIGHT: return new HighlightAnnotationElement(parameters); case AnnotationType.UNDERLINE: return new UnderlineAnnotationElement(parameters); case AnnotationType.SQUIGGLY: return new SquigglyAnnotationElement(parameters); case AnnotationType.STRIKEOUT: return new StrikeOutAnnotationElement(parameters); case AnnotationType.FILEATTACHMENT: return new FileAttachmentAnnotationElement(parameters); default: return new AnnotationElement(parameters); } } }; /** * @class * @alias AnnotationElement */ var AnnotationElement = (function AnnotationElementClosure() { function AnnotationElement(parameters, isRenderable) { this.isRenderable = isRenderable || false; this.data = parameters.data; this.layer = parameters.layer; this.page = parameters.page; this.viewport = parameters.viewport; this.linkService = parameters.linkService; this.downloadManager = parameters.downloadManager; this.imageResourcesPath = parameters.imageResourcesPath; this.renderInteractiveForms = parameters.renderInteractiveForms; if (isRenderable) { this.container = this._createContainer(); } } AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ { /** * Create an empty container for the annotation's HTML element. * * @private * @memberof AnnotationElement * @returns {HTMLSectionElement} */ _createContainer: function AnnotationElement_createContainer() { var data = this.data, page = this.page, viewport = this.viewport; var container = document.createElement('section'); var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; container.setAttribute('data-annotation-id', data.id); // Do *not* modify `data.rect`, since that will corrupt the annotation // position on subsequent calls to `_createContainer` (see issue 6804). var rect = Util.normalizeRect([ data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1] ]); CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')'); CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px'); if (data.borderStyle.width > 0) { container.style.borderWidth = data.borderStyle.width + 'px'; if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) { // Underline styles only have a bottom border, so we do not need // to adjust for all borders. This yields a similar result as // Adobe Acrobat/Reader. width = width - 2 * data.borderStyle.width; height = height - 2 * data.borderStyle.width; } var horizontalRadius = data.borderStyle.horizontalCornerRadius; var verticalRadius = data.borderStyle.verticalCornerRadius; if (horizontalRadius > 0 || verticalRadius > 0) { var radius = horizontalRadius + 'px / ' + verticalRadius + 'px'; CustomStyle.setProp('borderRadius', container, radius); } switch (data.borderStyle.style) { case AnnotationBorderStyleType.SOLID: container.style.borderStyle = 'solid'; break; case AnnotationBorderStyleType.DASHED: container.style.borderStyle = 'dashed'; break; case AnnotationBorderStyleType.BEVELED: warn('Unimplemented border style: beveled'); break; case AnnotationBorderStyleType.INSET: warn('Unimplemented border style: inset'); break; case AnnotationBorderStyleType.UNDERLINE: container.style.borderBottomStyle = 'solid'; break; default: break; } if (data.color) { container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); } else { // Transparent (invisible) border, so do not draw it at all. container.style.borderWidth = 0; } } container.style.left = rect[0] + 'px'; container.style.top = rect[1] + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; return container; }, /** * Create a popup for the annotation's HTML element. This is used for * annotations that do not have a Popup entry in the dictionary, but * are of a type that works with popups (such as Highlight annotations). * * @private * @param {HTMLSectionElement} container * @param {HTMLDivElement|HTMLImageElement|null} trigger * @param {Object} data * @memberof AnnotationElement */ _createPopup: function AnnotationElement_createPopup(container, trigger, data) { // If no trigger element is specified, create it. if (!trigger) { trigger = document.createElement('div'); trigger.style.height = container.style.height; trigger.style.width = container.style.width; container.appendChild(trigger); } var popupElement = new PopupElement({ container: container, trigger: trigger, color: data.color, title: data.title, contents: data.contents, hideWrapper: true }); var popup = popupElement.render(); // Position the popup next to the annotation's container. popup.style.left = container.style.width; container.appendChild(popup); }, /** * Render the annotation's HTML element in the empty container. * * @public * @memberof AnnotationElement */ render: function AnnotationElement_render() { throw new Error('Abstract method AnnotationElement.render called'); } }; return AnnotationElement; })(); /** * @class * @alias LinkAnnotationElement */ var LinkAnnotationElement = (function LinkAnnotationElementClosure() { function LinkAnnotationElement(parameters) { AnnotationElement.call(this, parameters, true); } Util.inherit(LinkAnnotationElement, AnnotationElement, { /** * Render the link annotation's HTML element in the empty container. * * @public * @memberof LinkAnnotationElement * @returns {HTMLSectionElement} */ render: function LinkAnnotationElement_render() { this.container.className = 'linkAnnotation'; var link = document.createElement('a'); addLinkAttributes(link, { url: this.data.url, target: (this.data.newWindow ? LinkTarget.BLANK : undefined), }); if (!this.data.url) { if (this.data.action) { this._bindNamedAction(link, this.data.action); } else { this._bindLink(link, (this.data.dest || null)); } } this.container.appendChild(link); return this.container; }, /** * Bind internal links to the link element. * * @private * @param {Object} link * @param {Object} destination * @memberof LinkAnnotationElement */ _bindLink: function LinkAnnotationElement_bindLink(link, destination) { var self = this; link.href = this.linkService.getDestinationHash(destination); link.onclick = function() { if (destination) { self.linkService.navigateTo(destination); } return false; }; if (destination) { link.className = 'internalLink'; } }, /** * Bind named actions to the link element. * * @private * @param {Object} link * @param {Object} action * @memberof LinkAnnotationElement */ _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) { var self = this; link.href = this.linkService.getAnchorUrl(''); link.onclick = function() { self.linkService.executeNamedAction(action); return false; }; link.className = 'internalLink'; } }); return LinkAnnotationElement; })(); /** * @class * @alias TextAnnotationElement */ var TextAnnotationElement = (function TextAnnotationElementClosure() { function TextAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(TextAnnotationElement, AnnotationElement, { /** * Render the text annotation's HTML element in the empty container. * * @public * @memberof TextAnnotationElement * @returns {HTMLSectionElement} */ render: function TextAnnotationElement_render() { this.container.className = 'textAnnotation'; var image = document.createElement('img'); image.style.height = this.container.style.height; image.style.width = this.container.style.width; image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: this.data.name}); if (!this.data.hasPopup) { this._createPopup(this.container, image, this.data); } this.container.appendChild(image); return this.container; } }); return TextAnnotationElement; })(); /** * @class * @alias WidgetAnnotationElement */ var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() { function WidgetAnnotationElement(parameters) { var isRenderable = parameters.renderInteractiveForms || (!parameters.data.hasAppearance && !!parameters.data.fieldValue); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(WidgetAnnotationElement, AnnotationElement, { /** * Render the widget annotation's HTML element in the empty container. * * @public * @memberof WidgetAnnotationElement * @returns {HTMLSectionElement} */ render: function WidgetAnnotationElement_render() { // Show only the container for unsupported field types. return this.container; } }); return WidgetAnnotationElement; })(); /** * @class * @alias TextWidgetAnnotationElement */ var TextWidgetAnnotationElement = ( function TextWidgetAnnotationElementClosure() { var TEXT_ALIGNMENT = ['left', 'center', 'right']; function TextWidgetAnnotationElement(parameters) { WidgetAnnotationElement.call(this, parameters); } Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, { /** * Render the text widget annotation's HTML element in the empty container. * * @public * @memberof TextWidgetAnnotationElement * @returns {HTMLSectionElement} */ render: function TextWidgetAnnotationElement_render() { this.container.className = 'textWidgetAnnotation'; var element = null; if (this.renderInteractiveForms) { // NOTE: We cannot set the values using `element.value` below, since it // prevents the AnnotationLayer rasterizer in `test/driver.js` // from parsing the elements correctly for the reference tests. if (this.data.multiLine) { element = document.createElement('textarea'); element.textContent = this.data.fieldValue; } else { element = document.createElement('input'); element.type = 'text'; element.setAttribute('value', this.data.fieldValue); } element.disabled = this.data.readOnly; if (this.data.maxLen !== null) { element.maxLength = this.data.maxLen; } if (this.data.comb) { var fieldWidth = this.data.rect[2] - this.data.rect[0]; var combWidth = fieldWidth / this.data.maxLen; element.classList.add('comb'); element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)'; } } else { element = document.createElement('div'); element.textContent = this.data.fieldValue; element.style.verticalAlign = 'middle'; element.style.display = 'table-cell'; var font = null; if (this.data.fontRefName) { font = this.page.commonObjs.getData(this.data.fontRefName); } this._setTextStyle(element, font); } if (this.data.textAlignment !== null) { element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; } this.container.appendChild(element); return this.container; }, /** * Apply text styles to the text in the element. * * @private * @param {HTMLDivElement} element * @param {Object} font * @memberof TextWidgetAnnotationElement */ _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) { // TODO: This duplicates some of the logic in CanvasGraphics.setFont(). var style = element.style; style.fontSize = this.data.fontSize + 'px'; style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr'); if (!font) { return; } style.fontWeight = (font.black ? (font.bold ? '900' : 'bold') : (font.bold ? 'bold' : 'normal')); style.fontStyle = (font.italic ? 'italic' : 'normal'); // Use a reasonable default font if the font doesn't specify a fallback. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : ''; var fallbackName = font.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } }); return TextWidgetAnnotationElement; })(); /** * @class * @alias PopupAnnotationElement */ var PopupAnnotationElement = (function PopupAnnotationElementClosure() { function PopupAnnotationElement(parameters) { var isRenderable = !!(parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(PopupAnnotationElement, AnnotationElement, { /** * Render the popup annotation's HTML element in the empty container. * * @public * @memberof PopupAnnotationElement * @returns {HTMLSectionElement} */ render: function PopupAnnotationElement_render() { this.container.className = 'popupAnnotation'; var selector = '[data-annotation-id="' + this.data.parentId + '"]'; var parentElement = this.layer.querySelector(selector); if (!parentElement) { return this.container; } var popup = new PopupElement({ container: this.container, trigger: parentElement, color: this.data.color, title: this.data.title, contents: this.data.contents }); // Position the popup next to the parent annotation's container. // PDF viewers ignore a popup annotation's rectangle. var parentLeft = parseFloat(parentElement.style.left); var parentWidth = parseFloat(parentElement.style.width); CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top); this.container.style.left = (parentLeft + parentWidth) + 'px'; this.container.appendChild(popup.render()); return this.container; } }); return PopupAnnotationElement; })(); /** * @class * @alias PopupElement */ var PopupElement = (function PopupElementClosure() { var BACKGROUND_ENLIGHT = 0.7; function PopupElement(parameters) { this.container = parameters.container; this.trigger = parameters.trigger; this.color = parameters.color; this.title = parameters.title; this.contents = parameters.contents; this.hideWrapper = parameters.hideWrapper || false; this.pinned = false; } PopupElement.prototype = /** @lends PopupElement.prototype */ { /** * Render the popup's HTML element. * * @public * @memberof PopupElement * @returns {HTMLSectionElement} */ render: function PopupElement_render() { var wrapper = document.createElement('div'); wrapper.className = 'popupWrapper'; // For Popup annotations we hide the entire section because it contains // only the popup. However, for Text annotations without a separate Popup // annotation, we cannot hide the entire container as the image would // disappear too. In that special case, hiding the wrapper suffices. this.hideElement = (this.hideWrapper ? wrapper : this.container); this.hideElement.setAttribute('hidden', true); var popup = document.createElement('div'); popup.className = 'popup'; var color = this.color; if (color) { // Enlighten the color. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0); } var contents = this._formatContents(this.contents); var title = document.createElement('h1'); title.textContent = this.title; // Attach the event listeners to the trigger element. this.trigger.addEventListener('click', this._toggle.bind(this)); this.trigger.addEventListener('mouseover', this._show.bind(this, false)); this.trigger.addEventListener('mouseout', this._hide.bind(this, false)); popup.addEventListener('click', this._hide.bind(this, true)); popup.appendChild(title); popup.appendChild(contents); wrapper.appendChild(popup); return wrapper; }, /** * Format the contents of the popup by adding newlines where necessary. * * @private * @param {string} contents * @memberof PopupElement * @returns {HTMLParagraphElement} */ _formatContents: function PopupElement_formatContents(contents) { var p = document.createElement('p'); var lines = contents.split(/(?:\r\n?|\n)/); for (var i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; p.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { p.appendChild(document.createElement('br')); } } return p; }, /** * Toggle the visibility of the popup. * * @private * @memberof PopupElement */ _toggle: function PopupElement_toggle() { if (this.pinned) { this._hide(true); } else { this._show(true); } }, /** * Show the popup. * * @private * @param {boolean} pin * @memberof PopupElement */ _show: function PopupElement_show(pin) { if (pin) { this.pinned = true; } if (this.hideElement.hasAttribute('hidden')) { this.hideElement.removeAttribute('hidden'); this.container.style.zIndex += 1; } }, /** * Hide the popup. * * @private * @param {boolean} unpin * @memberof PopupElement */ _hide: function PopupElement_hide(unpin) { if (unpin) { this.pinned = false; } if (!this.hideElement.hasAttribute('hidden') && !this.pinned) { this.hideElement.setAttribute('hidden', true); this.container.style.zIndex -= 1; } } }; return PopupElement; })(); /** * @class * @alias HighlightAnnotationElement */ var HighlightAnnotationElement = ( function HighlightAnnotationElementClosure() { function HighlightAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(HighlightAnnotationElement, AnnotationElement, { /** * Render the highlight annotation's HTML element in the empty container. * * @public * @memberof HighlightAnnotationElement * @returns {HTMLSectionElement} */ render: function HighlightAnnotationElement_render() { this.container.className = 'highlightAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }); return HighlightAnnotationElement; })(); /** * @class * @alias UnderlineAnnotationElement */ var UnderlineAnnotationElement = ( function UnderlineAnnotationElementClosure() { function UnderlineAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(UnderlineAnnotationElement, AnnotationElement, { /** * Render the underline annotation's HTML element in the empty container. * * @public * @memberof UnderlineAnnotationElement * @returns {HTMLSectionElement} */ render: function UnderlineAnnotationElement_render() { this.container.className = 'underlineAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }); return UnderlineAnnotationElement; })(); /** * @class * @alias SquigglyAnnotationElement */ var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() { function SquigglyAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(SquigglyAnnotationElement, AnnotationElement, { /** * Render the squiggly annotation's HTML element in the empty container. * * @public * @memberof SquigglyAnnotationElement * @returns {HTMLSectionElement} */ render: function SquigglyAnnotationElement_render() { this.container.className = 'squigglyAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }); return SquigglyAnnotationElement; })(); /** * @class * @alias StrikeOutAnnotationElement */ var StrikeOutAnnotationElement = ( function StrikeOutAnnotationElementClosure() { function StrikeOutAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(StrikeOutAnnotationElement, AnnotationElement, { /** * Render the strikeout annotation's HTML element in the empty container. * * @public * @memberof StrikeOutAnnotationElement * @returns {HTMLSectionElement} */ render: function StrikeOutAnnotationElement_render() { this.container.className = 'strikeoutAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }); return StrikeOutAnnotationElement; })(); /** * @class * @alias FileAttachmentAnnotationElement */ var FileAttachmentAnnotationElement = ( function FileAttachmentAnnotationElementClosure() { function FileAttachmentAnnotationElement(parameters) { AnnotationElement.call(this, parameters, true); this.filename = getFilenameFromUrl(parameters.data.file.filename); this.content = parameters.data.file.content; } Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, { /** * Render the file attachment annotation's HTML element in the empty * container. * * @public * @memberof FileAttachmentAnnotationElement * @returns {HTMLSectionElement} */ render: function FileAttachmentAnnotationElement_render() { this.container.className = 'fileAttachmentAnnotation'; var trigger = document.createElement('div'); trigger.style.height = this.container.style.height; trigger.style.width = this.container.style.width; trigger.addEventListener('dblclick', this._download.bind(this)); if (!this.data.hasPopup && (this.data.title || this.data.contents)) { this._createPopup(this.container, trigger, this.data); } this.container.appendChild(trigger); return this.container; }, /** * Download the file attachment associated with this annotation. * * @private * @memberof FileAttachmentAnnotationElement */ _download: function FileAttachmentAnnotationElement_download() { if (!this.downloadManager) { warn('Download cannot be started due to unavailable download manager'); return; } this.downloadManager.downloadData(this.content, this.filename, ''); } }); return FileAttachmentAnnotationElement; })(); /** * @typedef {Object} AnnotationLayerParameters * @property {PageViewport} viewport * @property {HTMLDivElement} div * @property {Array} annotations * @property {PDFPage} page * @property {IPDFLinkService} linkService * @property {string} imageResourcesPath * @property {boolean} renderInteractiveForms */ /** * @class * @alias AnnotationLayer */ var AnnotationLayer = (function AnnotationLayerClosure() { return { /** * Render a new annotation layer with all annotation elements. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ render: function AnnotationLayer_render(parameters) { var annotationElementFactory = new AnnotationElementFactory(); for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; if (!data) { continue; } var properties = { data: data, layer: parameters.div, page: parameters.page, viewport: parameters.viewport, linkService: parameters.linkService, downloadManager: parameters.downloadManager, imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'), renderInteractiveForms: parameters.renderInteractiveForms || false, }; var element = annotationElementFactory.create(properties); if (element.isRenderable) { parameters.div.appendChild(element.render()); } } }, /** * Update the annotation elements on existing annotation layer. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ update: function AnnotationLayer_update(parameters) { for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; var element = parameters.div.querySelector( '[data-annotation-id="' + data.id + '"]'); if (element) { CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')'); } } parameters.div.removeAttribute('hidden'); } }; })(); exports.AnnotationLayer = AnnotationLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var CustomStyle = displayDOMUtils.CustomStyle; var getDefaultSetting = displayDOMUtils.getDefaultSetting; /** * Text layer render parameters. * * @typedef {Object} TextLayerRenderParameters * @property {TextContent} textContent - Text content to render (the object is * returned by the page's getTextContent() method). * @property {HTMLElement} container - HTML element that will contain text runs. * @property {PageViewport} viewport - The target viewport to properly * layout the text runs. * @property {Array} textDivs - (optional) HTML elements that are correspond * the text items of the textContent input. This is output and shall be * initially be set to empty array. * @property {number} timeout - (optional) Delay in milliseconds before * rendering of the text runs occurs. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the * text selection enhancement. */ var renderTextLayer = (function renderTextLayerClosure() { var MAX_TEXT_DIVS_TO_RENDER = 100000; var NonWhitespaceRegexp = /\S/; function isAllWhitespace(str) { return !NonWhitespaceRegexp.test(str); } // Text layers may contain many thousand div's, and using `styleBuf` avoids // creating many intermediate strings when building their 'style' properties. var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0, 'px; font-family: ', '', ';']; function appendText(task, geom, styles) { // Initialize all used properties to keep the caches monomorphic. var textDiv = document.createElement('div'); var textDivProperties = { style: null, angle: 0, canvasWidth: 0, isWhitespace: false, originalTransform: null, paddingBottom: 0, paddingLeft: 0, paddingRight: 0, paddingTop: 0, scale: 1, }; task._textDivs.push(textDiv); if (isAllWhitespace(geom.str)) { textDivProperties.isWhitespace = true; task._textDivProperties.set(textDiv, textDivProperties); return; } var tx = Util.transform(task._viewport.transform, geom.transform); var angle = Math.atan2(tx[1], tx[0]); var style = styles[geom.fontName]; if (style.vertical) { angle += Math.PI / 2; } var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3])); var fontAscent = fontHeight; if (style.ascent) { fontAscent = style.ascent * fontAscent; } else if (style.descent) { fontAscent = (1 + style.descent) * fontAscent; } var left; var top; if (angle === 0) { left = tx[4]; top = tx[5] - fontAscent; } else { left = tx[4] + (fontAscent * Math.sin(angle)); top = tx[5] - (fontAscent * Math.cos(angle)); } styleBuf[1] = left; styleBuf[3] = top; styleBuf[5] = fontHeight; styleBuf[7] = style.fontFamily; textDivProperties.style = styleBuf.join(''); textDiv.setAttribute('style', textDivProperties.style); textDiv.textContent = geom.str; // |fontName| is only used by the Font Inspector. This test will succeed // when e.g. the Font Inspector is off but the Stepper is on, but it's // not worth the effort to do a more accurate test. We only use `dataset` // here to make the font name available for the debugger. if (getDefaultSetting('pdfBug')) { textDiv.dataset.fontName = geom.fontName; } if (angle !== 0) { textDivProperties.angle = angle * (180 / Math.PI); } // We don't bother scaling single-char text divs, because it has very // little effect on text highlighting. This makes scrolling on docs with // lots of such divs a lot faster. if (geom.str.length > 1) { if (style.vertical) { textDivProperties.canvasWidth = geom.height * task._viewport.scale; } else { textDivProperties.canvasWidth = geom.width * task._viewport.scale; } } task._textDivProperties.set(textDiv, textDivProperties); if (task._enhanceTextSelection) { var angleCos = 1, angleSin = 0; if (angle !== 0) { angleCos = Math.cos(angle); angleSin = Math.sin(angle); } var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale; var divHeight = fontHeight; var m, b; if (angle !== 0) { m = [angleCos, angleSin, -angleSin, angleCos, left, top]; b = Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m); } else { b = [left, top, left + divWidth, top + divHeight]; } task._bounds.push({ left: b[0], top: b[1], right: b[2], bottom: b[3], div: textDiv, size: [divWidth, divHeight], m: m }); } } function render(task) { if (task._canceled) { return; } var textLayerFrag = task._container; var textDivs = task._textDivs; var capability = task._capability; var textDivsLength = textDivs.length; // No point in rendering many divs as it would make the browser // unusable even after the divs are rendered. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { task._renderingDone = true; capability.resolve(); return; } var canvas = document.createElement('canvas'); canvas.mozOpaque = true; var ctx = canvas.getContext('2d', {alpha: false}); var lastFontSize; var lastFontFamily; for (var i = 0; i < textDivsLength; i++) { var textDiv = textDivs[i]; var textDivProperties = task._textDivProperties.get(textDiv); if (textDivProperties.isWhitespace) { continue; } var fontSize = textDiv.style.fontSize; var fontFamily = textDiv.style.fontFamily; // Only build font string and set to context if different from last. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) { ctx.font = fontSize + ' ' + fontFamily; lastFontSize = fontSize; lastFontFamily = fontFamily; } var width = ctx.measureText(textDiv.textContent).width; textLayerFrag.appendChild(textDiv); var transform = ''; if (textDivProperties.canvasWidth !== 0 && width > 0) { textDivProperties.scale = textDivProperties.canvasWidth / width; transform = 'scaleX(' + textDivProperties.scale + ')'; } if (textDivProperties.angle !== 0) { transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform; } if (transform !== '') { textDivProperties.originalTransform = transform; CustomStyle.setProp('transform', textDiv, transform); } task._textDivProperties.set(textDiv, textDivProperties); } task._renderingDone = true; capability.resolve(); } function expand(task) { var bounds = task._bounds; var viewport = task._viewport; var expanded = expandBounds(viewport.width, viewport.height, bounds); for (var i = 0; i < expanded.length; i++) { var div = bounds[i].div; var divProperties = task._textDivProperties.get(div); if (divProperties.angle === 0) { divProperties.paddingLeft = bounds[i].left - expanded[i].left; divProperties.paddingTop = bounds[i].top - expanded[i].top; divProperties.paddingRight = expanded[i].right - bounds[i].right; divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom; task._textDivProperties.set(div, divProperties); continue; } // Box is rotated -- trying to find padding so rotated div will not // exceed its expanded bounds. var e = expanded[i], b = bounds[i]; var m = b.m, c = m[0], s = m[1]; // Finding intersections with expanded box. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size]; var ts = new Float64Array(64); points.forEach(function (p, i) { var t = Util.applyTransform(p, m); ts[i + 0] = c && (e.left - t[0]) / c; ts[i + 4] = s && (e.top - t[1]) / s; ts[i + 8] = c && (e.right - t[0]) / c; ts[i + 12] = s && (e.bottom - t[1]) / s; ts[i + 16] = s && (e.left - t[0]) / -s; ts[i + 20] = c && (e.top - t[1]) / c; ts[i + 24] = s && (e.right - t[0]) / -s; ts[i + 28] = c && (e.bottom - t[1]) / c; ts[i + 32] = c && (e.left - t[0]) / -c; ts[i + 36] = s && (e.top - t[1]) / -s; ts[i + 40] = c && (e.right - t[0]) / -c; ts[i + 44] = s && (e.bottom - t[1]) / -s; ts[i + 48] = s && (e.left - t[0]) / s; ts[i + 52] = c && (e.top - t[1]) / -c; ts[i + 56] = s && (e.right - t[0]) / s; ts[i + 60] = c && (e.bottom - t[1]) / -c; }); var findPositiveMin = function (ts, offset, count) { var result = 0; for (var i = 0; i < count; i++) { var t = ts[offset++]; if (t > 0) { result = result ? Math.min(t, result) : t; } } return result; }; // Not based on math, but to simplify calculations, using cos and sin // absolute values to not exceed the box (it can but insignificantly). var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s)); divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale; divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale; divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale; divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale; task._textDivProperties.set(div, divProperties); } } function expandBounds(width, height, boxes) { var bounds = boxes.map(function (box, i) { return { x1: box.left, y1: box.top, x2: box.right, y2: box.bottom, index: i, x1New: undefined, x2New: undefined }; }); expandBoundsLTR(width, bounds); var expanded = new Array(boxes.length); bounds.forEach(function (b) { var i = b.index; expanded[i] = { left: b.x1New, top: 0, right: b.x2New, bottom: 0 }; }); // Rotating on 90 degrees and extending extended boxes. Reusing the bounds // array and objects. boxes.map(function (box, i) { var e = expanded[i], b = bounds[i]; b.x1 = box.top; b.y1 = width - e.right; b.x2 = box.bottom; b.y2 = width - e.left; b.index = i; b.x1New = undefined; b.x2New = undefined; }); expandBoundsLTR(height, bounds); bounds.forEach(function (b) { var i = b.index; expanded[i].top = b.x1New; expanded[i].bottom = b.x2New; }); return expanded; } function expandBoundsLTR(width, bounds) { // Sorting by x1 coordinate and walk by the bounds in the same order. bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; }); // First we see on the horizon is a fake boundary. var fakeBoundary = { x1: -Infinity, y1: -Infinity, x2: 0, y2: Infinity, index: -1, x1New: 0, x2New: 0 }; var horizon = [{ start: -Infinity, end: Infinity, boundary: fakeBoundary }]; bounds.forEach(function (boundary) { // Searching for the affected part of horizon. // TODO red-black tree or simple binary search var i = 0; while (i < horizon.length && horizon[i].end <= boundary.y1) { i++; } var j = horizon.length - 1; while(j >= 0 && horizon[j].start >= boundary.y2) { j--; } var horizonPart, affectedBoundary; var q, k, maxXNew = -Infinity; for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; var xNew; if (affectedBoundary.x2 > boundary.x1) { // In the middle of the previous element, new x shall be at the // boundary start. Extending if further if the affected bondary // placed on top of the current one. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1; } else if (affectedBoundary.x2New === undefined) { // We have some space in between, new x in middle will be a fair // choice. xNew = (affectedBoundary.x2 + boundary.x1) / 2; } else { // Affected boundary has x2new set, using it as new x. xNew = affectedBoundary.x2New; } if (xNew > maxXNew) { maxXNew = xNew; } } // Set new x1 for current boundary. boundary.x1New = maxXNew; // Adjusts new x2 for the affected boundaries. for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New === undefined) { // Was not set yet, choosing new x if possible. if (affectedBoundary.x2 > boundary.x1) { // Current and affected boundaries intersect. If affected boundary // is placed on top of the current, shrinking the affected. if (affectedBoundary.index > boundary.index) { affectedBoundary.x2New = affectedBoundary.x2; } } else { affectedBoundary.x2New = maxXNew; } } else if (affectedBoundary.x2New > maxXNew) { // Affected boundary is touching new x, pushing it back. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2); } } // Fixing the horizon. var changedHorizon = [], lastBoundary = null; for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; // Checking which boundary will be visible. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary; if (lastBoundary === useBoundary) { // Merging with previous. changedHorizon[changedHorizon.length - 1].end = horizonPart.end; } else { changedHorizon.push({ start: horizonPart.start, end: horizonPart.end, boundary: useBoundary }); lastBoundary = useBoundary; } } if (horizon[i].start < boundary.y1) { changedHorizon[0].start = boundary.y1; changedHorizon.unshift({ start: horizon[i].start, end: boundary.y1, boundary: horizon[i].boundary }); } if (boundary.y2 < horizon[j].end) { changedHorizon[changedHorizon.length - 1].end = boundary.y2; changedHorizon.push({ start: boundary.y2, end: horizon[j].end, boundary: horizon[j].boundary }); } // Set x2 new of boundary that is no longer visible (see overlapping case // above). // TODO more efficient, e.g. via reference counting. for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New !== undefined) { continue; } var used = false; for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) { used = horizon[k].boundary === affectedBoundary; } for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) { used = horizon[k].boundary === affectedBoundary; } for (k = 0; !used && k < changedHorizon.length; k++) { used = changedHorizon[k].boundary === affectedBoundary; } if (!used) { affectedBoundary.x2New = maxXNew; } } Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon)); }); // Set new x2 for all unset boundaries. horizon.forEach(function (horizonPart) { var affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New === undefined) { affectedBoundary.x2New = Math.max(width, affectedBoundary.x2); } }); } /** * Text layer rendering task. * * @param {TextContent} textContent * @param {HTMLElement} container * @param {PageViewport} viewport * @param {Array} textDivs * @param {boolean} enhanceTextSelection * @private */ function TextLayerRenderTask(textContent, container, viewport, textDivs, enhanceTextSelection) { this._textContent = textContent; this._container = container; this._viewport = viewport; this._textDivs = textDivs || []; this._textDivProperties = new WeakMap(); this._renderingDone = false; this._canceled = false; this._capability = createPromiseCapability(); this._renderTimer = null; this._bounds = []; this._enhanceTextSelection = !!enhanceTextSelection; } TextLayerRenderTask.prototype = { get promise() { return this._capability.promise; }, cancel: function TextLayer_cancel() { this._canceled = true; if (this._renderTimer !== null) { clearTimeout(this._renderTimer); this._renderTimer = null; } this._capability.reject('canceled'); }, _render: function TextLayer_render(timeout) { var textItems = this._textContent.items; var textStyles = this._textContent.styles; for (var i = 0, len = textItems.length; i < len; i++) { appendText(this, textItems[i], textStyles); } if (!timeout) { // Render right away render(this); } else { // Schedule var self = this; this._renderTimer = setTimeout(function() { render(self); self._renderTimer = null; }, timeout); } }, expandTextDivs: function TextLayer_expandTextDivs(expandDivs) { if (!this._enhanceTextSelection || !this._renderingDone) { return; } if (this._bounds !== null) { expand(this); this._bounds = null; } for (var i = 0, ii = this._textDivs.length; i < ii; i++) { var div = this._textDivs[i]; var divProperties = this._textDivProperties.get(div); if (divProperties.isWhitespace) { continue; } if (expandDivs) { var transform = '', padding = ''; if (divProperties.scale !== 1) { transform = 'scaleX(' + divProperties.scale + ')'; } if (divProperties.angle !== 0) { transform = 'rotate(' + divProperties.angle + 'deg) ' + transform; } if (divProperties.paddingLeft !== 0) { padding += ' padding-left: ' + (divProperties.paddingLeft / divProperties.scale) + 'px;'; transform += ' translateX(' + (-divProperties.paddingLeft / divProperties.scale) + 'px)'; } if (divProperties.paddingTop !== 0) { padding += ' padding-top: ' + divProperties.paddingTop + 'px;'; transform += ' translateY(' + (-divProperties.paddingTop) + 'px)'; } if (divProperties.paddingRight !== 0) { padding += ' padding-right: ' + (divProperties.paddingRight / divProperties.scale) + 'px;'; } if (divProperties.paddingBottom !== 0) { padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;'; } if (padding !== '') { div.setAttribute('style', divProperties.style + padding); } if (transform !== '') { CustomStyle.setProp('transform', div, transform); } } else { div.style.padding = 0; CustomStyle.setProp('transform', div, divProperties.originalTransform || ''); } } }, }; /** * Starts rendering of the text layer. * * @param {TextLayerRenderParameters} renderParameters * @returns {TextLayerRenderTask} */ function renderTextLayer(renderParameters) { var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs, renderParameters.enhanceTextSelection); task._render(renderParameters.timeout); return task; } return renderTextLayer; })(); exports.renderTextLayer = renderTextLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var shadow = sharedUtil.shadow; var getDefaultSetting = displayDOMUtils.getDefaultSetting; var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[j]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if (getDefaultSetting('disableWebGL')) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); exports.WebGLUtils = WebGLUtils; })); (function (root, factory) { { factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayWebGL) { var Util = sharedUtil.Util; var info = sharedUtil.info; var isArray = sharedUtil.isArray; var error = sharedUtil.error; var WebGLUtils = displayWebGL.WebGLUtils; var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough // We need to keep transparent border around our pattern for fill(): // createPattern with 'no-repeat' will bleed edges across entire area. var BORDER_SIZE = 2; var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var paddedWidth = width + BORDER_SIZE * 2; var paddedHeight = height + BORDER_SIZE * 2; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false); tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE); canvas = tmpCanvas.canvas; } else { tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX - BORDER_SIZE * scaleX, offsetY: offsetY - BORDER_SIZE * scaleY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { //var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; //var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { // Obtain scale from matrix and current transformation matrix. scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.canvasGraphicsFactory = canvasGraphicsFactory; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var canvasGraphicsFactory = this.canvasGraphicsFactory; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); exports.getShadingPatternFromIR = getShadingPatternFromIR; exports.TilingPattern = TilingPattern; })); (function (root, factory) { { factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper, displayWebGL) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var TextRenderingMode = sharedUtil.TextRenderingMode; var Uint32ArrayView = sharedUtil.Uint32ArrayView; var Util = sharedUtil.Util; var assert = sharedUtil.assert; var info = sharedUtil.info; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var isLittleEndian = sharedUtil.isLittleEndian; var error = sharedUtil.error; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; var TilingPattern = displayPatternHelper.TilingPattern; var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR; var WebGLUtils = displayWebGL.WebGLUtils; var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays; // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; // Maximum font size that would be used during canvas fillText operations. var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; // Heuristic value used when enforcing minimum line widths. var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; var HasCanvasTypedArraysCached = { get value() { return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays()); } }; var IsLittleEndianCached = { get value() { return shadow(IsLittleEndianCached, 'value', isLittleEndian()); } }; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based one. if (!ctx.mozCurrentTransform) { ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { function CachedCanvases() { this.cache = Object.create(null); } CachedCanvases.prototype = { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (this.cache[id] !== undefined) { canvasEntry = this.cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } this.cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { for (var id in this.cache) { var canvasEntry = this.cache[id]; // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. canvasEntry.canvas.width = 0; canvasEntry.canvas.height = 0; delete this.cache[id]; } } }; return CachedCanvases; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; this.resumeSMaskCtx = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; // Defines the number of steps before checking the execution time var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; this.cachedCanvases = new CachedCanvases(); if (canvasCtx) { // NOTE: if mozCurrentTransform is polyfilled, then the current state of // the transformation must already be set in canvasCtx._transformMatrix. addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var srcLength = src.byteLength; var dest32 = HasCanvasTypedArraysCached.value ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (IsLittleEndianCached.value || !HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8; } } } function composeSMaskAlpha(maskData, layerData, transferMap) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; layerData[i] = (layerData[i] * alpha * scale) | 0; } } function composeSMaskLuminosity(maskData, layerData, transferMap) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskData[i - 2] * 152) + // * 0.59 .... (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = transferMap ? (layerData[i] * transferMap[y >> 8]) >> 8 : (layerData[i] * y) >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data, transferMap); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (!smask.transferMap && WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, creating temporary // transparent canvas when we have blend modes. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); if (transparency) { var transparentCanvas = this.cachedCanvases.getCanvas( 'transparent', width, height, true); this.compositeCtx = this.ctx; this.transparentCanvas = transparentCanvas.canvas; this.ctx = transparentCanvas.context; this.ctx.save(); // The transform can be applied before rendering, transferring it to // the new canvas. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); } this.ctx.save(); if (transform) { this.ctx.transform.apply(this.ctx, transform); } this.ctx.transform.apply(this.ctx, viewport.transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen === i) { return i; } var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'); var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i === argsArrayLen) { return i; } // If the execution took longer then a certain amount of time and // `continueCallback` is specified, interrupt the execution. if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { // Finishing all opened operations such as SMask group painting. if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.ctx.restore(); if (this.transparentCanvas) { this.ctx = this.compositeCtx; this.ctx.save(); this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice this.ctx.drawImage(this.transparentCanvas, 0, 0); this.ctx.restore(); this.transparentCanvas = null; } this.cachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { // If SMask is currrenly used, it needs to be suspended or // finished. Suspend only makes sense when at least one save() // was performed and state needs to be reverted on restore(). if (this.stateStack.length > 0 && (this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask)) { this.suspendSMaskGroup(); } else { this.endSMaskGroup(); } } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse; copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() { // Similar to endSMaskGroup, the intermediate canvas has to be composed // and future ctx state restored. var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); this.ctx.save(); // save is needed since SMask will be resumed. copyCtxState(groupCtx, this.ctx); // Saving state for resuming. this.current.resumeSMaskCtx = groupCtx; // Transform was changed in the SMask canvas, reflecting this change on // this.ctx. var deltaTransform = Util.transform( this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform); this.ctx.transform.apply(this.ctx, deltaTransform); // SMask was composed, the results at the groupCtx can be cleared. groupCtx.save(); groupCtx.setTransform(1, 0, 0, 1, 0, 0); groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height); groupCtx.restore(); }, resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() { // Resuming state saved by suspendSMaskGroup. We don't need to restore // any groupCtx state since restore() command (the only caller) will do // that for us. See also beginSMaskGroup. var groupCtx = this.current.resumeSMaskCtx; var currentCtx = this.ctx; this.ctx = groupCtx; this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); copyCtxState(groupCtx, this.ctx); // Transform was changed in the SMask canvas, reflecting this change on // this.ctx. var deltaTransform = Util.transform( this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform); this.ctx.transform.apply(this.ctx, deltaTransform); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.resumeSMaskCtx = null; }, restore: function CanvasGraphics_restore() { // SMask was suspended, we just need to resume it. if (this.current.resumeSMaskCtx) { this.resumeSMaskGroup(); } // SMask has to be finished once there is no states that are using the // same SMask. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) { this.endSMaskGroup(); } if (this.stateStack.length !== 0) { this.current = this.stateStack.pop(); this.ctx.restore(); // Ensure that the clipping path is reset (fixes issue6413.pdf). this.pendingClip = null; this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, // Path constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; // Prevent drawing too thin lines by enforcing a minimum line width. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); if (this.baseTransform) { ctx.setTransform.apply(ctx, this.baseTransform); } ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.fill(); ctx.mozFillRule = 'nonzero'; } else { ctx.fill('evenodd'); } this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var spacingDir = vertical ? 1 : -1; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (current.patternFill) { // TODO: Some shading patterns are not applied correctly to text, // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf. ctx.fillStyle = current.fillColor.getPattern(ctx, this); } if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (isNum(glyph)) { x += spacingDir * glyph * fontSize / 1000; continue; } var restoreNeeded = false; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0) { // Some standard fonts may not have the exact width: rescale per // character if measured width is greater than expected glyph width // and subpixel-aa is enabled, otherwise just center the glyph. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; if (width < measuredWidth && this.isFontSubpixelAAEnabled) { var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } else if (width !== measuredWidth) { scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; } } // Only attempt to draw the glyph if it is actually in the embedded font // file or if there isn't a font file so the fallback font is shown. if (glyph.isInFont || font.missingFile) { if (simpleFillText && !accent) { // common case ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } } var charWidth = width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { // Type3 fonts - each glyph is a "mini-PDF" var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var spacingDir = font.vertical ? 1 : -1; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width, spacingLength; if (isTextInvisible || fontSize === 0) { return; } this.cachedGetSinglePixelWidth = null; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (isNum(glyph)) { spacingLength = spacingDir * glyph * fontSize / 1000; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { warn('Type3 character \"' + glyph.operatorListId + '\" is not available'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + spacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); var self = this; var canvasGraphicsFactory = { createCanvasGraphics: function (ctx) { return new CanvasGraphics(ctx, self.commonObjs, self.objs); } }; pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (isArray(matrix) && 6 === matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (isArray(bbox) && 4 === bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implementing: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, transferMap: group.smask.transferMap || null, startTransformInverse: null, // used during suspend operation }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; // Reseting mask state, masks will be applied on restore of the group. this.current.activeSMask = null; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); if (this.baseTransform) { this.ctx.setTransform.apply(this.ctx, this.baseTransform); } }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (isArray(rect) && 4 === rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, paintXObject: function CanvasGraphics_paintXObject() { warn('Unsupported \'paintXObject\' command.'); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.clip(); ctx.mozFillRule = 'nonzero'; } else { ctx.clip('evenodd'); } } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { // NOTE: The `save` and `restore` commands used below is a workaround // that is necessary in order to prevent `mozCurrentTransformInverse` // from intermittently returning incorrect values in Firefox, see: // https://github.com/mozilla/pdf.js/issues/7188. this.ctx.save(); var inverse = this.ctx.mozCurrentTransformInverse; this.ctx.restore(); // max of the current horizontal and vertical scale this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); exports.CanvasGraphics = CanvasGraphics; exports.createScratchCanvas = createScratchCanvas; })); (function (root, factory) { { factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, displayDOMUtils, amdRequire) { var InvalidPDFException = sharedUtil.InvalidPDFException; var MessageHandler = sharedUtil.MessageHandler; var MissingPDFException = sharedUtil.MissingPDFException; var PageViewport = sharedUtil.PageViewport; var PasswordResponses = sharedUtil.PasswordResponses; var PasswordException = sharedUtil.PasswordException; var StatTimer = sharedUtil.StatTimer; var UnexpectedResponseException = sharedUtil.UnexpectedResponseException; var UnknownErrorException = sharedUtil.UnknownErrorException; var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var error = sharedUtil.error; var deprecated = sharedUtil.deprecated; var getVerbosityLevel = sharedUtil.getVerbosityLevel; var info = sharedUtil.info; var isInt = sharedUtil.isInt; var isArray = sharedUtil.isArray; var isArrayBuffer = sharedUtil.isArrayBuffer; var isSameOrigin = sharedUtil.isSameOrigin; var loadJpegStream = sharedUtil.loadJpegStream; var stringToBytes = sharedUtil.stringToBytes; var globalScope = sharedUtil.globalScope; var warn = sharedUtil.warn; var FontFaceObject = displayFontLoader.FontFaceObject; var FontLoader = displayFontLoader.FontLoader; var CanvasGraphics = displayCanvas.CanvasGraphics; var createScratchCanvas = displayCanvas.createScratchCanvas; var Metadata = displayMetadata.Metadata; var getDefaultSetting = displayDOMUtils.getDefaultSetting; var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536 var isWorkerDisabled = false; var workerSrc; var isPostMessageTransfersDisabled = false; var useRequireEnsure = false; if (typeof window === 'undefined') { // node.js - disable worker and set require.ensure. isWorkerDisabled = true; if (typeof require.ensure === 'undefined') { require.ensure = require('node-ensure'); } useRequireEnsure = true; } if (typeof __webpack_require__ !== 'undefined') { useRequireEnsure = true; } if (typeof requirejs !== 'undefined' && requirejs.toUrl) { workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js'); } var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load; var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) { require.ensure([], function () { var worker = require('./pdf.worker.js'); callback(worker.WorkerMessageHandler); }); }) : dynamicLoaderSupported ? (function (callback) { requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) { callback(worker.WorkerMessageHandler); }); }) : null; /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded, * use atob() to convert it to a binary string first. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. * @property {number} length - The PDF file length. It's used for progress * reports and range requests operations. * @property {PDFDataRangeTransport} range * @property {number} rangeChunkSize - Optional parameter to specify * maximum number of bytes fetched per range request. The default value is * 2^16 = 65536. * @property {PDFWorker} worker - The worker that will be used for the loading * and parsing of the PDF data. */ /** * @typedef {Object} PDFDocumentStats * @property {Array} streamTypes - Used stream types in the document (an item * is set to true if specific stream ID was used in the document). * @property {Array} fontTypes - Used font type in the document (an item is set * to true if specific font ID was used in the document). */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src * Can be a url to where a PDF is located, a typed array (Uint8Array) * already populated with data or parameter object. * * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used * if you want to manually serve range requests for data in the PDF. * * @param {function} passwordCallback (deprecated) It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @param {function} progressCallback (deprecated) It is used to be able to * monitor the loading progress of the PDF file (necessary to implement e.g. * a loading bar). The callback receives an {Object} with the properties: * {number} loaded and {number} total. * * @return {PDFDocumentLoadingTask} */ function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { var task = new PDFDocumentLoadingTask(); // Support of the obsolete arguments (for compatibility with API v1.0) if (arguments.length > 1) { deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument'); } if (pdfDataRangeTransport) { if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { // Not a PDFDataRangeTransport instance, trying to add missing properties. pdfDataRangeTransport = Object.create(pdfDataRangeTransport); pdfDataRangeTransport.length = src.length; pdfDataRangeTransport.initialData = src.initialData; if (!pdfDataRangeTransport.abort) { pdfDataRangeTransport.abort = function () {}; } } src = Object.create(src); src.range = pdfDataRangeTransport; } task.onPassword = passwordCallback || null; task.onProgress = progressCallback || null; var source; if (typeof src === 'string') { source = { url: src }; } else if (isArrayBuffer(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if (typeof src !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!src.url && !src.data && !src.range) { error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; var rangeTransport = null; var worker = null; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { // The full path is required in the 'url' field. params[key] = new URL(source[key], window.location).href; continue; } else if (key === 'range') { rangeTransport = source[key]; continue; } else if (key === 'worker') { worker = source[key]; continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { // Converting string or array-like data to Uint8Array. var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = stringToBytes(pdfBytes); } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else if (isArrayBuffer(pdfBytes)) { params[key] = new Uint8Array(pdfBytes); } else { error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.'); } continue; } params[key] = source[key]; } params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; if (!worker) { // Worker was not provided -- creating and owning our own. worker = new PDFWorker(); task._worker = worker; } var docId = task.docId; worker.promise.then(function () { if (task.destroyed) { throw new Error('Loading aborted'); } return _fetchDocument(worker, params, rangeTransport, docId).then( function (workerId) { if (task.destroyed) { throw new Error('Loading aborted'); } var messageHandler = new MessageHandler(docId, workerId, worker.port); var transport = new WorkerTransport(messageHandler, task, rangeTransport); task._transport = transport; messageHandler.send('Ready', null); }); }).catch(task._capability.reject); return task; } /** * Starts fetching of specified PDF document/data. * @param {PDFWorker} worker * @param {Object} source * @param {PDFDataRangeTransport} pdfDataRangeTransport * @param {string} docId Unique document id, used as MessageHandler id. * @returns {Promise} The promise, which is resolved when worker id of * MessageHandler is known. * @private */ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { if (worker.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } source.disableAutoFetch = getDefaultSetting('disableAutoFetch'); source.disableStream = getDefaultSetting('disableStream'); source.chunkedViewerLoading = !!pdfDataRangeTransport; if (pdfDataRangeTransport) { source.length = pdfDataRangeTransport.length; source.initialData = pdfDataRangeTransport.initialData; } return worker.messageHandler.sendWithPromise('GetDocRequest', { docId: docId, source: source, disableRange: getDefaultSetting('disableRange'), maxImageSize: getDefaultSetting('maxImageSize'), cMapUrl: getDefaultSetting('cMapUrl'), cMapPacked: getDefaultSetting('cMapPacked'), disableFontFace: getDefaultSetting('disableFontFace'), disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'), postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled, }).then(function (workerId) { if (worker.destroyed) { throw new Error('Worker was destroyed'); } return workerId; }); } /** * PDF document loading operation. * @class * @alias PDFDocumentLoadingTask */ var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { var nextDocumentId = 0; /** @constructs PDFDocumentLoadingTask */ function PDFDocumentLoadingTask() { this._capability = createPromiseCapability(); this._transport = null; this._worker = null; /** * Unique document loading task id -- used in MessageHandlers. * @type {string} */ this.docId = 'd' + (nextDocumentId++); /** * Shows if loading task is destroyed. * @type {boolean} */ this.destroyed = false; /** * Callback to request a password if wrong or no password was provided. * The callback receives two parameters: function that needs to be called * with new password and reason (see {PasswordResponses}). */ this.onPassword = null; /** * Callback to be able to monitor the loading progress of the PDF file * (necessary to implement e.g. a loading bar). The callback receives * an {Object} with the properties: {number} loaded and {number} total. */ this.onProgress = null; /** * Callback to when unsupported feature is used. The callback receives * an {UNSUPPORTED_FEATURES} argument. */ this.onUnsupportedFeature = null; } PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */ { /** * @return {Promise} */ get promise() { return this._capability.promise; }, /** * Aborts all network requests and destroys worker. * @return {Promise} A promise that is resolved after destruction activity * is completed. */ destroy: function () { this.destroyed = true; var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); return transportDestroyed.then(function () { this._transport = null; if (this._worker) { this._worker.destroy(); this._worker = null; } }.bind(this)); }, /** * Registers callbacks to indicate the document loading completion. * * @param {function} onFulfilled The callback for the loading completion. * @param {function} onRejected The callback for the loading failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; })(); /** * Abstract class to support range requests file loading. * @class * @alias PDFDataRangeTransport * @param {number} length * @param {Uint8Array} initialData */ var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() { function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = createPromiseCapability(); } PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */ { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { this._readyCapability.promise.then(function () { var listeners = this._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }.bind(this)); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { this._readyCapability.promise.then(function () { var listeners = this._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }.bind(this)); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); }, abort: function PDFDataRangeTransport_abort() { } }; return PDFDataRangeTransport; })(); /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class * @alias PDFDocumentProxy */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport, loadingTask) { this.pdfInfo = pdfInfo; this.transport = transport; this.loadingTask = loadingTask; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. * * This can be slow for large documents: use getDestination instead */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @param {string} id The named destination to get. * @return {Promise} A promise that is resolved with all information * of the given named destination. */ getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, /** * @return {Promise} A promise that is resolved with: * an Array containing the pageLabels that correspond to the pageIndexes, * or `null` when no pageLabels are present in the PDF file. */ getPageLabels: function PDFDocumentProxy_getPageLabels() { return this.transport.getPageLabels(); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named attachments to their content. */ getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { return this.transport.getJavaScript(); }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb Uint8Array, * dest: dest obj, * url: string, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, /** * @return {Promise} A promise this is resolved with current stats about * document structures (see {@link PDFDocumentStats}). */ getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { return this.loadingTask.destroy(); } }; return PDFDocumentProxy; })(); /** * Page getTextContent parameters. * * @typedef {Object} getTextContentParameters * @param {boolean} normalizeWhitespace - replaces all occurrences of * whitespace with standard spaces (0x20). The default value is `false`. * @param {boolean} disableCombineTextItems - do not attempt to combine * same line {@link TextItem}'s. The default value is `false`. */ /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page annotation parameters. * * @typedef {Object} GetAnnotationsParameters * @param {string} intent - Determines the annotations that will be fetched, * can be either 'display' (viewable annotations) or 'print' * (printable annotations). * If the parameter is omitted, all annotations are fetched. */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {boolean} renderInteractiveForms - (optional) Whether or not * interactive form elements are rendered in the display * layer. If so, we do not render them on canvas as well. * @property {Array} transform - (optional) Additional transform, applied * just before viewport transform. * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (deprecated) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * PDF page operator list. * * @typedef {Object} PDFOperatorList * @property {Array} fnArray - Array containing the operator functions. * @property {Array} argsArray - Array containing the arguments of the * functions. */ /** * Proxy to a PDFPage in the worker thread. * @class * @alias PDFPageProxy */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = getDefaultSetting('enableStats'); this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingCleanup = false; this.intentStates = Object.create(null); this.destroyed = false; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PageViewport(this.view, scale, rotate, 0, 0); }, /** * @param {GetAnnotationsParameters} params - Annotation parameters. * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations(params) { var intent = (params && params.intent) || null; if (!this.annotationsPromise || this.annotationsIntent !== intent) { this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent); this.annotationsIntent = intent; } return this.annotationsPromise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingCleanup = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); var renderInteractiveForms = (params.renderInteractiveForms === true ? true : /* Default */ false); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = Object.create(null); } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent, renderInteractiveForms: renderInteractiveForms, }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { deprecated('render is used with continueCallback parameter'); renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingCleanup) { complete(); return; } stats.time('Rendering'); internalRenderTask.initializeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingCleanup = true; } self._tryCleanup(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} A promise resolved with an {@link PDFOperatorList} * object that represents page's operator list. */ getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); var i = intentState.renderTasks.indexOf(opListTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = Object.create(null); } var intentState = this.intentStates[renderingIntent]; var opListTask; if (!intentState.opListReadCapability) { opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = createPromiseCapability(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, /** * @param {getTextContentParameters} params - getTextContent parameters. * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent(params) { return this.transport.messageHandler.sendWithPromise('GetTextContent', { pageIndex: this.pageNumber - 1, normalizeWhitespace: (params && params.normalizeWhitespace === true ? true : /* Default */ false), combineTextItems: (params && params.disableCombineTextItems === true ? false : /* Default */ true), }); }, /** * Destroys page object. */ _destroy: function PDFPageProxy_destroy() { this.destroyed = true; this.transport.pageCache[this.pageIndex] = null; var waitOn = []; Object.keys(this.intentStates).forEach(function(intent) { if (intent === 'oplist') { // Avoid errors below, since the renderTasks are just stubs. return; } var intentState = this.intentStates[intent]; intentState.renderTasks.forEach(function(renderTask) { var renderCompleted = renderTask.capability.promise. catch(function () {}); // ignoring failures waitOn.push(renderCompleted); renderTask.cancel(); }); }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; return Promise.all(waitOn); }, /** * Cleans up resources allocated by the page. (deprecated) */ destroy: function() { deprecated('page destroy method, use cleanup() instead'); this.cleanup(); }, /** * Cleans up resources allocated by the page. */ cleanup: function PDFPageProxy_cleanup() { this.pendingCleanup = true; this._tryCleanup(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryCleanup: function PDFPageProxy_tryCleanup() { if (!this.pendingCleanup || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; // TODO Refactor RenderPageRequest to separate rendering // and operator list logic if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryCleanup(); } } }; return PDFPageProxy; })(); /** * PDF.js web worker abstraction, it controls instantiation of PDF documents and * WorkerTransport for them. If creation of a web worker is not possible, * a "fake" worker will be used instead. * @class */ var PDFWorker = (function PDFWorkerClosure() { var nextFakeWorkerId = 0; function getWorkerSrc() { if (typeof workerSrc !== 'undefined') { return workerSrc; } if (getDefaultSetting('workerSrc')) { return getDefaultSetting('workerSrc'); } if (pdfjsFilePath) { return pdfjsFilePath.replace(/\.js$/i, '.worker.js'); } error('No PDFJS.workerSrc specified'); } var fakeWorkerFilesLoadedCapability; // Loads worker code into main thread. function setupFakeWorkerGlobal() { var WorkerMessageHandler; if (!fakeWorkerFilesLoadedCapability) { fakeWorkerFilesLoadedCapability = createPromiseCapability(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. var loader = fakeWorkerFilesLoader || function (callback) { Util.loadScript(getWorkerSrc(), function () { callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler); }); }; loader(fakeWorkerFilesLoadedCapability.resolve); } return fakeWorkerFilesLoadedCapability.promise; } function FakeWorkerPort(defer) { this._listeners = []; this._defer = defer; this._deferred = Promise.resolve(undefined); } FakeWorkerPort.prototype = { postMessage: function (obj, transfers) { function cloneValue(value) { // Trying to perform a structured clone close to the spec, including // transfers. if (typeof value !== 'object' || value === null) { return value; } if (cloned.has(value)) { // already cloned the object return cloned.get(value); } var result; var buffer; if ((buffer = value.buffer) && isArrayBuffer(buffer)) { // We found object with ArrayBuffer (typed array). var transferable = transfers && transfers.indexOf(buffer) >= 0; if (value === buffer) { // Special case when we are faking typed arrays in compatibility.js. result = value; } else if (transferable) { result = new value.constructor(buffer, value.byteOffset, value.byteLength); } else { result = new value.constructor(value); } cloned.set(value, result); return result; } result = isArray(value) ? [] : {}; cloned.set(value, result); // adding to cache now for cyclic references // Cloning all value and object properties, however ignoring properties // defined via getter. for (var i in value) { var desc, p = value; while (!(desc = Object.getOwnPropertyDescriptor(p, i))) { p = Object.getPrototypeOf(p); } if (typeof desc.value === 'undefined' || typeof desc.value === 'function') { continue; } result[i] = cloneValue(desc.value); } return result; } if (!this._defer) { this._listeners.forEach(function (listener) { listener.call(this, {data: obj}); }, this); return; } var cloned = new WeakMap(); var e = {data: cloneValue(obj)}; this._deferred.then(function () { this._listeners.forEach(function (listener) { listener.call(this, e); }, this); }.bind(this)); }, addEventListener: function (name, listener) { this._listeners.push(listener); }, removeEventListener: function (name, listener) { var i = this._listeners.indexOf(listener); this._listeners.splice(i, 1); }, terminate: function () { this._listeners = []; } }; function createCDNWrapper(url) { // We will rely on blob URL's property to specify origin. // We want this function to fail in case if createObjectURL or Blob do not // exist or fail for some reason -- our Worker creation will fail anyway. var wrapper = 'importScripts(\'' + url + '\');'; return URL.createObjectURL(new Blob([wrapper])); } function PDFWorker(name) { this.name = name; this.destroyed = false; this._readyCapability = createPromiseCapability(); this._port = null; this._webWorker = null; this._messageHandler = null; this._initialize(); } PDFWorker.prototype = /** @lends PDFWorker.prototype */ { get promise() { return this._readyCapability.promise; }, get port() { return this._port; }, get messageHandler() { return this._messageHandler; }, _initialize: function PDFWorker_initialize() { // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fulfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an // Uint8Array as it arrives on the worker. (Chrome added this with v.15.) if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') { var workerSrc = getWorkerSrc(); try { // Wraps workerSrc path into blob URL, if the former does not belong // to the same origin. if (!isSameOrigin(window.location.href, workerSrc)) { workerSrc = createCDNWrapper( new URL(workerSrc, window.location).href); } // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', 'worker', worker); var terminateEarly = function() { worker.removeEventListener('error', onWorkerError); messageHandler.destroy(); worker.terminate(); if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); } else { // Fall back to fake worker if the termination is caused by an // error (e.g. NetworkError / SecurityError). this._setupFakeWorker(); } }.bind(this); var onWorkerError = function(event) { if (!this._webWorker) { // Worker failed to initialize due to an error. Clean up and fall // back to the fake worker. terminateEarly(); } }.bind(this); worker.addEventListener('error', onWorkerError); messageHandler.on('test', function PDFWorker_test(data) { worker.removeEventListener('error', onWorkerError); if (this.destroyed) { terminateEarly(); return; // worker was destroyed } var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this._messageHandler = messageHandler; this._port = worker; this._webWorker = worker; if (!data.supportTransfers) { isPostMessageTransfersDisabled = true; } this._readyCapability.resolve(); // Send global setting, e.g. verbosity level. messageHandler.send('configure', { verbosity: getVerbosityLevel() }); } else { this._setupFakeWorker(); messageHandler.destroy(); worker.terminate(); } }.bind(this)); messageHandler.on('console_log', function (data) { console.log.apply(console, data); }); messageHandler.on('console_error', function (data) { console.error.apply(console, data); }); messageHandler.on('ready', function (data) { worker.removeEventListener('error', onWorkerError); if (this.destroyed) { terminateEarly(); return; // worker was destroyed } try { sendTest(); } catch (e) { // We need fallback to a faked worker. this._setupFakeWorker(); } }.bind(this)); var sendTest = function () { var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled; var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } }; // It might take time for worker to initialize (especially when AMD // loader is used). We will try to send test immediately, and then // when 'ready' message will arrive. The worker shall process only // first received 'test'. sendTest(); return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. this._setupFakeWorker(); }, _setupFakeWorker: function PDFWorker_setupFakeWorker() { if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) { warn('Setting up fake worker.'); isWorkerDisabled = true; } setupFakeWorkerGlobal().then(function (WorkerMessageHandler) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); return; } // We cannot turn on proper fake port simulation (this includes // structured cloning) when typed arrays are not supported. Relying // on a chance that messages will be sent in proper order. var isTypedArraysPresent = Uint8Array !== Float32Array; var port = new FakeWorkerPort(isTypedArraysPresent); this._port = port; // All fake workers use the same port, making id unique. var id = 'fake' + (nextFakeWorkerId++); // If the main thread is our worker, setup the handling for the // messages -- the main thread sends to it self. var workerHandler = new MessageHandler(id + '_worker', id, port); WorkerMessageHandler.setup(workerHandler, port); var messageHandler = new MessageHandler(id, id + '_worker', port); this._messageHandler = messageHandler; this._readyCapability.resolve(); }.bind(this)); }, /** * Destroys the worker instance. */ destroy: function PDFWorker_destroy() { this.destroyed = true; if (this._webWorker) { // We need to terminate only web worker created resource. this._webWorker.terminate(); this._webWorker = null; } this._port = null; if (this._messageHandler) { this._messageHandler.destroy(); this._messageHandler = null; } } }; return PDFWorker; })(); /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) { this.messageHandler = messageHandler; this.loadingTask = loadingTask; this.pdfDataRangeTransport = pdfDataRangeTransport; this.commonObjs = new PDFObjects(); this.fontLoader = new FontLoader(loadingTask.docId); this.destroyed = false; this.destroyCapability = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = createPromiseCapability(); this.setupMessageHandler(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { if (this.destroyCapability) { return this.destroyCapability.promise; } this.destroyed = true; this.destroyCapability = createPromiseCapability(); var waitOn = []; // We need to wait for all renderings to be completed, e.g. // timeout/rAF can take a long time. this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } }); this.pageCache = []; this.pagePromises = []; var self = this; // We also need to wait for the worker to finish its long running tasks. var terminated = this.messageHandler.sendWithPromise('Terminate', null); waitOn.push(terminated); Promise.all(waitOn).then(function () { self.fontLoader.clear(); if (self.pdfDataRangeTransport) { self.pdfDataRangeTransport.abort(); self.pdfDataRangeTransport = null; } if (self.messageHandler) { self.messageHandler.destroy(); self.messageHandler = null; } self.destroyCapability.resolve(); }, this.destroyCapability.reject); return this.destroyCapability.promise; }, setupMessageHandler: function WorkerTransport_setupMessageHandler() { var messageHandler = this.messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); pdfDataRangeTransport.addProgressiveReadListener(function(chunk) { messageHandler.send('OnDataRange', { chunk: chunk }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var loadingTask = this.loadingTask; var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask); this.pdfDocument = pdfDocument; loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportNeedPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject( new InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject( new MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject( new UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject( new UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) { if (this.pdfDataRangeTransport) { this.pdfDataRangeTransport.transportReady(); } }, this); messageHandler.on('StartRenderPage', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; if ('error' in exportedData) { var exportedError = exportedData.error; warn('Error during font loading: ' + exportedError); this.commonObjs.resolve(id, exportedError); break; } var fontRegistry = null; if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) { fontRegistry = { registerFont: function (font, url) { globalScope['FontInspector'].fontAdded(font, url); } }; } var font = new FontFaceObject(exportedData, { isEvalSuported: getDefaultSetting('isEvalSupported'), disableFontFace: getDefaultSetting('disableFontFace'), fontRegistry: fontRegistry }); this.fontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { error(data.error); } if (intentState.operatorList) { // Mark operator list as complete. intentState.operatorList.lastChunk = true; for (var i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } } }, this); messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var featureId = data.featureId; var loadingTask = this.loadingTask; if (loadingTask.onUnsupportedFeature) { loadingTask.onUnsupportedFeature(featureId); } _UnsupportedManager.notify(featureId); }, this); messageHandler.on('JpegDecode', function(data) { if (this.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject( new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height}); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }, this); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { if (this.destroyed) { throw new Error('Transport destroyed'); } var page = new PDFPageProxy(pageIndex, pageInfo, this); this.pageCache[pageIndex] = page; return page; }.bind(this)); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref, }).catch(function (reason) { return Promise.reject(new Error(reason)); }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex, intent: intent, }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id }); }, getPageLabels: function WorkerTransport_getPageLabels() { return this.messageHandler.sendWithPromise('GetPageLabels', null); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null). then(function transportMetadata(results) { return { info: results[0], metadata: (results[1] ? new Metadata(results[1]) : null) }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.sendWithPromise('Cleanup', null). then(function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.cleanup(); } } this.commonObjs.clear(); this.fontLoader.clear(); }.bind(this)); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = Object.create(null); } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: createPromiseCapability(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = Object.create(null); } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class * @alias RenderTask */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ this.onContinue = null; } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Promise for rendering task completion. * @return {Promise} */ get promise() { return this._internalRenderTask.capability.promise; }, /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, /** * Registers callbacks to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.useRequestAnimationFrame = false; this.cancelled = false; this.capability = createPromiseCapability(); this.task = new RenderTask(this); // caching this-bound methods this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); } InternalRenderTask.prototype = { initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) { if (this.cancelled) { return; } if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.transform, params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue.call(this.task, this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { if (this.useRequestAnimationFrame && typeof window !== 'undefined') { window.requestAnimationFrame(this._nextBound); } else { Promise.resolve(undefined).then(this._nextBound); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); /** * (Deprecated) Global observer of unsupported feature usages. Use * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance. */ var _UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead'); listeners.push(cb); }, notify: function (featureId) { for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); if (typeof pdfjsVersion !== 'undefined') { exports.version = pdfjsVersion; } if (typeof pdfjsBuild !== 'undefined') { exports.build = pdfjsBuild; } exports.getDocument = getDocument; exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFWorker = PDFWorker; exports.PDFDocumentProxy = PDFDocumentProxy; exports.PDFPageProxy = PDFPageProxy; exports._UnsupportedManager = _UnsupportedManager; })); (function (root, factory) { { factory((root.pdfjsDisplayGlobal = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI, root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer, root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG); } }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI, displayAnnotationLayer, displayTextLayer, displayMetadata, displaySVG) { var globalScope = sharedUtil.globalScope; var deprecated = sharedUtil.deprecated; var warn = sharedUtil.warn; var LinkTarget = displayDOMUtils.LinkTarget; var isWorker = (typeof window === 'undefined'); // The global PDFJS object is now deprecated and will not be supported in // the future. The members below are maintained for backward compatibility // and shall not be extended or modified. If the global.js is included as // a module, we will create a global PDFJS object instance or use existing. if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } var PDFJS = globalScope.PDFJS; if (typeof pdfjsVersion !== 'undefined') { PDFJS.version = pdfjsVersion; } if (typeof pdfjsBuild !== 'undefined') { PDFJS.build = pdfjsBuild; } PDFJS.pdfBug = false; if (PDFJS.verbosity !== undefined) { sharedUtil.setVerbosityLevel(PDFJS.verbosity); } delete PDFJS.verbosity; Object.defineProperty(PDFJS, 'verbosity', { get: function () { return sharedUtil.getVerbosityLevel(); }, set: function (level) { sharedUtil.setVerbosityLevel(level); }, enumerable: true, configurable: true }); PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS; PDFJS.OPS = sharedUtil.OPS; PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES; PDFJS.isValidUrl = sharedUtil.isValidUrl; PDFJS.shadow = sharedUtil.shadow; PDFJS.createBlob = sharedUtil.createBlob; PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) { return sharedUtil.createObjectURL(data, contentType, PDFJS.disableCreateObjectURL); }; Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { var value = sharedUtil.isLittleEndian(); return sharedUtil.shadow(PDFJS, 'isLittleEndian', value); } }); PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters; PDFJS.PasswordResponses = sharedUtil.PasswordResponses; PDFJS.PasswordException = sharedUtil.PasswordException; PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException; PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException; PDFJS.MissingPDFException = sharedUtil.MissingPDFException; PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException; PDFJS.Util = sharedUtil.Util; PDFJS.PageViewport = sharedUtil.PageViewport; PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability; /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /** * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font * renderer that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will * happen automatically if the browser doesn't support workers or sending * typed arrays to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled * in development mode. If unspecified in the production build, the worker * will be loaded based on the location of the pdf.js file. It is recommended * that the workerSrc is set in a custom application to prevent issues caused * by third-party frameworks and libraries. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable streaming of PDF file data. By default PDF.js attempts to load PDF * in chunks. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableStream = (PDFJS.disableStream === undefined ? false : PDFJS.disableStream); /** * Disable pre-fetching of PDF file data. When range requests are enabled * PDF.js will automatically keep fetching more data even if it isn't needed * to display the current page. This default behavior can be disabled. * * NOTE: It is also necessary to disable streaming, see above, * in order for disabling of pre-fetching to work correctly. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Specifies the |target| attribute for external links. * The constants from PDFJS.LinkTarget should be used: * - NONE [default] * - SELF * - BLANK * - PARENT * - TOP * @var {number} */ PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ? LinkTarget.NONE : PDFJS.externalLinkTarget); /** * Specifies the |rel| attribute for external links. Defaults to stripping * the referrer. * @var {string} */ PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel); /** * Determines if we can eval strings as JS. Primarily used to improve * performance for font rendering. * @var {boolean} */ PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported); var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow; delete PDFJS.openExternalLinksInNewWindow; Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', { get: function () { return PDFJS.externalLinkTarget === LinkTarget.BLANK; }, set: function (value) { if (value) { deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'); } if (PDFJS.externalLinkTarget !== LinkTarget.NONE) { warn('PDFJS.externalLinkTarget is already initialized'); return; } PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE; }, enumerable: true, configurable: true }); if (savedOpenExternalLinksInNewWindow) { /** * (Deprecated) Opens external links in a new window if enabled. * The default behavior opens external links in the PDF.js window. * * NOTE: This property has been deprecated, please use * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead. * @var {boolean} */ PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow; } PDFJS.getDocument = displayAPI.getDocument; PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport; PDFJS.PDFWorker = displayAPI.PDFWorker; Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { var value = displayDOMUtils.hasCanvasTypedArrays(); return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value); } }); PDFJS.CustomStyle = displayDOMUtils.CustomStyle; PDFJS.LinkTarget = LinkTarget; PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes; PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl; PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet; PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer; PDFJS.renderTextLayer = displayTextLayer.renderTextLayer; PDFJS.Metadata = displayMetadata.Metadata; PDFJS.SVGGraphics = displaySVG.SVGGraphics; PDFJS.UnsupportedManager = displayAPI._UnsupportedManager; exports.globalScope = globalScope; exports.isWorker = isWorker; exports.PDFJS = globalScope.PDFJS; })); }).call(pdfjsLibs); exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS; exports.build = pdfjsLibs.pdfjsDisplayAPI.build; exports.version = pdfjsLibs.pdfjsDisplayAPI.version; exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument; exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport; exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker; exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer; exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer; exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle; exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses; exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException; exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException; exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics; exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException; exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS; exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES; exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl; exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL; exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters; exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow; exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob; exports.getFilenameFromUrl = pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl; exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes; }));
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/libs/fineuploader.js
3,761
/** * http://github.com/Valums-File-Uploader/file-uploader * * Multiple file upload component with progress-bar, drag-and-drop, support for all modern browsers. * * Original version: 1.0 © 2010 Andrew Valums ( andrew(at)valums.com ) * Current Maintainer (2.0+): © 2012, Ray Nicholus ( fineuploader(at)garstasio.com ) * * Licensed under MIT license, GNU GPL 2 or later, GNU LGPL 2 or later, see license.txt. */ /*globals window, navigator, document, FormData, File, HTMLInputElement, XMLHttpRequest, Blob*/ var qq = function(element) { "use strict"; return { hide: function() { element.style.display = 'none'; return this; }, /** Returns the function which detaches attached event */ attach: function(type, fn) { if (element.addEventListener){ element.addEventListener(type, fn, false); } else if (element.attachEvent){ element.attachEvent('on' + type, fn); } return function() { qq(element).detach(type, fn); }; }, detach: function(type, fn) { if (element.removeEventListener){ element.removeEventListener(type, fn, false); } else if (element.attachEvent){ element.detachEvent('on' + type, fn); } return this; }, contains: function(descendant) { // compareposition returns false in this case if (element === descendant) { return true; } if (element.contains){ return element.contains(descendant); } else { /*jslint bitwise: true*/ return !!(descendant.compareDocumentPosition(element) & 8); } }, /** * Insert this element before elementB. */ insertBefore: function(elementB) { elementB.parentNode.insertBefore(element, elementB); return this; }, remove: function() { element.parentNode.removeChild(element); return this; }, /** * Sets styles for an element. * Fixes opacity in IE6-8. */ css: function(styles) { if (styles.opacity !== null){ if (typeof element.style.opacity !== 'string' && typeof(element.filters) !== 'undefined'){ styles.filter = 'alpha(opacity=' + Math.round(100 * styles.opacity) + ')'; } } qq.extend(element.style, styles); return this; }, hasClass: function(name) { var re = new RegExp('(^| )' + name + '( |$)'); return re.test(element.className); }, addClass: function(name) { if (!qq(element).hasClass(name)){ element.className += ' ' + name; } return this; }, removeClass: function(name) { var re = new RegExp('(^| )' + name + '( |$)'); element.className = element.className.replace(re, ' ').replace(/^\s+|\s+$/g, ""); return this; }, getByClass: function(className) { var candidates, result = []; if (element.querySelectorAll){ return element.querySelectorAll('.' + className); } candidates = element.getElementsByTagName("*"); qq.each(candidates, function(idx, val) { if (qq(val).hasClass(className)){ result.push(val); } }); return result; }, children: function() { var children = [], child = element.firstChild; while (child){ if (child.nodeType === 1){ children.push(child); } child = child.nextSibling; } return children; }, setText: function(text) { element.innerText = text; element.textContent = text; return this; }, clearText: function() { return qq(element).setText(""); } }; }; qq.log = function(message, level) { "use strict"; if (window.console) { if (!level || level === 'info') { window.console.log(message); } else { if (window.console[level]) { window.console[level](message); } else { window.console.log('<' + level + '> ' + message); } } } }; qq.isObject = function(variable) { "use strict"; return variable !== null && variable && typeof(variable) === "object" && variable.constructor === Object; }; qq.isFunction = function(variable) { "use strict"; return typeof(variable) === "function"; }; qq.trimStr = function(string) { if (String.prototype.trim) { return string.trim(); } return string.replace(/^\s+|\s+$/g,''); }; qq.isFileOrInput = function(maybeFileOrInput) { "use strict"; if (qq.isBlob(maybeFileOrInput) && window.File && maybeFileOrInput instanceof File) { return true; } else if (window.HTMLInputElement) { if (maybeFileOrInput instanceof HTMLInputElement) { if (maybeFileOrInput.type && maybeFileOrInput.type.toLowerCase() === 'file') { return true; } } } else if (maybeFileOrInput.tagName) { if (maybeFileOrInput.tagName.toLowerCase() === 'input') { if (maybeFileOrInput.type && maybeFileOrInput.type.toLowerCase() === 'file') { return true; } } } return false; }; qq.isBlob = function(maybeBlob) { "use strict"; return window.Blob && maybeBlob instanceof Blob; }; qq.isXhrUploadSupported = function() { "use strict"; var input = document.createElement('input'); input.type = 'file'; return ( input.multiple !== undefined && typeof File !== "undefined" && typeof FormData !== "undefined" && typeof (new XMLHttpRequest()).upload !== "undefined" ); }; qq.isFolderDropSupported = function(dataTransfer) { "use strict"; return (dataTransfer.items && dataTransfer.items[0].webkitGetAsEntry); }; qq.isFileChunkingSupported = function() { "use strict"; return !qq.android() && //android's impl of Blob.slice is broken qq.isXhrUploadSupported() && (File.prototype.slice || File.prototype.webkitSlice || File.prototype.mozSlice); }; qq.extend = function (first, second, extendNested) { "use strict"; qq.each(second, function(prop, val) { if (extendNested && qq.isObject(val)) { if (first[prop] === undefined) { first[prop] = {}; } qq.extend(first[prop], val, true); } else { first[prop] = val; } }); }; /** * Searches for a given element in the array, returns -1 if it is not present. * @param {Number} [from] The index at which to begin the search */ qq.indexOf = function(arr, elt, from){ "use strict"; if (arr.indexOf) { return arr.indexOf(elt, from); } from = from || 0; var len = arr.length; if (from < 0) { from += len; } for (; from < len; from+=1){ if (arr.hasOwnProperty(from) && arr[from] === elt){ return from; } } return -1; }; //this is a version 4 UUID qq.getUniqueId = function(){ "use strict"; return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { /*jslint eqeq: true, bitwise: true*/ var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8); return v.toString(16); }); }; // // Browsers and platforms detection qq.ie = function(){ "use strict"; return navigator.userAgent.indexOf('MSIE') !== -1; }; qq.ie10 = function(){ "use strict"; return navigator.userAgent.indexOf('MSIE 10') !== -1; }; qq.safari = function(){ "use strict"; return navigator.vendor !== undefined && navigator.vendor.indexOf("Apple") !== -1; }; qq.chrome = function(){ "use strict"; return navigator.vendor !== undefined && navigator.vendor.indexOf('Google') !== -1; }; qq.firefox = function(){ "use strict"; return (navigator.userAgent.indexOf('Mozilla') !== -1 && navigator.vendor !== undefined && navigator.vendor === ''); }; qq.windows = function(){ "use strict"; return navigator.platform === "Win32"; }; qq.android = function(){ "use strict"; return navigator.userAgent.toLowerCase().indexOf('android') !== -1; }; // // Events qq.preventDefault = function(e){ "use strict"; if (e.preventDefault){ e.preventDefault(); } else{ e.returnValue = false; } }; /** * Creates and returns element from html string * Uses innerHTML to create an element */ qq.toElement = (function(){ "use strict"; var div = document.createElement('div'); return function(html){ div.innerHTML = html; var element = div.firstChild; div.removeChild(element); return element; }; }()); //key and value are passed to callback for each item in the object or array qq.each = function(obj, callback) { "use strict"; var key, retVal; if (obj) { for (key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { retVal = callback(key, obj[key]); if (retVal === false) { break; } } } } }; /** * obj2url() takes a json-object as argument and generates * a querystring. pretty much like jQuery.param() * * how to use: * * `qq.obj2url({a:'b',c:'d'},'http://any.url/upload?otherParam=value');` * * will result in: * * `http://any.url/upload?otherParam=value&a=b&c=d` * * @param Object JSON-Object * @param String current querystring-part * @return String encoded querystring */ qq.obj2url = function(obj, temp, prefixDone){ "use strict"; /*jshint laxbreak: true*/ var i, len, uristrings = [], prefix = '&', add = function(nextObj, i){ var nextTemp = temp ? (/\[\]$/.test(temp)) // prevent double-encoding ? temp : temp+'['+i+']' : i; if ((nextTemp !== 'undefined') && (i !== 'undefined')) { uristrings.push( (typeof nextObj === 'object') ? qq.obj2url(nextObj, nextTemp, true) : (Object.prototype.toString.call(nextObj) === '[object Function]') ? encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj()) : encodeURIComponent(nextTemp) + '=' + encodeURIComponent(nextObj) ); } }; if (!prefixDone && temp) { prefix = (/\?/.test(temp)) ? (/\?$/.test(temp)) ? '' : '&' : '?'; uristrings.push(temp); uristrings.push(qq.obj2url(obj)); } else if ((Object.prototype.toString.call(obj) === '[object Array]') && (typeof obj !== 'undefined') ) { // we wont use a for-in-loop on an array (performance) for (i = -1, len = obj.length; i < len; i+=1){ add(obj[i], i); } } else if ((typeof obj !== 'undefined') && (obj !== null) && (typeof obj === "object")){ // for anything else but a scalar, we will use for-in-loop for (i in obj){ if (obj.hasOwnProperty(i)) { add(obj[i], i); } } } else { uristrings.push(encodeURIComponent(temp) + '=' + encodeURIComponent(obj)); } if (temp) { return uristrings.join(prefix); } else { return uristrings.join(prefix) .replace(/^&/, '') .replace(/%20/g, '+'); } }; qq.obj2FormData = function(obj, formData, arrayKeyName) { "use strict"; if (!formData) { formData = new FormData(); } qq.each(obj, function(key, val) { key = arrayKeyName ? arrayKeyName + '[' + key + ']' : key; if (qq.isObject(val)) { qq.obj2FormData(val, formData, key); } else if (qq.isFunction(val)) { formData.append(key, val()); } else { formData.append(key, val); } }); return formData; }; qq.obj2Inputs = function(obj, form) { "use strict"; var input; if (!form) { form = document.createElement('form'); } qq.obj2FormData(obj, { append: function(key, val) { input = document.createElement('input'); input.setAttribute('name', key); input.setAttribute('value', val); form.appendChild(input); } }); return form; }; qq.setCookie = function(name, value, days) { var date = new Date(), expires = ""; if (days) { date.setTime(date.getTime()+(days*24*60*60*1000)); expires = "; expires="+date.toGMTString(); } document.cookie = name+"="+value+expires+"; path=/"; }; qq.getCookie = function(name) { var nameEQ = name + "=", ca = document.cookie.split(';'), c; for(var i=0;i < ca.length;i++) { c = ca[i]; while (c.charAt(0)==' ') { c = c.substring(1,c.length); } if (c.indexOf(nameEQ) === 0) { return c.substring(nameEQ.length,c.length); } } }; qq.getCookieNames = function(regexp) { var cookies = document.cookie.split(';'), cookieNames = []; qq.each(cookies, function(idx, cookie) { cookie = qq.trimStr(cookie); var equalsIdx = cookie.indexOf("="); if (cookie.match(regexp)) { cookieNames.push(cookie.substr(0, equalsIdx)); } }); return cookieNames; }; qq.deleteCookie = function(name) { qq.setCookie(name, "", -1); }; qq.areCookiesEnabled = function() { var randNum = Math.random() * 100000, name = "qqCookieTest:" + randNum; qq.setCookie(name, 1); if (qq.getCookie(name)) { qq.deleteCookie(name); return true; } return false; }; /** * Not recommended for use outside of Fine Uploader since this falls back to an unchecked eval if JSON.parse is not * implemented. For a more secure JSON.parse polyfill, use Douglas Crockford's json2.js. */ qq.parseJson = function(json) { /*jshint evil: true*/ if (window.JSON && qq.isFunction(JSON.parse)) { return JSON.parse(json); } else { return eval("(" + json + ")"); } }; /** * A generic module which supports object disposing in dispose() method. * */ qq.DisposeSupport = function() { "use strict"; var disposers = []; return { /** Run all registered disposers */ dispose: function() { var disposer; do { disposer = disposers.shift(); if (disposer) { disposer(); } } while (disposer); }, /** Attach event handler and register de-attacher as a disposer */ attach: function() { var args = arguments; /*jslint undef:true*/ this.addDisposer(qq(args[0]).attach.apply(this, Array.prototype.slice.call(arguments, 1))); }, /** Add disposer to the collection */ addDisposer: function(disposeFunction) { disposers.push(disposeFunction); } }; }; qq.UploadButton = function(o){ this._options = { element: null, // if set to true adds multiple attribute to file input multiple: false, acceptFiles: null, // name attribute of file input name: 'file', onChange: function(input){}, hoverClass: 'qq-upload-button-hover', focusClass: 'qq-upload-button-focus' }; qq.extend(this._options, o); this._disposeSupport = new qq.DisposeSupport(); this._element = this._options.element; // make button suitable container for input qq(this._element).css({ position: 'relative', overflow: 'hidden', // Make sure browse button is in the right side // in Internet Explorer direction: 'ltr' }); this._input = this._createInput(); }; qq.UploadButton.prototype = { /* returns file input element */ getInput: function(){ return this._input; }, /* cleans/recreates the file input */ reset: function(){ if (this._input.parentNode){ qq(this._input).remove(); } qq(this._element).removeClass(this._options.focusClass); this._input = this._createInput(); }, _createInput: function(){ var input = document.createElement("input"); if (this._options.multiple){ input.setAttribute("multiple", "multiple"); } if (this._options.acceptFiles) input.setAttribute("accept", this._options.acceptFiles); input.setAttribute("type", "file"); input.setAttribute("name", this._options.name); qq(input).css({ position: 'absolute', // in Opera only 'browse' button // is clickable and it is located at // the right side of the input right: 0, top: 0, fontFamily: 'Arial', // 4 persons reported this, the max values that worked for them were 243, 236, 236, 118 fontSize: '118px', margin: 0, padding: 0, cursor: 'pointer', opacity: 0 }); this._element.appendChild(input); var self = this; this._disposeSupport.attach(input, 'change', function(){ self._options.onChange(input); }); this._disposeSupport.attach(input, 'mouseover', function(){ qq(self._element).addClass(self._options.hoverClass); }); this._disposeSupport.attach(input, 'mouseout', function(){ qq(self._element).removeClass(self._options.hoverClass); }); this._disposeSupport.attach(input, 'focus', function(){ qq(self._element).addClass(self._options.focusClass); }); this._disposeSupport.attach(input, 'blur', function(){ qq(self._element).removeClass(self._options.focusClass); }); // IE and Opera, unfortunately have 2 tab stops on file input // which is unacceptable in our case, disable keyboard access if (window.attachEvent){ // it is IE or Opera input.setAttribute('tabIndex', "-1"); } return input; } }; qq.FineUploaderBasic = function(o){ var that = this; this._options = { debug: false, button: null, multiple: true, maxConnections: 3, disableCancelForFormUploads: false, autoUpload: true, request: { endpoint: '/server/upload', params: {}, paramsInBody: true, customHeaders: {}, forceMultipart: true, inputName: 'qqfile', uuidName: 'qquuid', totalFileSizeName: 'qqtotalfilesize' }, validation: { allowedExtensions: [], sizeLimit: 0, minSizeLimit: 0, stopOnFirstInvalidFile: true }, callbacks: { onSubmit: function(id, name){}, onComplete: function(id, name, responseJSON){}, onCancel: function(id, name){}, onUpload: function(id, name){}, onUploadChunk: function(id, name, chunkData){}, onResume: function(id, fileName, chunkData){}, onProgress: function(id, name, loaded, total){}, onError: function(id, name, reason) {}, onAutoRetry: function(id, name, attemptNumber) {}, onManualRetry: function(id, name) {}, onValidateBatch: function(fileOrBlobData) {}, onValidate: function(fileOrBlobData) {}, onSubmitDelete: function(id) {}, onDelete: function(id){}, onDeleteComplete: function(id, xhr, isError){} }, messages: { typeError: "{file} has an invalid extension. Valid extension(s): {extensions}.", sizeError: "{file} is too large, maximum file size is {sizeLimit}.", minSizeError: "{file} is too small, minimum file size is {minSizeLimit}.", emptyError: "{file} is empty, please select files again without it.", noFilesError: "No files to upload.", onLeave: "The files are being uploaded, if you leave now the upload will be cancelled." }, retry: { enableAuto: false, maxAutoAttempts: 3, autoAttemptDelay: 5, preventRetryResponseProperty: 'preventRetry' }, classes: { buttonHover: 'qq-upload-button-hover', buttonFocus: 'qq-upload-button-focus' }, chunking: { enabled: false, partSize: 2000000, paramNames: { partIndex: 'qqpartindex', partByteOffset: 'qqpartbyteoffset', chunkSize: 'qqchunksize', totalFileSize: 'qqtotalfilesize', totalParts: 'qqtotalparts', filename: 'qqfilename' } }, resume: { enabled: false, id: null, cookiesExpireIn: 7, //days paramNames: { resuming: "qqresume" } }, formatFileName: function(fileOrBlobName) { if (fileOrBlobName.length > 33) { fileOrBlobName = fileOrBlobName.slice(0, 19) + '...' + fileOrBlobName.slice(-14); } return fileOrBlobName; }, text: { sizeSymbols: ['kB', 'MB', 'GB', 'TB', 'PB', 'EB'] }, deleteFile : { enabled: false, endpoint: '/server/upload', customHeaders: {}, params: {} }, cors: { expected: false, sendCredentials: false }, blobs: { defaultName: 'Misc data', paramNames: { name: 'qqblobname' } } }; qq.extend(this._options, o, true); this._wrapCallbacks(); this._disposeSupport = new qq.DisposeSupport(); // number of files being uploaded this._filesInProgress = []; this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._paramsStore = this._createParamsStore("request"); this._deleteFileParamsStore = this._createParamsStore("deleteFile"); this._endpointStore = this._createEndpointStore("request"); this._deleteFileEndpointStore = this._createEndpointStore("deleteFile"); this._handler = this._createUploadHandler(); this._deleteHandler = this._createDeleteHandler(); if (this._options.button){ this._button = this._createUploadButton(this._options.button); } this._preventLeaveInProgress(); }; qq.FineUploaderBasic.prototype = { log: function(str, level) { if (this._options.debug && (!level || level === 'info')) { qq.log('[FineUploader] ' + str); } else if (level && level !== 'info') { qq.log('[FineUploader] ' + str, level); } }, setParams: function(params, id) { /*jshint eqeqeq: true, eqnull: true*/ if (id == null) { this._options.request.params = params; } else { this._paramsStore.setParams(params, id); } }, setDeleteFileParams: function(params, id) { /*jshint eqeqeq: true, eqnull: true*/ if (id == null) { this._options.deleteFile.params = params; } else { this._deleteFileParamsStore.setParams(params, id); } }, setEndpoint: function(endpoint, id) { /*jshint eqeqeq: true, eqnull: true*/ if (id == null) { this._options.request.endpoint = endpoint; } else { this._endpointStore.setEndpoint(endpoint, id); } }, getInProgress: function(){ return this._filesInProgress.length; }, uploadStoredFiles: function(){ "use strict"; var idToUpload; while(this._storedIds.length) { idToUpload = this._storedIds.shift(); this._filesInProgress.push(idToUpload); this._handler.upload(idToUpload); } }, clearStoredFiles: function(){ this._storedIds = []; }, retry: function(id) { if (this._onBeforeManualRetry(id)) { this._handler.retry(id); return true; } else { return false; } }, cancel: function(id) { this._handler.cancel(id); }, cancelAll: function() { var storedIdsCopy = [], self = this; qq.extend(storedIdsCopy, this._storedIds); qq.each(storedIdsCopy, function(idx, storedFileId) { self.cancel(storedFileId); }); this._handler.cancelAll(); }, reset: function() { this.log("Resetting uploader..."); this._handler.reset(); this._filesInProgress = []; this._storedIds = []; this._autoRetries = []; this._retryTimeouts = []; this._preventRetries = []; this._button.reset(); this._paramsStore.reset(); this._endpointStore.reset(); }, addFiles: function(filesBlobDataOrInputs) { var self = this, verifiedFilesOrInputs = [], index, fileOrInput; if (filesBlobDataOrInputs) { if (!window.FileList || !(filesBlobDataOrInputs instanceof FileList)) { filesBlobDataOrInputs = [].concat(filesBlobDataOrInputs); } for (index = 0; index < filesBlobDataOrInputs.length; index+=1) { fileOrInput = filesBlobDataOrInputs[index]; if (qq.isFileOrInput(fileOrInput)) { verifiedFilesOrInputs.push(fileOrInput); } else { self.log(fileOrInput + ' is not a File or INPUT element! Ignoring!', 'warn'); } } this.log('Processing ' + verifiedFilesOrInputs.length + ' files or inputs...'); this._uploadFileOrBlobDataList(verifiedFilesOrInputs); } }, addBlobs: function(blobDataOrArray) { if (blobDataOrArray) { var blobDataArray = [].concat(blobDataOrArray), verifiedBlobDataList = [], self = this; qq.each(blobDataArray, function(idx, blobData) { if (qq.isBlob(blobData) && !qq.isFileOrInput(blobData)) { verifiedBlobDataList.push({ blob: blobData, name: self._options.blobs.defaultName }); } else if (qq.isObject(blobData) && blobData.blob && blobData.name) { verifiedBlobDataList.push(blobData); } else { self.log("addBlobs: entry at index " + idx + " is not a Blob or a BlobData object", "error"); } }); this._uploadFileOrBlobDataList(verifiedBlobDataList); } else { this.log("undefined or non-array parameter passed into addBlobs", "error"); } }, getUuid: function(id) { return this._handler.getUuid(id); }, getResumableFilesData: function() { return this._handler.getResumableFilesData(); }, getSize: function(id) { return this._handler.getSize(id); }, getFile: function(fileOrBlobId) { return this._handler.getFile(fileOrBlobId); }, deleteFile: function(id) { this._onSubmitDelete(id); }, setDeleteFileEndpoint: function(endpoint, id) { /*jshint eqeqeq: true, eqnull: true*/ if (id == null) { this._options.deleteFile.endpoint = endpoint; } else { this._deleteFileEndpointStore.setEndpoint(endpoint, id); } }, _createUploadButton: function(element){ var self = this; var button = new qq.UploadButton({ element: element, multiple: this._options.multiple && qq.isXhrUploadSupported(), acceptFiles: this._options.validation.acceptFiles, onChange: function(input){ self._onInputChange(input); }, hoverClass: this._options.classes.buttonHover, focusClass: this._options.classes.buttonFocus }); this._disposeSupport.addDisposer(function() { button.dispose(); }); return button; }, _createUploadHandler: function(){ var self = this; return new qq.UploadHandler({ debug: this._options.debug, forceMultipart: this._options.request.forceMultipart, maxConnections: this._options.maxConnections, customHeaders: this._options.request.customHeaders, inputName: this._options.request.inputName, uuidParamName: this._options.request.uuidName, totalFileSizeParamName: this._options.request.totalFileSizeName, cors: this._options.cors, demoMode: this._options.demoMode, paramsInBody: this._options.request.paramsInBody, paramsStore: this._paramsStore, endpointStore: this._endpointStore, chunking: this._options.chunking, resume: this._options.resume, blobs: this._options.blobs, log: function(str, level) { self.log(str, level); }, onProgress: function(id, name, loaded, total){ self._onProgress(id, name, loaded, total); self._options.callbacks.onProgress(id, name, loaded, total); }, onComplete: function(id, name, result, xhr){ self._onComplete(id, name, result, xhr); self._options.callbacks.onComplete(id, name, result); }, onCancel: function(id, name){ self._onCancel(id, name); self._options.callbacks.onCancel(id, name); }, onUpload: function(id, name){ self._onUpload(id, name); self._options.callbacks.onUpload(id, name); }, onUploadChunk: function(id, name, chunkData){ self._options.callbacks.onUploadChunk(id, name, chunkData); }, onResume: function(id, name, chunkData) { return self._options.callbacks.onResume(id, name, chunkData); }, onAutoRetry: function(id, name, responseJSON, xhr) { self._preventRetries[id] = responseJSON[self._options.retry.preventRetryResponseProperty]; if (self._shouldAutoRetry(id, name, responseJSON)) { self._maybeParseAndSendUploadError(id, name, responseJSON, xhr); self._options.callbacks.onAutoRetry(id, name, self._autoRetries[id] + 1); self._onBeforeAutoRetry(id, name); self._retryTimeouts[id] = setTimeout(function() { self._onAutoRetry(id, name, responseJSON) }, self._options.retry.autoAttemptDelay * 1000); return true; } else { return false; } } }); }, _createDeleteHandler: function() { var self = this; return new qq.DeleteFileAjaxRequestor({ maxConnections: this._options.maxConnections, customHeaders: this._options.deleteFile.customHeaders, paramsStore: this._deleteFileParamsStore, endpointStore: this._deleteFileEndpointStore, demoMode: this._options.demoMode, cors: this._options.cors, log: function(str, level) { self.log(str, level); }, onDelete: function(id) { self._onDelete(id); self._options.callbacks.onDelete(id); }, onDeleteComplete: function(id, xhr, isError) { self._onDeleteComplete(id, xhr, isError); self._options.callbacks.onDeleteComplete(id, xhr, isError); } }); }, _preventLeaveInProgress: function(){ var self = this; this._disposeSupport.attach(window, 'beforeunload', function(e){ if (!self._filesInProgress.length){return;} var e = e || window.event; // for ie, ff e.returnValue = self._options.messages.onLeave; // for webkit return self._options.messages.onLeave; }); }, _onSubmit: function(id, name){ if (this._options.autoUpload) { this._filesInProgress.push(id); } }, _onProgress: function(id, name, loaded, total){ }, _onComplete: function(id, name, result, xhr){ this._removeFromFilesInProgress(id); this._maybeParseAndSendUploadError(id, name, result, xhr); }, _onCancel: function(id, name){ this._removeFromFilesInProgress(id); clearTimeout(this._retryTimeouts[id]); var storedItemIndex = qq.indexOf(this._storedIds, id); if (!this._options.autoUpload && storedItemIndex >= 0) { this._storedIds.splice(storedItemIndex, 1); } }, _isDeletePossible: function() { return (this._options.deleteFile.enabled && (!this._options.cors.expected || (this._options.cors.expected && (qq.ie10() || !qq.ie())) ) ); }, _onSubmitDelete: function(id) { if (this._isDeletePossible()) { if (this._options.callbacks.onSubmitDelete(id)) { this._deleteHandler.sendDelete(id, this.getUuid(id)); } } else { this.log("Delete request ignored for ID " + id + ", delete feature is disabled or request not possible " + "due to CORS on a user agent that does not support pre-flighting.", "warn"); return false; } }, _onDelete: function(fileId) {}, _onDeleteComplete: function(id, xhr, isError) { var name = this._handler.getName(id); if (isError) { this.log("Delete request for '" + name + "' has failed.", "error"); this._options.callbacks.onError(id, name, "Delete request failed with response code " + xhr.status); } else { this.log("Delete request for '" + name + "' has succeeded."); } }, _removeFromFilesInProgress: function(id) { var index = qq.indexOf(this._filesInProgress, id); if (index >= 0) { this._filesInProgress.splice(index, 1); } }, _onUpload: function(id, name){}, _onInputChange: function(input){ if (qq.isXhrUploadSupported()){ this.addFiles(input.files); } else { this.addFiles(input); } this._button.reset(); }, _onBeforeAutoRetry: function(id, name) { this.log("Waiting " + this._options.retry.autoAttemptDelay + " seconds before retrying " + name + "..."); }, _onAutoRetry: function(id, name, responseJSON) { this.log("Retrying " + name + "..."); this._autoRetries[id]++; this._handler.retry(id); }, _shouldAutoRetry: function(id, name, responseJSON) { if (!this._preventRetries[id] && this._options.retry.enableAuto) { if (this._autoRetries[id] === undefined) { this._autoRetries[id] = 0; } return this._autoRetries[id] < this._options.retry.maxAutoAttempts } return false; }, //return false if we should not attempt the requested retry _onBeforeManualRetry: function(id) { if (this._preventRetries[id]) { this.log("Retries are forbidden for id " + id, 'warn'); return false; } else if (this._handler.isValid(id)) { var fileName = this._handler.getName(id); if (this._options.callbacks.onManualRetry(id, fileName) === false) { return false; } this.log("Retrying upload for '" + fileName + "' (id: " + id + ")..."); this._filesInProgress.push(id); return true; } else { this.log("'" + id + "' is not a valid file ID", 'error'); return false; } }, _maybeParseAndSendUploadError: function(id, name, response, xhr) { //assuming no one will actually set the response code to something other than 200 and still set 'success' to true if (!response.success){ if (xhr && xhr.status !== 200 && !response.error) { this._options.callbacks.onError(id, name, "XHR returned response code " + xhr.status); } else { var errorReason = response.error ? response.error : "Upload failure reason unknown"; this._options.callbacks.onError(id, name, errorReason); } } }, _uploadFileOrBlobDataList: function(fileOrBlobDataList){ var validationDescriptors, index, batchInvalid; validationDescriptors = this._getValidationDescriptors(fileOrBlobDataList); batchInvalid = this._options.callbacks.onValidateBatch(validationDescriptors) === false; if (!batchInvalid) { if (fileOrBlobDataList.length > 0) { for (index = 0; index < fileOrBlobDataList.length; index++){ if (this._validateFileOrBlobData(fileOrBlobDataList[index])){ this._upload(fileOrBlobDataList[index]); } else { if (this._options.validation.stopOnFirstInvalidFile){ return; } } } } else { this._error('noFilesError', ""); } } }, _upload: function(blobOrFileContainer){ var id = this._handler.add(blobOrFileContainer); var name = this._handler.getName(id); if (this._options.callbacks.onSubmit(id, name) !== false){ this._onSubmit(id, name); if (this._options.autoUpload) { this._handler.upload(id); } else { this._storeForLater(id); } } }, _storeForLater: function(id) { this._storedIds.push(id); }, _validateFileOrBlobData: function(fileOrBlobData){ var validationDescriptor, name, size; validationDescriptor = this._getValidationDescriptor(fileOrBlobData); name = validationDescriptor.name; size = validationDescriptor.size; if (this._options.callbacks.onValidate(validationDescriptor) === false) { return false; } if (qq.isFileOrInput(fileOrBlobData) && !this._isAllowedExtension(name)){ this._error('typeError', name); return false; } else if (size === 0){ this._error('emptyError', name); return false; } else if (size && this._options.validation.sizeLimit && size > this._options.validation.sizeLimit){ this._error('sizeError', name); return false; } else if (size && size < this._options.validation.minSizeLimit){ this._error('minSizeError', name); return false; } return true; }, _error: function(code, name){ var message = this._options.messages[code]; function r(name, replacement){ message = message.replace(name, replacement); } var extensions = this._options.validation.allowedExtensions.join(', ').toLowerCase(); r('{file}', this._options.formatFileName(name)); r('{extensions}', extensions); r('{sizeLimit}', this._formatSize(this._options.validation.sizeLimit)); r('{minSizeLimit}', this._formatSize(this._options.validation.minSizeLimit)); this._options.callbacks.onError(null, name, message); return message; }, _isAllowedExtension: function(fileName){ var allowed = this._options.validation.allowedExtensions, valid = false; if (!allowed.length) { return true; } qq.each(allowed, function(idx, allowedExt) { /*jshint eqeqeq: true, eqnull: true*/ var extRegex = new RegExp('\\.' + allowedExt + "$", 'i'); if (fileName.match(extRegex) != null) { valid = true; return false; } }); return valid; }, _formatSize: function(bytes){ var i = -1; do { bytes = bytes / 1024; i++; } while (bytes > 99); return Math.max(bytes, 0.1).toFixed(1) + this._options.text.sizeSymbols[i]; }, _wrapCallbacks: function() { var self, safeCallback; self = this; safeCallback = function(name, callback, args) { try { return callback.apply(self, args); } catch (exception) { self.log("Caught exception in '" + name + "' callback - " + exception.message, 'error'); } } for (var prop in this._options.callbacks) { (function() { var callbackName, callbackFunc; callbackName = prop; callbackFunc = self._options.callbacks[callbackName]; self._options.callbacks[callbackName] = function() { return safeCallback(callbackName, callbackFunc, arguments); } }()); } }, _parseFileOrBlobDataName: function(fileOrBlobData) { var name; if (qq.isFileOrInput(fileOrBlobData)) { if (fileOrBlobData.value) { // it is a file input // get input value and remove path to normalize name = fileOrBlobData.value.replace(/.*(\/|\\)/, ""); } else { // fix missing properties in Safari 4 and firefox 11.0a2 name = (fileOrBlobData.fileName !== null && fileOrBlobData.fileName !== undefined) ? fileOrBlobData.fileName : fileOrBlobData.name; } } else { name = fileOrBlobData.name; } return name; }, _parseFileOrBlobDataSize: function(fileOrBlobData) { var size; if (qq.isFileOrInput(fileOrBlobData)) { if (!fileOrBlobData.value){ // fix missing properties in Safari 4 and firefox 11.0a2 size = (fileOrBlobData.fileSize !== null && fileOrBlobData.fileSize !== undefined) ? fileOrBlobData.fileSize : fileOrBlobData.size; } } else { size = fileOrBlobData.blob.size; } return size; }, _getValidationDescriptor: function(fileOrBlobData) { var name, size, fileDescriptor; fileDescriptor = {}; name = this._parseFileOrBlobDataName(fileOrBlobData); size = this._parseFileOrBlobDataSize(fileOrBlobData); fileDescriptor.name = name; if (size) { fileDescriptor.size = size; } return fileDescriptor; }, _getValidationDescriptors: function(files) { var self = this, fileDescriptors = []; qq.each(files, function(idx, file) { fileDescriptors.push(self._getValidationDescriptor(file)); }); return fileDescriptors; }, _createParamsStore: function(type) { var paramsStore = {}, self = this; return { setParams: function(params, id) { var paramsCopy = {}; qq.extend(paramsCopy, params); paramsStore[id] = paramsCopy; }, getParams: function(id) { /*jshint eqeqeq: true, eqnull: true*/ var paramsCopy = {}; if (id != null && paramsStore[id]) { qq.extend(paramsCopy, paramsStore[id]); } else { qq.extend(paramsCopy, self._options[type].params); } return paramsCopy; }, remove: function(fileId) { return delete paramsStore[fileId]; }, reset: function() { paramsStore = {}; } }; }, _createEndpointStore: function(type) { var endpointStore = {}, self = this; return { setEndpoint: function(endpoint, id) { endpointStore[id] = endpoint; }, getEndpoint: function(id) { /*jshint eqeqeq: true, eqnull: true*/ if (id != null && endpointStore[id]) { return endpointStore[id]; } return self._options[type].endpoint; }, remove: function(fileId) { return delete endpointStore[fileId]; }, reset: function() { endpointStore = {}; } }; } }; /*globals qq, document*/ qq.DragAndDrop = function(o) { "use strict"; var options, dz, dirPending, droppedFiles = [], droppedEntriesCount = 0, droppedEntriesParsedCount = 0, disposeSupport = new qq.DisposeSupport(); options = { dropArea: null, extraDropzones: [], hideDropzones: true, multiple: true, classes: { dropActive: null }, callbacks: { dropProcessing: function(isProcessing, files) {}, error: function(code, filename) {}, log: function(message, level) {} } }; qq.extend(options, o); function maybeUploadDroppedFiles() { if (droppedEntriesCount === droppedEntriesParsedCount && !dirPending) { options.callbacks.log('Grabbed ' + droppedFiles.length + " files after tree traversal."); dz.dropDisabled(false); options.callbacks.dropProcessing(false, droppedFiles); } } function addDroppedFile(file) { droppedFiles.push(file); droppedEntriesParsedCount+=1; maybeUploadDroppedFiles(); } function traverseFileTree(entry) { var dirReader, i; droppedEntriesCount+=1; if (entry.isFile) { entry.file(function(file) { addDroppedFile(file); }); } else if (entry.isDirectory) { dirPending = true; dirReader = entry.createReader(); dirReader.readEntries(function(entries) { droppedEntriesParsedCount+=1; for (i = 0; i < entries.length; i+=1) { traverseFileTree(entries[i]); } dirPending = false; if (!entries.length) { maybeUploadDroppedFiles(); } }); } } function handleDataTransfer(dataTransfer) { var i, items, entry; options.callbacks.dropProcessing(true); dz.dropDisabled(true); if (dataTransfer.files.length > 1 && !options.multiple) { options.callbacks.dropProcessing(false); options.callbacks.error('tooManyFilesError', ""); dz.dropDisabled(false); } else { droppedFiles = []; droppedEntriesCount = 0; droppedEntriesParsedCount = 0; if (qq.isFolderDropSupported(dataTransfer)) { items = dataTransfer.items; for (i = 0; i < items.length; i+=1) { entry = items[i].webkitGetAsEntry(); if (entry) { //due to a bug in Chrome's File System API impl - #149735 if (entry.isFile) { droppedFiles.push(items[i].getAsFile()); if (i === items.length-1) { maybeUploadDroppedFiles(); } } else { traverseFileTree(entry); } } } } else { options.callbacks.dropProcessing(false, dataTransfer.files); dz.dropDisabled(false); } } } function setupDropzone(dropArea){ dz = new qq.UploadDropZone({ element: dropArea, onEnter: function(e){ qq(dropArea).addClass(options.classes.dropActive); e.stopPropagation(); }, onLeaveNotDescendants: function(e){ qq(dropArea).removeClass(options.classes.dropActive); }, onDrop: function(e){ if (options.hideDropzones) { qq(dropArea).hide(); } qq(dropArea).removeClass(options.classes.dropActive); handleDataTransfer(e.dataTransfer); } }); disposeSupport.addDisposer(function() { dz.dispose(); }); if (options.hideDropzones) { qq(dropArea).hide(); } } function isFileDrag(dragEvent) { var fileDrag; qq.each(dragEvent.dataTransfer.types, function(key, val) { if (val === 'Files') { fileDrag = true; return false; } }); return fileDrag; } function setupDragDrop(){ if (options.dropArea) { options.extraDropzones.push(options.dropArea); } var i, dropzones = options.extraDropzones; for (i=0; i < dropzones.length; i+=1){ setupDropzone(dropzones[i]); } // IE <= 9 does not support the File API used for drag+drop uploads if (options.dropArea && (!qq.ie() || qq.ie10())) { disposeSupport.attach(document, 'dragenter', function(e) { if (!dz.dropDisabled() && isFileDrag(e)) { if (qq(options.dropArea).hasClass(options.classes.dropDisabled)) { return; } options.dropArea.style.display = 'block'; for (i=0; i < dropzones.length; i+=1) { dropzones[i].style.display = 'block'; } } }); } disposeSupport.attach(document, 'dragleave', function(e){ if (options.hideDropzones && qq.FineUploader.prototype._leaving_document_out(e)) { for (i=0; i < dropzones.length; i+=1) { qq(dropzones[i]).hide(); } } }); disposeSupport.attach(document, 'drop', function(e){ if (options.hideDropzones) { for (i=0; i < dropzones.length; i+=1) { qq(dropzones[i]).hide(); } } e.preventDefault(); }); } return { setup: function() { setupDragDrop(); }, setupExtraDropzone: function(element) { options.extraDropzones.push(element); setupDropzone(element); }, removeExtraDropzone: function(element) { var i, dzs = options.extraDropzones; for(i in dzs) { if (dzs[i] === element) { return dzs.splice(i, 1); } } }, dispose: function() { disposeSupport.dispose(); dz.dispose(); } }; }; qq.UploadDropZone = function(o){ "use strict"; var options, element, preventDrop, dropOutsideDisabled, disposeSupport = new qq.DisposeSupport(); options = { element: null, onEnter: function(e){}, onLeave: function(e){}, // is not fired when leaving element by hovering descendants onLeaveNotDescendants: function(e){}, onDrop: function(e){} }; qq.extend(options, o); element = options.element; function dragover_should_be_canceled(){ return qq.safari() || (qq.firefox() && qq.windows()); } function disableDropOutside(e){ // run only once for all instances if (!dropOutsideDisabled ){ // for these cases we need to catch onDrop to reset dropArea if (dragover_should_be_canceled){ disposeSupport.attach(document, 'dragover', function(e){ e.preventDefault(); }); } else { disposeSupport.attach(document, 'dragover', function(e){ if (e.dataTransfer){ e.dataTransfer.dropEffect = 'none'; e.preventDefault(); } }); } dropOutsideDisabled = true; } } function isValidFileDrag(e){ // e.dataTransfer currently causing IE errors // IE9 does NOT support file API, so drag-and-drop is not possible if (qq.ie() && !qq.ie10()) { return false; } var effectTest, dt = e.dataTransfer, // do not check dt.types.contains in webkit, because it crashes safari 4 isSafari = qq.safari(); // dt.effectAllowed is none in Safari 5 // dt.types.contains check is for firefox effectTest = qq.ie10() ? true : dt.effectAllowed !== 'none'; return dt && effectTest && (dt.files || (!isSafari && dt.types.contains && dt.types.contains('Files'))); } function isOrSetDropDisabled(isDisabled) { if (isDisabled !== undefined) { preventDrop = isDisabled; } return preventDrop; } function attachEvents(){ disposeSupport.attach(element, 'dragover', function(e){ if (!isValidFileDrag(e)) { return; } var effect = qq.ie() ? null : e.dataTransfer.effectAllowed; if (effect === 'move' || effect === 'linkMove'){ e.dataTransfer.dropEffect = 'move'; // for FF (only move allowed) } else { e.dataTransfer.dropEffect = 'copy'; // for Chrome } e.stopPropagation(); e.preventDefault(); }); disposeSupport.attach(element, 'dragenter', function(e){ if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } options.onEnter(e); } }); disposeSupport.attach(element, 'dragleave', function(e){ if (!isValidFileDrag(e)) { return; } options.onLeave(e); var relatedTarget = document.elementFromPoint(e.clientX, e.clientY); // do not fire when moving a mouse over a descendant if (qq(this).contains(relatedTarget)) { return; } options.onLeaveNotDescendants(e); }); disposeSupport.attach(element, 'drop', function(e){ if (!isOrSetDropDisabled()) { if (!isValidFileDrag(e)) { return; } e.preventDefault(); options.onDrop(e); } }); } disableDropOutside(); attachEvents(); return { dropDisabled: function(isDisabled) { return isOrSetDropDisabled(isDisabled); }, dispose: function() { disposeSupport.dispose(); } }; }; /** * Class that creates upload widget with drag-and-drop and file list * @inherits qq.FineUploaderBasic */ qq.FineUploader = function(o){ // call parent constructor qq.FineUploaderBasic.apply(this, arguments); // additional options qq.extend(this._options, { element: null, listElement: null, dragAndDrop: { extraDropzones: [], hideDropzones: true, disableDefaultDropzone: false }, text: { uploadButton: 'Upload a file', cancelButton: 'Cancel', retryButton: 'Retry', deleteButton: 'Delete', failUpload: 'Upload failed', dragZone: 'Drop files here to upload', dropProcessing: 'Processing dropped files...', formatProgress: "{percent}% of {total_size}", waitingForResponse: "Processing..." }, template: '<div class="qq-uploader">' + ((!this._options.dragAndDrop || !this._options.dragAndDrop.disableDefaultDropzone) ? '<div class="qq-upload-drop-area"><span>{dragZoneText}</span></div>' : '') + (!this._options.button ? '<div class="qq-upload-button"><div>{uploadButtonText}</div></div>' : '') + '<span class="qq-drop-processing"><span>{dropProcessingText}</span><span class="qq-drop-processing-spinner"></span></span>' + (!this._options.listElement ? '<ul class="qq-upload-list"></ul>' : '') + '</div>', // template for one item in file list fileTemplate: '<li>' + '<div class="qq-progress-bar"></div>' + '<span class="qq-upload-spinner"></span>' + '<span class="qq-upload-finished"></span>' + '<span class="qq-upload-file"></span>' + '<span class="qq-upload-size"></span>' + '<a class="qq-upload-cancel" href="#">{cancelButtonText}</a>' + '<a class="qq-upload-retry" href="#">{retryButtonText}</a>' + '<a class="qq-upload-delete" href="#">{deleteButtonText}</a>' + '<span class="qq-upload-status-text">{statusText}</span>' + '</li>', classes: { button: 'qq-upload-button', drop: 'qq-upload-drop-area', dropActive: 'qq-upload-drop-area-active', dropDisabled: 'qq-upload-drop-area-disabled', list: 'qq-upload-list', progressBar: 'qq-progress-bar', file: 'qq-upload-file', spinner: 'qq-upload-spinner', finished: 'qq-upload-finished', retrying: 'qq-upload-retrying', retryable: 'qq-upload-retryable', size: 'qq-upload-size', cancel: 'qq-upload-cancel', deleteButton: 'qq-upload-delete', retry: 'qq-upload-retry', statusText: 'qq-upload-status-text', success: 'qq-upload-success', fail: 'qq-upload-fail', successIcon: null, failIcon: null, dropProcessing: 'qq-drop-processing', dropProcessingSpinner: 'qq-drop-processing-spinner' }, failedUploadTextDisplay: { mode: 'default', //default, custom, or none maxChars: 50, responseProperty: 'error', enableTooltip: true }, messages: { tooManyFilesError: "You may only drop one file" }, retry: { showAutoRetryNote: true, autoRetryNote: "Retrying {retryNum}/{maxAuto}...", showButton: false }, deleteFile: { forceConfirm: false, confirmMessage: "Are you sure you want to delete {filename}?", deletingStatusText: "Deleting...", deletingFailedText: "Delete failed" }, display: { fileSizeOnSubmit: false }, showMessage: function(message){ setTimeout(function() { alert(message); }, 0); }, showConfirm: function(message, okCallback, cancelCallback) { setTimeout(function() { var result = confirm(message); if (result) { okCallback(); } else if (cancelCallback) { cancelCallback(); } }, 0); } }, true); // overwrite options with user supplied qq.extend(this._options, o, true); this._wrapCallbacks(); // overwrite the upload button text if any // same for the Cancel button and Fail message text this._options.template = this._options.template.replace(/\{dragZoneText\}/g, this._options.text.dragZone); this._options.template = this._options.template.replace(/\{uploadButtonText\}/g, this._options.text.uploadButton); this._options.template = this._options.template.replace(/\{dropProcessingText\}/g, this._options.text.dropProcessing); this._options.fileTemplate = this._options.fileTemplate.replace(/\{cancelButtonText\}/g, this._options.text.cancelButton); this._options.fileTemplate = this._options.fileTemplate.replace(/\{retryButtonText\}/g, this._options.text.retryButton); this._options.fileTemplate = this._options.fileTemplate.replace(/\{deleteButtonText\}/g, this._options.text.deleteButton); this._options.fileTemplate = this._options.fileTemplate.replace(/\{statusText\}/g, ""); this._element = this._options.element; this._element.innerHTML = this._options.template; this._listElement = this._options.listElement || this._find(this._element, 'list'); this._classes = this._options.classes; if (!this._button) { this._button = this._createUploadButton(this._find(this._element, 'button')); } this._bindCancelAndRetryEvents(); this._dnd = this._setupDragAndDrop(); }; // inherit from Basic Uploader qq.extend(qq.FineUploader.prototype, qq.FineUploaderBasic.prototype); qq.extend(qq.FineUploader.prototype, { clearStoredFiles: function() { qq.FineUploaderBasic.prototype.clearStoredFiles.apply(this, arguments); this._listElement.innerHTML = ""; }, addExtraDropzone: function(element){ this._dnd.setupExtraDropzone(element); }, removeExtraDropzone: function(element){ return this._dnd.removeExtraDropzone(element); }, getItemByFileId: function(id){ var item = this._listElement.firstChild; // there can't be txt nodes in dynamically created list // and we can use nextSibling while (item){ if (item.qqFileId == id) return item; item = item.nextSibling; } }, reset: function() { qq.FineUploaderBasic.prototype.reset.apply(this, arguments); this._element.innerHTML = this._options.template; this._listElement = this._options.listElement || this._find(this._element, 'list'); if (!this._options.button) { this._button = this._createUploadButton(this._find(this._element, 'button')); } this._bindCancelAndRetryEvents(); this._dnd.dispose(); this._dnd = this._setupDragAndDrop(); }, _removeFileItem: function(fileId) { var item = this.getItemByFileId(fileId); qq(item).remove(); }, _setupDragAndDrop: function() { var self = this, dropProcessingEl = this._find(this._element, 'dropProcessing'), dnd, preventSelectFiles, defaultDropAreaEl; preventSelectFiles = function(event) { event.preventDefault(); }; if (!this._options.dragAndDrop.disableDefaultDropzone) { defaultDropAreaEl = this._find(this._options.element, 'drop'); } dnd = new qq.DragAndDrop({ dropArea: defaultDropAreaEl, extraDropzones: this._options.dragAndDrop.extraDropzones, hideDropzones: this._options.dragAndDrop.hideDropzones, multiple: this._options.multiple, classes: { dropActive: this._options.classes.dropActive }, callbacks: { dropProcessing: function(isProcessing, files) { var input = self._button.getInput(); if (isProcessing) { qq(dropProcessingEl).css({display: 'block'}); qq(input).attach('click', preventSelectFiles); } else { qq(dropProcessingEl).hide(); qq(input).detach('click', preventSelectFiles); } if (files) { self.addFiles(files); } }, error: function(code, filename) { self._error(code, filename); }, log: function(message, level) { self.log(message, level); } } }); dnd.setup(); return dnd; }, _leaving_document_out: function(e){ return ((qq.chrome() || (qq.safari() && qq.windows())) && e.clientX == 0 && e.clientY == 0) // null coords for Chrome and Safari Windows || (qq.firefox() && !e.relatedTarget); // null e.relatedTarget for Firefox }, _storeForLater: function(id) { qq.FineUploaderBasic.prototype._storeForLater.apply(this, arguments); var item = this.getItemByFileId(id); qq(this._find(item, 'spinner')).hide(); }, /** * Gets one of the elements listed in this._options.classes **/ _find: function(parent, type){ var element = qq(parent).getByClass(this._options.classes[type])[0]; if (!element){ throw new Error('element not found ' + type); } return element; }, _onSubmit: function(id, name){ qq.FineUploaderBasic.prototype._onSubmit.apply(this, arguments); this._addToList(id, name); }, // Update the progress bar & percentage as the file is uploaded _onProgress: function(id, name, loaded, total){ qq.FineUploaderBasic.prototype._onProgress.apply(this, arguments); var item, progressBar, percent, cancelLink; item = this.getItemByFileId(id); progressBar = this._find(item, 'progressBar'); percent = Math.round(loaded / total * 100); if (loaded === total) { cancelLink = this._find(item, 'cancel'); qq(cancelLink).hide(); qq(progressBar).hide(); qq(this._find(item, 'statusText')).setText(this._options.text.waitingForResponse); // If last byte was sent, display total file size this._displayFileSize(id); } else { // If still uploading, display percentage - total size is actually the total request(s) size this._displayFileSize(id, loaded, total); qq(progressBar).css({display: 'block'}); } // Update progress bar element qq(progressBar).css({width: percent + '%'}); }, _onComplete: function(id, name, result, xhr){ qq.FineUploaderBasic.prototype._onComplete.apply(this, arguments); var item = this.getItemByFileId(id); qq(this._find(item, 'statusText')).clearText(); qq(item).removeClass(this._classes.retrying); qq(this._find(item, 'progressBar')).hide(); if (!this._options.disableCancelForFormUploads || qq.isXhrUploadSupported()) { qq(this._find(item, 'cancel')).hide(); } qq(this._find(item, 'spinner')).hide(); if (result.success) { if (this._isDeletePossible()) { this._showDeleteLink(id); } qq(item).addClass(this._classes.success); if (this._classes.successIcon) { this._find(item, 'finished').style.display = "inline-block"; qq(item).addClass(this._classes.successIcon); } } else { qq(item).addClass(this._classes.fail); if (this._classes.failIcon) { this._find(item, 'finished').style.display = "inline-block"; qq(item).addClass(this._classes.failIcon); } if (this._options.retry.showButton && !this._preventRetries[id]) { qq(item).addClass(this._classes.retryable); } this._controlFailureTextDisplay(item, result); } }, _onUpload: function(id, name){ qq.FineUploaderBasic.prototype._onUpload.apply(this, arguments); this._showSpinner(id); }, _onCancel: function(id, name) { qq.FineUploaderBasic.prototype._onCancel.apply(this, arguments); this._removeFileItem(id); }, _onBeforeAutoRetry: function(id) { var item, progressBar, failTextEl, retryNumForDisplay, maxAuto, retryNote; qq.FineUploaderBasic.prototype._onBeforeAutoRetry.apply(this, arguments); item = this.getItemByFileId(id); progressBar = this._find(item, 'progressBar'); this._showCancelLink(item); progressBar.style.width = 0; qq(progressBar).hide(); if (this._options.retry.showAutoRetryNote) { failTextEl = this._find(item, 'statusText'); retryNumForDisplay = this._autoRetries[id] + 1; maxAuto = this._options.retry.maxAutoAttempts; retryNote = this._options.retry.autoRetryNote.replace(/\{retryNum\}/g, retryNumForDisplay); retryNote = retryNote.replace(/\{maxAuto\}/g, maxAuto); qq(failTextEl).setText(retryNote); if (retryNumForDisplay === 1) { qq(item).addClass(this._classes.retrying); } } }, //return false if we should not attempt the requested retry _onBeforeManualRetry: function(id) { if (qq.FineUploaderBasic.prototype._onBeforeManualRetry.apply(this, arguments)) { var item = this.getItemByFileId(id); this._find(item, 'progressBar').style.width = 0; qq(item).removeClass(this._classes.fail); qq(this._find(item, 'statusText')).clearText(); this._showSpinner(id); this._showCancelLink(item); return true; } return false; }, _onSubmitDelete: function(id) { if (this._isDeletePossible()) { if (this._options.callbacks.onSubmitDelete(id) !== false) { if (this._options.deleteFile.forceConfirm) { this._showDeleteConfirm(id); } else { this._sendDeleteRequest(id); } } } else { this.log("Delete request ignored for file ID " + id + ", delete feature is disabled.", "warn"); return false; } }, _onDeleteComplete: function(id, xhr, isError) { qq.FineUploaderBasic.prototype._onDeleteComplete.apply(this, arguments); var item = this.getItemByFileId(id), spinnerEl = this._find(item, 'spinner'), statusTextEl = this._find(item, 'statusText'); qq(spinnerEl).hide(); if (isError) { qq(statusTextEl).setText(this._options.deleteFile.deletingFailedText); this._showDeleteLink(id); } else { this._removeFileItem(id); } }, _sendDeleteRequest: function(id) { var item = this.getItemByFileId(id), deleteLink = this._find(item, 'deleteButton'), statusTextEl = this._find(item, 'statusText'); qq(deleteLink).hide(); this._showSpinner(id); qq(statusTextEl).setText(this._options.deleteFile.deletingStatusText); this._deleteHandler.sendDelete(id, this.getUuid(id)); }, _showDeleteConfirm: function(id) { var fileName = this._handler.getName(id), confirmMessage = this._options.deleteFile.confirmMessage.replace(/\{filename\}/g, fileName), uuid = this.getUuid(id), self = this; this._options.showConfirm(confirmMessage, function() { self._sendDeleteRequest(id); }); }, _addToList: function(id, name){ var item = qq.toElement(this._options.fileTemplate); if (this._options.disableCancelForFormUploads && !qq.isXhrUploadSupported()) { var cancelLink = this._find(item, 'cancel'); qq(cancelLink).remove(); } item.qqFileId = id; var fileElement = this._find(item, 'file'); qq(fileElement).setText(this._options.formatFileName(name)); qq(this._find(item, 'size')).hide(); if (!this._options.multiple) { this._handler.cancelAll(); this._clearList(); } this._listElement.appendChild(item); if (this._options.display.fileSizeOnSubmit && qq.isXhrUploadSupported()) { this._displayFileSize(id); } }, _clearList: function(){ this._listElement.innerHTML = ''; this.clearStoredFiles(); }, _displayFileSize: function(id, loadedSize, totalSize) { var item = this.getItemByFileId(id), size = this.getSize(id), sizeForDisplay = this._formatSize(size), sizeEl = this._find(item, 'size'); if (loadedSize !== undefined && totalSize !== undefined) { sizeForDisplay = this._formatProgress(loadedSize, totalSize); } qq(sizeEl).css({display: 'inline'}); qq(sizeEl).setText(sizeForDisplay); }, /** * delegate click event for cancel & retry links **/ _bindCancelAndRetryEvents: function(){ var self = this, list = this._listElement; this._disposeSupport.attach(list, 'click', function(e){ e = e || window.event; var target = e.target || e.srcElement; if (qq(target).hasClass(self._classes.cancel) || qq(target).hasClass(self._classes.retry) || qq(target).hasClass(self._classes.deleteButton)){ qq.preventDefault(e); var item = target.parentNode; while(item.qqFileId === undefined) { item = target = target.parentNode; } if (qq(target).hasClass(self._classes.deleteButton)) { self.deleteFile(item.qqFileId); } else if (qq(target).hasClass(self._classes.cancel)) { self.cancel(item.qqFileId); } else { qq(item).removeClass(self._classes.retryable); self.retry(item.qqFileId); } } }); }, _formatProgress: function (uploadedSize, totalSize) { var message = this._options.text.formatProgress; function r(name, replacement) { message = message.replace(name, replacement); } r('{percent}', Math.round(uploadedSize / totalSize * 100)); r('{total_size}', this._formatSize(totalSize)); return message; }, _controlFailureTextDisplay: function(item, response) { var mode, maxChars, responseProperty, failureReason, shortFailureReason; mode = this._options.failedUploadTextDisplay.mode; maxChars = this._options.failedUploadTextDisplay.maxChars; responseProperty = this._options.failedUploadTextDisplay.responseProperty; if (mode === 'custom') { failureReason = response[responseProperty]; if (failureReason) { if (failureReason.length > maxChars) { shortFailureReason = failureReason.substring(0, maxChars) + '...'; } } else { failureReason = this._options.text.failUpload; this.log("'" + responseProperty + "' is not a valid property on the server response.", 'warn'); } qq(this._find(item, 'statusText')).setText(shortFailureReason || failureReason); if (this._options.failedUploadTextDisplay.enableTooltip) { this._showTooltip(item, failureReason); } } else if (mode === 'default') { qq(this._find(item, 'statusText')).setText(this._options.text.failUpload); } else if (mode !== 'none') { this.log("failedUploadTextDisplay.mode value of '" + mode + "' is not valid", 'warn'); } }, _showTooltip: function(item, text) { item.title = text; }, _showSpinner: function(id) { var item = this.getItemByFileId(id), spinnerEl = this._find(item, 'spinner'); spinnerEl.style.display = "inline-block"; }, _showCancelLink: function(item) { if (!this._options.disableCancelForFormUploads || qq.isXhrUploadSupported()) { var cancelLink = this._find(item, 'cancel'); qq(cancelLink).css({display: 'inline'}); } }, _showDeleteLink: function(id) { var item = this.getItemByFileId(id), deleteLink = this._find(item, 'deleteButton'); qq(deleteLink).css({display: 'inline'}); }, _error: function(code, name){ var message = qq.FineUploaderBasic.prototype._error.apply(this, arguments); this._options.showMessage(message); } }); /** Generic class for sending non-upload ajax requests and handling the associated responses **/ //TODO Use XDomainRequest if expectCors = true. Not necessary now since only DELETE requests are sent and XDR doesn't support pre-flighting. /*globals qq, XMLHttpRequest*/ qq.AjaxRequestor = function(o) { "use strict"; var log, shouldParamsBeInQueryString, queue = [], requestState = [], options = { method: 'POST', maxConnections: 3, customHeaders: {}, endpointStore: {}, paramsStore: {}, successfulResponseCodes: [200], demoMode: false, cors: { expected: false, sendCredentials: false }, log: function(str, level) {}, onSend: function(id) {}, onComplete: function(id, xhr, isError) {}, onCancel: function(id) {} }; qq.extend(options, o); log = options.log; shouldParamsBeInQueryString = getMethod() === 'GET' || getMethod() === 'DELETE'; /** * Removes element from queue, sends next request */ function dequeue(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; delete requestState[id]; queue.splice(i, 1); if (queue.length >= max && i < max){ nextId = queue[max-1]; sendRequest(nextId); } } function onComplete(id) { var xhr = requestState[id].xhr, method = getMethod(), isError = false; dequeue(id); if (!isResponseSuccessful(xhr.status)) { isError = true; log(method + " request for " + id + " has failed - response code " + xhr.status, "error"); } options.onComplete(id, xhr, isError); } function sendRequest(id) { var xhr = new XMLHttpRequest(), method = getMethod(), params = {}, url; options.onSend(id); if (options.paramsStore.getParams) { params = options.paramsStore.getParams(id); } url = createUrl(id, params); requestState[id].xhr = xhr; xhr.onreadystatechange = getReadyStateChangeHandler(id); xhr.open(method, url, true); if (options.cors.expected && options.cors.sendCredentials) { xhr.withCredentials = true; } setHeaders(id); log('Sending ' + method + " request for " + id); if (!shouldParamsBeInQueryString && params) { xhr.send(qq.obj2url(params, "")); } else { xhr.send(); } } function createUrl(id, params) { var endpoint = options.endpointStore.getEndpoint(id), addToPath = requestState[id].addToPath; if (addToPath !== undefined) { endpoint += "/" + addToPath; } if (shouldParamsBeInQueryString && params) { return qq.obj2url(params, endpoint); } else { return endpoint; } } function getReadyStateChangeHandler(id) { var xhr = requestState[id].xhr; return function() { if (xhr.readyState === 4) { onComplete(id, xhr); } }; } function setHeaders(id) { var xhr = requestState[id].xhr, customHeaders = options.customHeaders; xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Cache-Control", "no-cache"); qq.each(customHeaders, function(name, val) { xhr.setRequestHeader(name, val); }); } function cancelRequest(id) { var xhr = requestState[id].xhr, method = getMethod(); if (xhr) { xhr.onreadystatechange = null; xhr.abort(); dequeue(id); log('Cancelled ' + method + " for " + id); options.onCancel(id); return true; } return false; } function isResponseSuccessful(responseCode) { return qq.indexOf(options.successfulResponseCodes, responseCode) >= 0; } function getMethod() { if (options.demoMode) { return "GET"; } return options.method; } return { send: function(id, addToPath) { requestState[id] = { addToPath: addToPath }; var len = queue.push(id); // if too many active connections, wait... if (len <= options.maxConnections){ sendRequest(id); } }, cancel: function(id) { return cancelRequest(id); } }; }; /** Generic class for sending non-upload ajax requests and handling the associated responses **/ /*globals qq, XMLHttpRequest*/ qq.DeleteFileAjaxRequestor = function(o) { "use strict"; var requestor, options = { endpointStore: {}, maxConnections: 3, customHeaders: {}, paramsStore: {}, demoMode: false, cors: { expected: false, sendCredentials: false }, log: function(str, level) {}, onDelete: function(id) {}, onDeleteComplete: function(id, xhr, isError) {} }; qq.extend(options, o); requestor = new qq.AjaxRequestor({ method: 'DELETE', endpointStore: options.endpointStore, paramsStore: options.paramsStore, maxConnections: options.maxConnections, customHeaders: options.customHeaders, successfulResponseCodes: [200, 202, 204], demoMode: options.demoMode, log: options.log, onSend: options.onDelete, onComplete: options.onDeleteComplete }); return { sendDelete: function(id, uuid) { requestor.send(id, uuid); options.log("Submitted delete file request for " + id); } }; }; qq.WindowReceiveMessage = function(o) { var options = { log: function(message, level) {} }, callbackWrapperDetachers = {}; qq.extend(options, o); return { receiveMessage : function(id, callback) { var onMessageCallbackWrapper = function(event) { callback(event.data); }; if (window.postMessage) { callbackWrapperDetachers[id] = qq(window).attach("message", onMessageCallbackWrapper); } else { log("iframe message passing not supported in this browser!", "error"); } }, stopReceivingMessages : function(id) { if (window.postMessage) { var detacher = callbackWrapperDetachers[id]; if (detacher) { detacher(); } } } }; }; /** * Class for uploading files, uploading itself is handled by child classes */ /*globals qq*/ qq.UploadHandler = function(o) { "use strict"; var queue = [], options, log, dequeue, handlerImpl; // Default options, can be overridden by the user options = { debug: false, forceMultipart: true, paramsInBody: false, paramsStore: {}, endpointStore: {}, cors: { expected: false, sendCredentials: false }, maxConnections: 3, // maximum number of concurrent uploads uuidParamName: 'qquuid', totalFileSizeParamName: 'qqtotalfilesize', chunking: { enabled: false, partSize: 2000000, //bytes paramNames: { partIndex: 'qqpartindex', partByteOffset: 'qqpartbyteoffset', chunkSize: 'qqchunksize', totalParts: 'qqtotalparts', filename: 'qqfilename' } }, resume: { enabled: false, id: null, cookiesExpireIn: 7, //days paramNames: { resuming: "qqresume" } }, blobs: { paramNames: { name: 'qqblobname' } }, log: function(str, level) {}, onProgress: function(id, fileName, loaded, total){}, onComplete: function(id, fileName, response, xhr){}, onCancel: function(id, fileName){}, onUpload: function(id, fileName){}, onUploadChunk: function(id, fileName, chunkData){}, onAutoRetry: function(id, fileName, response, xhr){}, onResume: function(id, fileName, chunkData){} }; qq.extend(options, o); log = options.log; /** * Removes element from queue, starts upload of next */ dequeue = function(id) { var i = qq.indexOf(queue, id), max = options.maxConnections, nextId; if (i >= 0) { queue.splice(i, 1); if (queue.length >= max && i < max){ nextId = queue[max-1]; handlerImpl.upload(nextId); } } }; if (qq.isXhrUploadSupported()) { handlerImpl = new qq.UploadHandlerXhr(options, dequeue, log); } else { handlerImpl = new qq.UploadHandlerForm(options, dequeue, log); } return { /** * Adds file or file input to the queue * @returns id **/ add: function(file){ return handlerImpl.add(file); }, /** * Sends the file identified by id */ upload: function(id){ var len = queue.push(id); // if too many active uploads, wait... if (len <= options.maxConnections){ return handlerImpl.upload(id); } }, retry: function(id) { var i = qq.indexOf(queue, id); if (i >= 0) { return handlerImpl.upload(id, true); } else { return this.upload(id); } }, /** * Cancels file upload by id */ cancel: function(id) { log('Cancelling ' + id); options.paramsStore.remove(id); handlerImpl.cancel(id); dequeue(id); }, /** * Cancels all queued or in-progress uploads */ cancelAll: function() { var self = this, queueCopy = []; qq.extend(queueCopy, queue); qq.each(queueCopy, function(idx, fileId) { self.cancel(fileId); }); queue = []; }, /** * Returns name of the file identified by id */ getName: function(id){ return handlerImpl.getName(id); }, /** * Returns size of the file identified by id */ getSize: function(id){ if (handlerImpl.getSize) { return handlerImpl.getSize(id); } }, getFile: function(id) { if (handlerImpl.getFile) { return handlerImpl.getFile(id); } }, /** * Returns id of files being uploaded or * waiting for their turn */ getQueue: function(){ return queue; }, reset: function() { log('Resetting upload handler'); queue = []; handlerImpl.reset(); }, getUuid: function(id) { return handlerImpl.getUuid(id); }, /** * Determine if the file exists. */ isValid: function(id) { return handlerImpl.isValid(id); }, getResumableFilesData: function() { if (handlerImpl.getResumableFilesData) { return handlerImpl.getResumableFilesData(); } return []; } }; }; /*globals qq, document, setTimeout*/ /*globals clearTimeout*/ qq.UploadHandlerForm = function(o, uploadCompleteCallback, logCallback) { "use strict"; var options = o, inputs = [], uuids = [], detachLoadEvents = {}, postMessageCallbackTimers = {}, uploadComplete = uploadCompleteCallback, log = logCallback, corsMessageReceiver = new qq.WindowReceiveMessage({log: log}), onloadCallbacks = {}, api; function detachLoadEvent(id) { if (detachLoadEvents[id] !== undefined) { detachLoadEvents[id](); delete detachLoadEvents[id]; } } function registerPostMessageCallback(iframe, callback) { var id = iframe.id; onloadCallbacks[uuids[id]] = callback; detachLoadEvents[id] = qq(iframe).attach('load', function() { if (inputs[id]) { log("Received iframe load event for CORS upload request (file id " + id + ")"); postMessageCallbackTimers[id] = setTimeout(function() { var errorMessage = "No valid message received from loaded iframe for file id " + id; log(errorMessage, "error"); callback({ error: errorMessage }); }, 1000); } }); corsMessageReceiver.receiveMessage(id, function(message) { log("Received the following window message: '" + message + "'"); var response = qq.parseJson(message), uuid = response.uuid, onloadCallback; if (uuid && onloadCallbacks[uuid]) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; detachLoadEvent(id); onloadCallback = onloadCallbacks[uuid]; delete onloadCallbacks[uuid]; corsMessageReceiver.stopReceivingMessages(id); onloadCallback(response); } else if (!uuid) { log("'" + message + "' does not contain a UUID - ignoring."); } }); } function attachLoadEvent(iframe, callback) { /*jslint eqeq: true*/ if (options.cors.expected) { registerPostMessageCallback(iframe, callback); } else { detachLoadEvents[iframe.id] = qq(iframe).attach('load', function(){ log('Received response for ' + iframe.id); // when we remove iframe from dom // the request stops, but in IE load // event fires if (!iframe.parentNode){ return; } try { // fixing Opera 10.53 if (iframe.contentDocument && iframe.contentDocument.body && iframe.contentDocument.body.innerHTML == "false"){ // In Opera event is fired second time // when body.innerHTML changed from false // to server response approx. after 1 sec // when we upload file with iframe return; } } catch (error) { //IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases log('Error when attempting to access iframe during handling of upload response (' + error + ")", 'error'); } callback(); }); } } /** * Returns json object received by iframe from server. */ function getIframeContentJson(iframe) { /*jshint evil: true*/ var response; //IE may throw an "access is denied" error when attempting to access contentDocument on the iframe in some cases try { // iframe.contentWindow.document - for IE<7 var doc = iframe.contentDocument || iframe.contentWindow.document, innerHTML = doc.body.innerHTML; log("converting iframe's innerHTML to JSON"); log("innerHTML = " + innerHTML); //plain text response may be wrapped in <pre> tag if (innerHTML && innerHTML.match(/^<pre/i)) { innerHTML = doc.body.firstChild.firstChild.nodeValue; } response = qq.parseJson(innerHTML); } catch(error){ log('Error when attempting to parse form upload response (' + error + ")", 'error'); response = {success: false}; } return response; } /** * Creates iframe with unique name */ function createIframe(id){ // We can't use following code as the name attribute // won't be properly registered in IE6, and new window // on form submit will open // var iframe = document.createElement('iframe'); // iframe.setAttribute('name', id); var iframe = qq.toElement('<iframe src="javascript:false;" name="' + id + '" />'); iframe.setAttribute('id', id); iframe.style.display = 'none'; document.body.appendChild(iframe); return iframe; } /** * Creates form, that will be submitted to iframe */ function createForm(id, iframe){ var params = options.paramsStore.getParams(id), protocol = options.demoMode ? "GET" : "POST", form = qq.toElement('<form method="' + protocol + '" enctype="multipart/form-data"></form>'), endpoint = options.endpointStore.getEndpoint(id), url = endpoint; params[options.uuidParamName] = uuids[id]; if (!options.paramsInBody) { url = qq.obj2url(params, endpoint); } else { qq.obj2Inputs(params, form); } form.setAttribute('action', url); form.setAttribute('target', iframe.name); form.style.display = 'none'; document.body.appendChild(form); return form; } api = { add: function(fileInput) { fileInput.setAttribute('name', options.inputName); var id = inputs.push(fileInput) - 1; uuids[id] = qq.getUniqueId(); // remove file input from DOM if (fileInput.parentNode){ qq(fileInput).remove(); } return id; }, getName: function(id) { /*jslint regexp: true*/ // get input value and remove path to normalize return inputs[id].value.replace(/.*(\/|\\)/, ""); }, isValid: function(id) { return inputs[id] !== undefined; }, reset: function() { qq.UploadHandler.prototype.reset.apply(this, arguments); inputs = []; uuids = []; detachLoadEvents = {}; }, getUuid: function(id) { return uuids[id]; }, cancel: function(id) { options.onCancel(id, this.getName(id)); delete inputs[id]; delete uuids[id]; delete detachLoadEvents[id]; if (options.cors.expected) { clearTimeout(postMessageCallbackTimers[id]); delete postMessageCallbackTimers[id]; corsMessageReceiver.stopReceivingMessages(id); } var iframe = document.getElementById(id); if (iframe) { // to cancel request set src to something else // we use src="javascript:false;" because it doesn't // trigger ie6 prompt on https iframe.setAttribute('src', 'java' + String.fromCharCode(115) + 'cript:false;'); //deal with "JSLint: javascript URL" warning, which apparently cannot be turned off qq(iframe).remove(); } }, upload: function(id){ var input = inputs[id], fileName = api.getName(id), iframe = createIframe(id), form; if (!input){ throw new Error('file with passed id was not added, or already uploaded or cancelled'); } options.onUpload(id, this.getName(id)); form = createForm(id, iframe); form.appendChild(input); attachLoadEvent(iframe, function(responseFromMessage){ log('iframe loaded'); var response = responseFromMessage ? responseFromMessage : getIframeContentJson(iframe); detachLoadEvent(id); //we can't remove an iframe if the iframe doesn't belong to the same domain if (!options.cors.expected) { qq(iframe).remove(); } if (!response.success) { if (options.onAutoRetry(id, fileName, response)) { return; } } options.onComplete(id, fileName, response); uploadComplete(id); }); log('Sending upload request for ' + id); form.submit(); qq(form).remove(); return id; } }; return api; }; /*globals qq, File, XMLHttpRequest, FormData, Blob*/ qq.UploadHandlerXhr = function(o, uploadCompleteCallback, logCallback) { "use strict"; var options = o, uploadComplete = uploadCompleteCallback, log = logCallback, fileState = [], cookieItemDelimiter = "|", chunkFiles = options.chunking.enabled && qq.isFileChunkingSupported(), resumeEnabled = options.resume.enabled && chunkFiles && qq.areCookiesEnabled(), resumeId = getResumeId(), multipart = options.forceMultipart || options.paramsInBody, api; function addChunkingSpecificParams(id, params, chunkData) { var size = api.getSize(id), name = api.getName(id); params[options.chunking.paramNames.partIndex] = chunkData.part; params[options.chunking.paramNames.partByteOffset] = chunkData.start; params[options.chunking.paramNames.chunkSize] = chunkData.size; params[options.chunking.paramNames.totalParts] = chunkData.count; params[options.totalFileSizeParamName] = size; /** * When a Blob is sent in a multipart request, the filename value in the content-disposition header is either "blob" * or an empty string. So, we will need to include the actual file name as a param in this case. */ if (multipart) { params[options.chunking.paramNames.filename] = name; } } function addResumeSpecificParams(params) { params[options.resume.paramNames.resuming] = true; } function getChunk(fileOrBlob, startByte, endByte) { if (fileOrBlob.slice) { return fileOrBlob.slice(startByte, endByte); } else if (fileOrBlob.mozSlice) { return fileOrBlob.mozSlice(startByte, endByte); } else if (fileOrBlob.webkitSlice) { return fileOrBlob.webkitSlice(startByte, endByte); } } function getChunkData(id, chunkIndex) { var chunkSize = options.chunking.partSize, fileSize = api.getSize(id), fileOrBlob = fileState[id].file || fileState[id].blobData.blob, startBytes = chunkSize * chunkIndex, endBytes = startBytes+chunkSize >= fileSize ? fileSize : startBytes+chunkSize, totalChunks = getTotalChunks(id); return { part: chunkIndex, start: startBytes, end: endBytes, count: totalChunks, blob: getChunk(fileOrBlob, startBytes, endBytes), size: endBytes - startBytes }; } function getTotalChunks(id) { var fileSize = api.getSize(id), chunkSize = options.chunking.partSize; return Math.ceil(fileSize / chunkSize); } function createXhr(id) { var xhr = new XMLHttpRequest(); fileState[id].xhr = xhr; return xhr; } function setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id) { var formData = new FormData(), method = options.demoMode ? "GET" : "POST", endpoint = options.endpointStore.getEndpoint(id), url = endpoint, name = api.getName(id), size = api.getSize(id), blobData = fileState[id].blobData; params[options.uuidParamName] = fileState[id].uuid; if (multipart) { params[options.totalFileSizeParamName] = size; if (blobData) { /** * When a Blob is sent in a multipart request, the filename value in the content-disposition header is either "blob" * or an empty string. So, we will need to include the actual file name as a param in this case. */ params[options.blobs.paramNames.name] = blobData.name; } } //build query string if (!options.paramsInBody) { if (!multipart) { params[options.inputName] = name; } url = qq.obj2url(params, endpoint); } xhr.open(method, url, true); if (options.cors.expected && options.cors.sendCredentials) { xhr.withCredentials = true; } if (multipart) { if (options.paramsInBody) { qq.obj2FormData(params, formData); } formData.append(options.inputName, fileOrBlob); return formData; } return fileOrBlob; } function setHeaders(id, xhr) { var extraHeaders = options.customHeaders, fileOrBlob = fileState[id].file || fileState[id].blobData.blob; xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest"); xhr.setRequestHeader("Cache-Control", "no-cache"); if (!multipart) { xhr.setRequestHeader("Content-Type", "application/octet-stream"); //NOTE: return mime type in xhr works on chrome 16.0.9 firefox 11.0a2 xhr.setRequestHeader("X-Mime-Type", fileOrBlob.type); } qq.each(extraHeaders, function(name, val) { xhr.setRequestHeader(name, val); }); } function handleCompletedItem(id, response, xhr) { var name = api.getName(id), size = api.getSize(id); fileState[id].attemptingResume = false; options.onProgress(id, name, size, size); options.onComplete(id, name, response, xhr); delete fileState[id].xhr; uploadComplete(id); } function uploadNextChunk(id) { var chunkIdx = fileState[id].remainingChunkIdxs[0], chunkData = getChunkData(id, chunkIdx), xhr = createXhr(id), size = api.getSize(id), name = api.getName(id), toSend, params; if (fileState[id].loaded === undefined) { fileState[id].loaded = 0; } if (resumeEnabled && fileState[id].file) { persistChunkData(id, chunkData); } xhr.onreadystatechange = getReadyStateChangeHandler(id, xhr); xhr.upload.onprogress = function(e) { if (e.lengthComputable) { var totalLoaded = e.loaded + fileState[id].loaded, estTotalRequestsSize = calcAllRequestsSizeForChunkedUpload(id, chunkIdx, e.total); options.onProgress(id, name, totalLoaded, estTotalRequestsSize); } }; options.onUploadChunk(id, name, getChunkDataForCallback(chunkData)); params = options.paramsStore.getParams(id); addChunkingSpecificParams(id, params, chunkData); if (fileState[id].attemptingResume) { addResumeSpecificParams(params); } toSend = setParamsAndGetEntityToSend(params, xhr, chunkData.blob, id); setHeaders(id, xhr); log('Sending chunked upload request for item ' + id + ": bytes " + (chunkData.start+1) + "-" + chunkData.end + " of " + size); xhr.send(toSend); } function calcAllRequestsSizeForChunkedUpload(id, chunkIdx, requestSize) { var chunkData = getChunkData(id, chunkIdx), blobSize = chunkData.size, overhead = requestSize - blobSize, size = api.getSize(id), chunkCount = chunkData.count, initialRequestOverhead = fileState[id].initialRequestOverhead, overheadDiff = overhead - initialRequestOverhead; fileState[id].lastRequestOverhead = overhead; if (chunkIdx === 0) { fileState[id].lastChunkIdxProgress = 0; fileState[id].initialRequestOverhead = overhead; fileState[id].estTotalRequestsSize = size + (chunkCount * overhead); } else if (fileState[id].lastChunkIdxProgress !== chunkIdx) { fileState[id].lastChunkIdxProgress = chunkIdx; fileState[id].estTotalRequestsSize += overheadDiff; } return fileState[id].estTotalRequestsSize; } function getLastRequestOverhead(id) { if (multipart) { return fileState[id].lastRequestOverhead; } else { return 0; } } function handleSuccessfullyCompletedChunk(id, response, xhr) { var chunkIdx = fileState[id].remainingChunkIdxs.shift(), chunkData = getChunkData(id, chunkIdx); fileState[id].attemptingResume = false; fileState[id].loaded += chunkData.size + getLastRequestOverhead(id); if (fileState[id].remainingChunkIdxs.length > 0) { uploadNextChunk(id); } else { if (resumeEnabled) { deletePersistedChunkData(id); } handleCompletedItem(id, response, xhr); } } function isErrorResponse(xhr, response) { return xhr.status !== 200 || !response.success || response.reset; } function parseResponse(xhr) { var response; try { response = qq.parseJson(xhr.responseText); } catch(error) { log('Error when attempting to parse xhr response text (' + error + ')', 'error'); response = {}; } return response; } function handleResetResponse(id) { log('Server has ordered chunking effort to be restarted on next attempt for item ID ' + id, 'error'); if (resumeEnabled) { deletePersistedChunkData(id); fileState[id].attemptingResume = false; } fileState[id].remainingChunkIdxs = []; delete fileState[id].loaded; delete fileState[id].estTotalRequestsSize; delete fileState[id].initialRequestOverhead; } function handleResetResponseOnResumeAttempt(id) { fileState[id].attemptingResume = false; log("Server has declared that it cannot handle resume for item ID " + id + " - starting from the first chunk", 'error'); handleResetResponse(id); api.upload(id, true); } function handleNonResetErrorResponse(id, response, xhr) { var name = api.getName(id); if (options.onAutoRetry(id, name, response, xhr)) { return; } else { handleCompletedItem(id, response, xhr); } } function onComplete(id, xhr) { var response; // the request was aborted/cancelled if (!fileState[id]) { return; } log("xhr - server response received for " + id); log("responseText = " + xhr.responseText); response = parseResponse(xhr); if (isErrorResponse(xhr, response)) { if (response.reset) { handleResetResponse(id); } if (fileState[id].attemptingResume && response.reset) { handleResetResponseOnResumeAttempt(id); } else { handleNonResetErrorResponse(id, response, xhr); } } else if (chunkFiles) { handleSuccessfullyCompletedChunk(id, response, xhr); } else { handleCompletedItem(id, response, xhr); } } function getChunkDataForCallback(chunkData) { return { partIndex: chunkData.part, startByte: chunkData.start + 1, endByte: chunkData.end, totalParts: chunkData.count }; } function getReadyStateChangeHandler(id, xhr) { return function() { if (xhr.readyState === 4) { onComplete(id, xhr); } }; } function persistChunkData(id, chunkData) { var fileUuid = api.getUuid(id), lastByteSent = fileState[id].loaded, initialRequestOverhead = fileState[id].initialRequestOverhead, estTotalRequestsSize = fileState[id].estTotalRequestsSize, cookieName = getChunkDataCookieName(id), cookieValue = fileUuid + cookieItemDelimiter + chunkData.part + cookieItemDelimiter + lastByteSent + cookieItemDelimiter + initialRequestOverhead + cookieItemDelimiter + estTotalRequestsSize, cookieExpDays = options.resume.cookiesExpireIn; qq.setCookie(cookieName, cookieValue, cookieExpDays); } function deletePersistedChunkData(id) { if (fileState[id].file) { var cookieName = getChunkDataCookieName(id); qq.deleteCookie(cookieName); } } function getPersistedChunkData(id) { var chunkCookieValue = qq.getCookie(getChunkDataCookieName(id)), filename = api.getName(id), sections, uuid, partIndex, lastByteSent, initialRequestOverhead, estTotalRequestsSize; if (chunkCookieValue) { sections = chunkCookieValue.split(cookieItemDelimiter); if (sections.length === 5) { uuid = sections[0]; partIndex = parseInt(sections[1], 10); lastByteSent = parseInt(sections[2], 10); initialRequestOverhead = parseInt(sections[3], 10); estTotalRequestsSize = parseInt(sections[4], 10); return { uuid: uuid, part: partIndex, lastByteSent: lastByteSent, initialRequestOverhead: initialRequestOverhead, estTotalRequestsSize: estTotalRequestsSize }; } else { log('Ignoring previously stored resume/chunk cookie for ' + filename + " - old cookie format", "warn"); } } } function getChunkDataCookieName(id) { var filename = api.getName(id), fileSize = api.getSize(id), maxChunkSize = options.chunking.partSize, cookieName; cookieName = "qqfilechunk" + cookieItemDelimiter + encodeURIComponent(filename) + cookieItemDelimiter + fileSize + cookieItemDelimiter + maxChunkSize; if (resumeId !== undefined) { cookieName += cookieItemDelimiter + resumeId; } return cookieName; } function getResumeId() { if (options.resume.id !== null && options.resume.id !== undefined && !qq.isFunction(options.resume.id) && !qq.isObject(options.resume.id)) { return options.resume.id; } } function handleFileChunkingUpload(id, retry) { var name = api.getName(id), firstChunkIndex = 0, persistedChunkInfoForResume, firstChunkDataForResume, currentChunkIndex; if (!fileState[id].remainingChunkIdxs || fileState[id].remainingChunkIdxs.length === 0) { fileState[id].remainingChunkIdxs = []; if (resumeEnabled && !retry && fileState[id].file) { persistedChunkInfoForResume = getPersistedChunkData(id); if (persistedChunkInfoForResume) { firstChunkDataForResume = getChunkData(id, persistedChunkInfoForResume.part); if (options.onResume(id, name, getChunkDataForCallback(firstChunkDataForResume)) !== false) { firstChunkIndex = persistedChunkInfoForResume.part; fileState[id].uuid = persistedChunkInfoForResume.uuid; fileState[id].loaded = persistedChunkInfoForResume.lastByteSent; fileState[id].estTotalRequestsSize = persistedChunkInfoForResume.estTotalRequestsSize; fileState[id].initialRequestOverhead = persistedChunkInfoForResume.initialRequestOverhead; fileState[id].attemptingResume = true; log('Resuming ' + name + " at partition index " + firstChunkIndex); } } } for (currentChunkIndex = getTotalChunks(id)-1; currentChunkIndex >= firstChunkIndex; currentChunkIndex-=1) { fileState[id].remainingChunkIdxs.unshift(currentChunkIndex); } } uploadNextChunk(id); } function handleStandardFileUpload(id) { var fileOrBlob = fileState[id].file || fileState[id].blobData.blob, name = api.getName(id), xhr, params, toSend; fileState[id].loaded = 0; xhr = createXhr(id); xhr.upload.onprogress = function(e){ if (e.lengthComputable){ fileState[id].loaded = e.loaded; options.onProgress(id, name, e.loaded, e.total); } }; xhr.onreadystatechange = getReadyStateChangeHandler(id, xhr); params = options.paramsStore.getParams(id); toSend = setParamsAndGetEntityToSend(params, xhr, fileOrBlob, id); setHeaders(id, xhr); log('Sending upload request for ' + id); xhr.send(toSend); } api = { /** * Adds File or Blob to the queue * Returns id to use with upload, cancel **/ add: function(fileOrBlobData){ var id; if (fileOrBlobData instanceof File) { id = fileState.push({file: fileOrBlobData}) - 1; } else if (fileOrBlobData.blob instanceof Blob) { id = fileState.push({blobData: fileOrBlobData}) - 1; } else { throw new Error('Passed obj in not a File or BlobData (in qq.UploadHandlerXhr)'); } fileState[id].uuid = qq.getUniqueId(); return id; }, getName: function(id){ var file = fileState[id].file, blobData = fileState[id].blobData; if (file) { // fix missing name in Safari 4 //NOTE: fixed missing name firefox 11.0a2 file.fileName is actually undefined return (file.fileName !== null && file.fileName !== undefined) ? file.fileName : file.name; } else { return blobData.name; } }, getSize: function(id){ /*jshint eqnull: true*/ var fileOrBlob = fileState[id].file || fileState[id].blobData.blob; if (qq.isFileOrInput(fileOrBlob)) { return fileOrBlob.fileSize != null ? fileOrBlob.fileSize : fileOrBlob.size; } else { return fileOrBlob.size; } }, getFile: function(id) { if (fileState[id]) { return fileState[id].file || fileState[id].blobData.blob; } }, /** * Returns uploaded bytes for file identified by id */ getLoaded: function(id){ return fileState[id].loaded || 0; }, isValid: function(id) { return fileState[id] !== undefined; }, reset: function() { fileState = []; }, getUuid: function(id) { return fileState[id].uuid; }, /** * Sends the file identified by id to the server */ upload: function(id, retry){ var name = this.getName(id); options.onUpload(id, name); if (chunkFiles) { handleFileChunkingUpload(id, retry); } else { handleStandardFileUpload(id); } }, cancel: function(id){ var xhr = fileState[id].xhr; options.onCancel(id, this.getName(id)); if (xhr) { xhr.onreadystatechange = null; xhr.abort(); } if (resumeEnabled) { deletePersistedChunkData(id); } delete fileState[id]; }, getResumableFilesData: function() { var matchingCookieNames = [], resumableFilesData = []; if (chunkFiles && resumeEnabled) { if (resumeId === undefined) { matchingCookieNames = qq.getCookieNames(new RegExp("^qqfilechunk\\" + cookieItemDelimiter + ".+\\" + cookieItemDelimiter + "\\d+\\" + cookieItemDelimiter + options.chunking.partSize + "=")); } else { matchingCookieNames = qq.getCookieNames(new RegExp("^qqfilechunk\\" + cookieItemDelimiter + ".+\\" + cookieItemDelimiter + "\\d+\\" + cookieItemDelimiter + options.chunking.partSize + "\\" + cookieItemDelimiter + resumeId + "=")); } qq.each(matchingCookieNames, function(idx, cookieName) { var cookiesNameParts = cookieName.split(cookieItemDelimiter); var cookieValueParts = qq.getCookie(cookieName).split(cookieItemDelimiter); resumableFilesData.push({ name: decodeURIComponent(cookiesNameParts[1]), size: cookiesNameParts[2], uuid: cookieValueParts[0], partIdx: cookieValueParts[1] }); }); return resumableFilesData; } return []; } }; return api; };
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/worker-xml.js
3,887
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; if (!window.console) { window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; } window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject(array[i]); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } if (Object.prototype.toString.call(obj) !== "[object Object]") return obj; copy = {}; for (var key in obj) copy[key] = deepCopy(obj[key]); return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); } } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!(range instanceof Range)) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/xml/sax",["require","exports","module"], function(require, exports, module) { var nameStartChar = /[A-Z_a-z\xC0-\xD6\xD8-\xF6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]///\u10000-\uEFFFF var nameChar = new RegExp("[\\-\\.0-9"+nameStartChar.source.slice(1,-1)+"\u00B7\u0300-\u036F\\ux203F-\u2040]"); var tagNamePattern = new RegExp('^'+nameStartChar.source+nameChar.source+'*(?:\:'+nameStartChar.source+nameChar.source+'*)?$'); var S_TAG = 0;//tag name offerring var S_ATTR = 1;//attr name offerring var S_ATTR_S=2;//attr name end and space offer var S_EQ = 3;//=space? var S_V = 4;//attr value(no quot value only) var S_E = 5;//attr value end and no space(quot end) var S_S = 6;//(attr value end || tag end ) && (space offer) var S_C = 7;//closed el<el /> function XMLReader(){ } XMLReader.prototype = { parse:function(source,defaultNSMap,entityMap){ var domBuilder = this.domBuilder; domBuilder.startDocument(); _copy(defaultNSMap ,defaultNSMap = {}) parse(source,defaultNSMap,entityMap, domBuilder,this.errorHandler); domBuilder.endDocument(); } } function parse(source,defaultNSMapCopy,entityMap,domBuilder,errorHandler){ function fixedFromCharCode(code) { if (code > 0xffff) { code -= 0x10000; var surrogate1 = 0xd800 + (code >> 10) , surrogate2 = 0xdc00 + (code & 0x3ff); return String.fromCharCode(surrogate1, surrogate2); } else { return String.fromCharCode(code); } } function entityReplacer(a){ var k = a.slice(1,-1); if(k in entityMap){ return entityMap[k]; }else if(k.charAt(0) === '#'){ return fixedFromCharCode(parseInt(k.substr(1).replace('x','0x'))) }else{ errorHandler.error('entity not found:'+a); return a; } } function appendText(end){//has some bugs var xt = source.substring(start,end).replace(/&#?\w+;/g,entityReplacer); locator&&position(start); domBuilder.characters(xt,0,end-start); start = end } function position(start,m){ while(start>=endPos && (m = linePattern.exec(source))){ startPos = m.index; endPos = startPos + m[0].length; locator.lineNumber++; } locator.columnNumber = start-startPos+1; } var startPos = 0; var endPos = 0; var linePattern = /.+(?:\r\n?|\n)|.*$/g var locator = domBuilder.locator; var parseStack = [{currentNSMap:defaultNSMapCopy}] var closeMap = {}; var start = 0; while(true){ var i = source.indexOf('<',start); if(i<0){ if(!source.substr(start).match(/^\s*$/)){ var doc = domBuilder.document; var text = doc.createTextNode(source.substr(start)); doc.appendChild(text); domBuilder.currentElement = text; } return; } if(i>start){ appendText(i); } switch(source.charAt(i+1)){ case '/': var end = source.indexOf('>',i+3); var tagName = source.substring(i+2,end); var config; if (parseStack.length > 1) { config = parseStack.pop(); } else { errorHandler.fatalError("end tag name not found for: "+tagName); break; } var localNSMap = config.localNSMap; if(config.tagName != tagName){ errorHandler.fatalError("end tag name: " + tagName + " does not match the current start tagName: "+config.tagName ); } domBuilder.endElement(config.uri,config.localName,tagName); if(localNSMap){ for(var prefix in localNSMap){ domBuilder.endPrefixMapping(prefix) ; } } end++; break; case '?':// <?...?> locator&&position(i); end = parseInstruction(source,i,domBuilder); break; case '!':// <!doctype,<![CDATA,<!-- locator&&position(i); end = parseDCC(source,i,domBuilder,errorHandler); break; default: try{ locator&&position(i); var el = new ElementAttributes(); var end = parseElementStartPart(source,i,el,entityReplacer,errorHandler); var len = el.length; if(len && locator){ var backup = copyLocator(locator,{}); for(var i = 0;i<len;i++){ var a = el[i]; position(a.offset); a.offset = copyLocator(locator,{}); } copyLocator(backup,locator); } if(!el.closed && fixSelfClosed(source,end,el.tagName,closeMap)){ el.closed = true; if(!entityMap.nbsp){ errorHandler.warning('unclosed xml attribute'); } } appendElement(el,domBuilder,parseStack); if(el.uri === 'http://www.w3.org/1999/xhtml' && !el.closed){ end = parseHtmlSpecialContent(source,end,el.tagName,entityReplacer,domBuilder) }else{ end++; } }catch(e){ errorHandler.error('element parse error: '+e); end = -1; } } if(end<0){ appendText(i+1); }else{ start = end; } } } function copyLocator(f,t){ t.lineNumber = f.lineNumber; t.columnNumber = f.columnNumber; return t; } function parseElementStartPart(source,start,el,entityReplacer,errorHandler){ var attrName; var value; var p = ++start; var s = S_TAG;//status while(true){ var c = source.charAt(p); switch(c){ case '=': if(s === S_ATTR){//attrName attrName = source.slice(start,p); s = S_EQ; }else if(s === S_ATTR_S){ s = S_EQ; }else{ throw new Error('attribute equal must after attrName'); } break; case '\'': case '"': if(s === S_EQ){//equal start = p+1; p = source.indexOf(c,start) if(p>0){ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); el.add(attrName,value,start-1); s = S_E; }else{ throw new Error('attribute value no end \''+c+'\' match'); } }else if(s == S_V){ value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); el.add(attrName,value,start); errorHandler.warning('attribute "'+attrName+'" missed start quot('+c+')!!'); start = p+1; s = S_E }else{ throw new Error('attribute value must after "="'); } break; case '/': switch(s){ case S_TAG: el.setTagName(source.slice(start,p)); case S_E: case S_S: case S_C: s = S_C; el.closed = true; case S_V: case S_ATTR: case S_ATTR_S: break; default: throw new Error("attribute invalid close char('/')") } break; case ''://end document errorHandler.error('unexpected end of input'); case '>': switch(s){ case S_TAG: el.setTagName(source.slice(start,p)); case S_E: case S_S: case S_C: break;//normal case S_V://Compatible state case S_ATTR: value = source.slice(start,p); if(value.slice(-1) === '/'){ el.closed = true; value = value.slice(0,-1) } case S_ATTR_S: if(s === S_ATTR_S){ value = attrName; } if(s == S_V){ errorHandler.warning('attribute "'+value+'" missed quot(")!!'); el.add(attrName,value.replace(/&#?\w+;/g,entityReplacer),start) }else{ errorHandler.warning('attribute "'+value+'" missed value!! "'+value+'" instead!!') el.add(value,value,start) } break; case S_EQ: throw new Error('attribute value missed!!'); } return p; case '\u0080': c = ' '; default: if(c<= ' '){//space switch(s){ case S_TAG: el.setTagName(source.slice(start,p));//tagName s = S_S; break; case S_ATTR: attrName = source.slice(start,p) s = S_ATTR_S; break; case S_V: var value = source.slice(start,p).replace(/&#?\w+;/g,entityReplacer); errorHandler.warning('attribute "'+value+'" missed quot(")!!'); el.add(attrName,value,start) case S_E: s = S_S; break; } }else{//not space switch(s){ case S_ATTR_S: errorHandler.warning('attribute "'+attrName+'" missed value!! "'+attrName+'" instead!!') el.add(attrName,attrName,start); start = p; s = S_ATTR; break; case S_E: errorHandler.warning('attribute space is required"'+attrName+'"!!') case S_S: s = S_ATTR; start = p; break; case S_EQ: s = S_V; start = p; break; case S_C: throw new Error("elements closed character '/' and '>' must be connected to"); } } } p++; } } function appendElement(el,domBuilder,parseStack){ var tagName = el.tagName; var localNSMap = null; var currentNSMap = parseStack[parseStack.length-1].currentNSMap; var i = el.length; while(i--){ var a = el[i]; var qName = a.qName; var value = a.value; var nsp = qName.indexOf(':'); if(nsp>0){ var prefix = a.prefix = qName.slice(0,nsp); var localName = qName.slice(nsp+1); var nsPrefix = prefix === 'xmlns' && localName }else{ localName = qName; prefix = null nsPrefix = qName === 'xmlns' && '' } a.localName = localName ; if(nsPrefix !== false){//hack!! if(localNSMap == null){ localNSMap = {} _copy(currentNSMap,currentNSMap={}) } currentNSMap[nsPrefix] = localNSMap[nsPrefix] = value; a.uri = 'http://www.w3.org/2000/xmlns/' domBuilder.startPrefixMapping(nsPrefix, value) } } var i = el.length; while(i--){ a = el[i]; var prefix = a.prefix; if(prefix){//no prefix attribute has no namespace if(prefix === 'xml'){ a.uri = 'http://www.w3.org/XML/1998/namespace'; }if(prefix !== 'xmlns'){ a.uri = currentNSMap[prefix] } } } var nsp = tagName.indexOf(':'); if(nsp>0){ prefix = el.prefix = tagName.slice(0,nsp); localName = el.localName = tagName.slice(nsp+1); }else{ prefix = null;//important!! localName = el.localName = tagName; } var ns = el.uri = currentNSMap[prefix || '']; domBuilder.startElement(ns,localName,tagName,el); if(el.closed){ domBuilder.endElement(ns,localName,tagName); if(localNSMap){ for(prefix in localNSMap){ domBuilder.endPrefixMapping(prefix) } } }else{ el.currentNSMap = currentNSMap; el.localNSMap = localNSMap; parseStack.push(el); } } function parseHtmlSpecialContent(source,elStartEnd,tagName,entityReplacer,domBuilder){ if(/^(?:script|textarea)$/i.test(tagName)){ var elEndStart = source.indexOf('</'+tagName+'>',elStartEnd); var text = source.substring(elStartEnd+1,elEndStart); if(/[&<]/.test(text)){ if(/^script$/i.test(tagName)){ domBuilder.characters(text,0,text.length); return elEndStart; }//}else{//text area text = text.replace(/&#?\w+;/g,entityReplacer); domBuilder.characters(text,0,text.length); return elEndStart; } } return elStartEnd+1; } function fixSelfClosed(source,elStartEnd,tagName,closeMap){ var pos = closeMap[tagName]; if(pos == null){ pos = closeMap[tagName] = source.lastIndexOf('</'+tagName+'>') } return pos<elStartEnd; } function _copy(source,target){ for(var n in source){target[n] = source[n]} } function parseDCC(source,start,domBuilder,errorHandler){//sure start with '<!' var next= source.charAt(start+2) switch(next){ case '-': if(source.charAt(start + 3) === '-'){ var end = source.indexOf('-->',start+4); if(end>start){ domBuilder.comment(source,start+4,end-start-4); return end+3; }else{ errorHandler.error("Unclosed comment"); return -1; } }else{ return -1; } default: if(source.substr(start+3,6) == 'CDATA['){ var end = source.indexOf(']]>',start+9); domBuilder.startCDATA(); domBuilder.characters(source,start+9,end-start-9); domBuilder.endCDATA() return end+3; } var matchs = split(source,start); var len = matchs.length; if(len>1 && /!doctype/i.test(matchs[0][0])){ var name = matchs[1][0]; var pubid = len>3 && /^public$/i.test(matchs[2][0]) && matchs[3][0] var sysid = len>4 && matchs[4][0]; var lastMatch = matchs[len-1] domBuilder.startDTD(name,pubid && pubid.replace(/^(['"])(.*?)\1$/,'$2'), sysid && sysid.replace(/^(['"])(.*?)\1$/,'$2')); domBuilder.endDTD(); return lastMatch.index+lastMatch[0].length } } return -1; } function parseInstruction(source,start,domBuilder){ var end = source.indexOf('?>',start); if(end){ var match = source.substring(start,end).match(/^<\?(\S*)\s*([\s\S]*?)\s*$/); if(match){ var len = match[0].length; domBuilder.processingInstruction(match[1], match[2]) ; return end+2; }else{//error return -1; } } return -1; } function ElementAttributes(source){ } ElementAttributes.prototype = { setTagName:function(tagName){ if(!tagNamePattern.test(tagName)){ throw new Error('invalid tagName:'+tagName) } this.tagName = tagName }, add:function(qName,value,offset){ if(!tagNamePattern.test(qName)){ throw new Error('invalid attribute:'+qName) } this[this.length++] = {qName:qName,value:value,offset:offset} }, length:0, getLocalName:function(i){return this[i].localName}, getOffset:function(i){return this[i].offset}, getQName:function(i){return this[i].qName}, getURI:function(i){return this[i].uri}, getValue:function(i){return this[i].value} } function _set_proto_(thiz,parent){ thiz.__proto__ = parent; return thiz; } if(!(_set_proto_({},_set_proto_.prototype) instanceof _set_proto_)){ _set_proto_ = function(thiz,parent){ function p(){}; p.prototype = parent; p = new p(); for(parent in thiz){ p[parent] = thiz[parent]; } return p; } } function split(source,start){ var match; var buf = []; var reg = /'[^']+'|"[^"]+"|[^\s<>\/=]+=?|(\/?\s*>|<)/g; reg.lastIndex = start; reg.exec(source);//skip < while(match = reg.exec(source)){ buf.push(match); if(match[1])return buf; } } return XMLReader; }); ace.define("ace/mode/xml/dom",["require","exports","module"], function(require, exports, module) { function copy(src,dest){ for(var p in src){ dest[p] = src[p]; } } function _extends(Class,Super){ var pt = Class.prototype; if(Object.create){ var ppt = Object.create(Super.prototype) pt.__proto__ = ppt; } if(!(pt instanceof Super)){ function t(){}; t.prototype = Super.prototype; t = new t(); copy(pt,t); Class.prototype = pt = t; } if(pt.constructor != Class){ if(typeof Class != 'function'){ console.error("unknow Class:"+Class) } pt.constructor = Class } } var htmlns = 'http://www.w3.org/1999/xhtml' ; var NodeType = {} var ELEMENT_NODE = NodeType.ELEMENT_NODE = 1; var ATTRIBUTE_NODE = NodeType.ATTRIBUTE_NODE = 2; var TEXT_NODE = NodeType.TEXT_NODE = 3; var CDATA_SECTION_NODE = NodeType.CDATA_SECTION_NODE = 4; var ENTITY_REFERENCE_NODE = NodeType.ENTITY_REFERENCE_NODE = 5; var ENTITY_NODE = NodeType.ENTITY_NODE = 6; var PROCESSING_INSTRUCTION_NODE = NodeType.PROCESSING_INSTRUCTION_NODE = 7; var COMMENT_NODE = NodeType.COMMENT_NODE = 8; var DOCUMENT_NODE = NodeType.DOCUMENT_NODE = 9; var DOCUMENT_TYPE_NODE = NodeType.DOCUMENT_TYPE_NODE = 10; var DOCUMENT_FRAGMENT_NODE = NodeType.DOCUMENT_FRAGMENT_NODE = 11; var NOTATION_NODE = NodeType.NOTATION_NODE = 12; var ExceptionCode = {} var ExceptionMessage = {}; var INDEX_SIZE_ERR = ExceptionCode.INDEX_SIZE_ERR = ((ExceptionMessage[1]="Index size error"),1); var DOMSTRING_SIZE_ERR = ExceptionCode.DOMSTRING_SIZE_ERR = ((ExceptionMessage[2]="DOMString size error"),2); var HIERARCHY_REQUEST_ERR = ExceptionCode.HIERARCHY_REQUEST_ERR = ((ExceptionMessage[3]="Hierarchy request error"),3); var WRONG_DOCUMENT_ERR = ExceptionCode.WRONG_DOCUMENT_ERR = ((ExceptionMessage[4]="Wrong document"),4); var INVALID_CHARACTER_ERR = ExceptionCode.INVALID_CHARACTER_ERR = ((ExceptionMessage[5]="Invalid character"),5); var NO_DATA_ALLOWED_ERR = ExceptionCode.NO_DATA_ALLOWED_ERR = ((ExceptionMessage[6]="No data allowed"),6); var NO_MODIFICATION_ALLOWED_ERR = ExceptionCode.NO_MODIFICATION_ALLOWED_ERR = ((ExceptionMessage[7]="No modification allowed"),7); var NOT_FOUND_ERR = ExceptionCode.NOT_FOUND_ERR = ((ExceptionMessage[8]="Not found"),8); var NOT_SUPPORTED_ERR = ExceptionCode.NOT_SUPPORTED_ERR = ((ExceptionMessage[9]="Not supported"),9); var INUSE_ATTRIBUTE_ERR = ExceptionCode.INUSE_ATTRIBUTE_ERR = ((ExceptionMessage[10]="Attribute in use"),10); var INVALID_STATE_ERR = ExceptionCode.INVALID_STATE_ERR = ((ExceptionMessage[11]="Invalid state"),11); var SYNTAX_ERR = ExceptionCode.SYNTAX_ERR = ((ExceptionMessage[12]="Syntax error"),12); var INVALID_MODIFICATION_ERR = ExceptionCode.INVALID_MODIFICATION_ERR = ((ExceptionMessage[13]="Invalid modification"),13); var NAMESPACE_ERR = ExceptionCode.NAMESPACE_ERR = ((ExceptionMessage[14]="Invalid namespace"),14); var INVALID_ACCESS_ERR = ExceptionCode.INVALID_ACCESS_ERR = ((ExceptionMessage[15]="Invalid access"),15); function DOMException(code, message) { if(message instanceof Error){ var error = message; }else{ error = this; Error.call(this, ExceptionMessage[code]); this.message = ExceptionMessage[code]; if(Error.captureStackTrace) Error.captureStackTrace(this, DOMException); } error.code = code; if(message) this.message = this.message + ": " + message; return error; }; DOMException.prototype = Error.prototype; copy(ExceptionCode,DOMException) function NodeList() { }; NodeList.prototype = { length:0, item: function(index) { return this[index] || null; } }; function LiveNodeList(node,refresh){ this._node = node; this._refresh = refresh _updateLiveList(this); } function _updateLiveList(list){ var inc = list._node._inc || list._node.ownerDocument._inc; if(list._inc != inc){ var ls = list._refresh(list._node); __set__(list,'length',ls.length); copy(ls,list); list._inc = inc; } } LiveNodeList.prototype.item = function(i){ _updateLiveList(this); return this[i]; } _extends(LiveNodeList,NodeList); function NamedNodeMap() { }; function _findNodeIndex(list,node){ var i = list.length; while(i--){ if(list[i] === node){return i} } } function _addNamedNode(el,list,newAttr,oldAttr){ if(oldAttr){ list[_findNodeIndex(list,oldAttr)] = newAttr; }else{ list[list.length++] = newAttr; } if(el){ newAttr.ownerElement = el; var doc = el.ownerDocument; if(doc){ oldAttr && _onRemoveAttribute(doc,el,oldAttr); _onAddAttribute(doc,el,newAttr); } } } function _removeNamedNode(el,list,attr){ var i = _findNodeIndex(list,attr); if(i>=0){ var lastIndex = list.length-1 while(i<lastIndex){ list[i] = list[++i] } list.length = lastIndex; if(el){ var doc = el.ownerDocument; if(doc){ _onRemoveAttribute(doc,el,attr); attr.ownerElement = null; } } }else{ throw DOMException(NOT_FOUND_ERR,new Error()) } } NamedNodeMap.prototype = { length:0, item:NodeList.prototype.item, getNamedItem: function(key) { var i = this.length; while(i--){ var attr = this[i]; if(attr.nodeName == key){ return attr; } } }, setNamedItem: function(attr) { var el = attr.ownerElement; if(el && el!=this._ownerElement){ throw new DOMException(INUSE_ATTRIBUTE_ERR); } var oldAttr = this.getNamedItem(attr.nodeName); _addNamedNode(this._ownerElement,this,attr,oldAttr); return oldAttr; }, setNamedItemNS: function(attr) {// raises: WRONG_DOCUMENT_ERR,NO_MODIFICATION_ALLOWED_ERR,INUSE_ATTRIBUTE_ERR var el = attr.ownerElement, oldAttr; if(el && el!=this._ownerElement){ throw new DOMException(INUSE_ATTRIBUTE_ERR); } oldAttr = this.getNamedItemNS(attr.namespaceURI,attr.localName); _addNamedNode(this._ownerElement,this,attr,oldAttr); return oldAttr; }, removeNamedItem: function(key) { var attr = this.getNamedItem(key); _removeNamedNode(this._ownerElement,this,attr); return attr; },// raises: NOT_FOUND_ERR,NO_MODIFICATION_ALLOWED_ERR removeNamedItemNS:function(namespaceURI,localName){ var attr = this.getNamedItemNS(namespaceURI,localName); _removeNamedNode(this._ownerElement,this,attr); return attr; }, getNamedItemNS: function(namespaceURI, localName) { var i = this.length; while(i--){ var node = this[i]; if(node.localName == localName && node.namespaceURI == namespaceURI){ return node; } } return null; } }; function DOMImplementation(/* Object */ features) { this._features = {}; if (features) { for (var feature in features) { this._features = features[feature]; } } }; DOMImplementation.prototype = { hasFeature: function(/* string */ feature, /* string */ version) { var versions = this._features[feature.toLowerCase()]; if (versions && (!version || version in versions)) { return true; } else { return false; } }, createDocument:function(namespaceURI, qualifiedName, doctype){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR,WRONG_DOCUMENT_ERR var doc = new Document(); doc.implementation = this; doc.childNodes = new NodeList(); doc.doctype = doctype; if(doctype){ doc.appendChild(doctype); } if(qualifiedName){ var root = doc.createElementNS(namespaceURI,qualifiedName); doc.appendChild(root); } return doc; }, createDocumentType:function(qualifiedName, publicId, systemId){// raises:INVALID_CHARACTER_ERR,NAMESPACE_ERR var node = new DocumentType(); node.name = qualifiedName; node.nodeName = qualifiedName; node.publicId = publicId; node.systemId = systemId; return node; } }; function Node() { }; Node.prototype = { firstChild : null, lastChild : null, previousSibling : null, nextSibling : null, attributes : null, parentNode : null, childNodes : null, ownerDocument : null, nodeValue : null, namespaceURI : null, prefix : null, localName : null, insertBefore:function(newChild, refChild){//raises return _insertBefore(this,newChild,refChild); }, replaceChild:function(newChild, oldChild){//raises this.insertBefore(newChild,oldChild); if(oldChild){ this.removeChild(oldChild); } }, removeChild:function(oldChild){ return _removeChild(this,oldChild); }, appendChild:function(newChild){ return this.insertBefore(newChild,null); }, hasChildNodes:function(){ return this.firstChild != null; }, cloneNode:function(deep){ return cloneNode(this.ownerDocument||this,this,deep); }, normalize:function(){ var child = this.firstChild; while(child){ var next = child.nextSibling; if(next && next.nodeType == TEXT_NODE && child.nodeType == TEXT_NODE){ this.removeChild(next); child.appendData(next.data); }else{ child.normalize(); child = next; } } }, isSupported:function(feature, version){ return this.ownerDocument.implementation.hasFeature(feature,version); }, hasAttributes:function(){ return this.attributes.length>0; }, lookupPrefix:function(namespaceURI){ var el = this; while(el){ var map = el._nsMap; if(map){ for(var n in map){ if(map[n] == namespaceURI){ return n; } } } el = el.nodeType == 2?el.ownerDocument : el.parentNode; } return null; }, lookupNamespaceURI:function(prefix){ var el = this; while(el){ var map = el._nsMap; if(map){ if(prefix in map){ return map[prefix] ; } } el = el.nodeType == 2?el.ownerDocument : el.parentNode; } return null; }, isDefaultNamespace:function(namespaceURI){ var prefix = this.lookupPrefix(namespaceURI); return prefix == null; } }; function _xmlEncoder(c){ return c == '<' && '&lt;' || c == '>' && '&gt;' || c == '&' && '&amp;' || c == '"' && '&quot;' || '&#'+c.charCodeAt()+';' } copy(NodeType,Node); copy(NodeType,Node.prototype); function _visitNode(node,callback){ if(callback(node)){ return true; } if(node = node.firstChild){ do{ if(_visitNode(node,callback)){return true} }while(node=node.nextSibling) } } function Document(){ } function _onAddAttribute(doc,el,newAttr){ doc && doc._inc++; var ns = newAttr.namespaceURI ; if(ns == 'http://www.w3.org/2000/xmlns/'){ el._nsMap[newAttr.prefix?newAttr.localName:''] = newAttr.value } } function _onRemoveAttribute(doc,el,newAttr,remove){ doc && doc._inc++; var ns = newAttr.namespaceURI ; if(ns == 'http://www.w3.org/2000/xmlns/'){ delete el._nsMap[newAttr.prefix?newAttr.localName:''] } } function _onUpdateChild(doc,el,newChild){ if(doc && doc._inc){ doc._inc++; var cs = el.childNodes; if(newChild){ cs[cs.length++] = newChild; }else{ var child = el.firstChild; var i = 0; while(child){ cs[i++] = child; child =child.nextSibling; } cs.length = i; } } } function _removeChild(parentNode,child){ var previous = child.previousSibling; var next = child.nextSibling; if(previous){ previous.nextSibling = next; }else{ parentNode.firstChild = next } if(next){ next.previousSibling = previous; }else{ parentNode.lastChild = previous; } _onUpdateChild(parentNode.ownerDocument,parentNode); return child; } function _insertBefore(parentNode,newChild,nextChild){ var cp = newChild.parentNode; if(cp){ cp.removeChild(newChild);//remove and update } if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ var newFirst = newChild.firstChild; if (newFirst == null) { return newChild; } var newLast = newChild.lastChild; }else{ newFirst = newLast = newChild; } var pre = nextChild ? nextChild.previousSibling : parentNode.lastChild; newFirst.previousSibling = pre; newLast.nextSibling = nextChild; if(pre){ pre.nextSibling = newFirst; }else{ parentNode.firstChild = newFirst; } if(nextChild == null){ parentNode.lastChild = newLast; }else{ nextChild.previousSibling = newLast; } do{ newFirst.parentNode = parentNode; }while(newFirst !== newLast && (newFirst= newFirst.nextSibling)) _onUpdateChild(parentNode.ownerDocument||parentNode,parentNode); if (newChild.nodeType == DOCUMENT_FRAGMENT_NODE) { newChild.firstChild = newChild.lastChild = null; } return newChild; } function _appendSingleChild(parentNode,newChild){ var cp = newChild.parentNode; if(cp){ var pre = parentNode.lastChild; cp.removeChild(newChild);//remove and update var pre = parentNode.lastChild; } var pre = parentNode.lastChild; newChild.parentNode = parentNode; newChild.previousSibling = pre; newChild.nextSibling = null; if(pre){ pre.nextSibling = newChild; }else{ parentNode.firstChild = newChild; } parentNode.lastChild = newChild; _onUpdateChild(parentNode.ownerDocument,parentNode,newChild); return newChild; } Document.prototype = { nodeName : '#document', nodeType : DOCUMENT_NODE, doctype : null, documentElement : null, _inc : 1, insertBefore : function(newChild, refChild){//raises if(newChild.nodeType == DOCUMENT_FRAGMENT_NODE){ var child = newChild.firstChild; while(child){ var next = child.nextSibling; this.insertBefore(child,refChild); child = next; } return newChild; } if(this.documentElement == null && newChild.nodeType == 1){ this.documentElement = newChild; } return _insertBefore(this,newChild,refChild),(newChild.ownerDocument = this),newChild; }, removeChild : function(oldChild){ if(this.documentElement == oldChild){ this.documentElement = null; } return _removeChild(this,oldChild); }, importNode : function(importedNode,deep){ return importNode(this,importedNode,deep); }, getElementById : function(id){ var rtv = null; _visitNode(this.documentElement,function(node){ if(node.nodeType == 1){ if(node.getAttribute('id') == id){ rtv = node; return true; } } }) return rtv; }, createElement : function(tagName){ var node = new Element(); node.ownerDocument = this; node.nodeName = tagName; node.tagName = tagName; node.childNodes = new NodeList(); var attrs = node.attributes = new NamedNodeMap(); attrs._ownerElement = node; return node; }, createDocumentFragment : function(){ var node = new DocumentFragment(); node.ownerDocument = this; node.childNodes = new NodeList(); return node; }, createTextNode : function(data){ var node = new Text(); node.ownerDocument = this; node.appendData(data) return node; }, createComment : function(data){ var node = new Comment(); node.ownerDocument = this; node.appendData(data) return node; }, createCDATASection : function(data){ var node = new CDATASection(); node.ownerDocument = this; node.appendData(data) return node; }, createProcessingInstruction : function(target,data){ var node = new ProcessingInstruction(); node.ownerDocument = this; node.tagName = node.target = target; node.nodeValue= node.data = data; return node; }, createAttribute : function(name){ var node = new Attr(); node.ownerDocument = this; node.name = name; node.nodeName = name; node.localName = name; node.specified = true; return node; }, createEntityReference : function(name){ var node = new EntityReference(); node.ownerDocument = this; node.nodeName = name; return node; }, createElementNS : function(namespaceURI,qualifiedName){ var node = new Element(); var pl = qualifiedName.split(':'); var attrs = node.attributes = new NamedNodeMap(); node.childNodes = new NodeList(); node.ownerDocument = this; node.nodeName = qualifiedName; node.tagName = qualifiedName; node.namespaceURI = namespaceURI; if(pl.length == 2){ node.prefix = pl[0]; node.localName = pl[1]; }else{ node.localName = qualifiedName; } attrs._ownerElement = node; return node; }, createAttributeNS : function(namespaceURI,qualifiedName){ var node = new Attr(); var pl = qualifiedName.split(':'); node.ownerDocument = this; node.nodeName = qualifiedName; node.name = qualifiedName; node.namespaceURI = namespaceURI; node.specified = true; if(pl.length == 2){ node.prefix = pl[0]; node.localName = pl[1]; }else{ node.localName = qualifiedName; } return node; } }; _extends(Document,Node); function Element() { this._nsMap = {}; }; Element.prototype = { nodeType : ELEMENT_NODE, hasAttribute : function(name){ return this.getAttributeNode(name)!=null; }, getAttribute : function(name){ var attr = this.getAttributeNode(name); return attr && attr.value || ''; }, getAttributeNode : function(name){ return this.attributes.getNamedItem(name); }, setAttribute : function(name, value){ var attr = this.ownerDocument.createAttribute(name); attr.value = attr.nodeValue = "" + value; this.setAttributeNode(attr) }, removeAttribute : function(name){ var attr = this.getAttributeNode(name) attr && this.removeAttributeNode(attr); }, appendChild:function(newChild){ if(newChild.nodeType === DOCUMENT_FRAGMENT_NODE){ return this.insertBefore(newChild,null); }else{ return _appendSingleChild(this,newChild); } }, setAttributeNode : function(newAttr){ return this.attributes.setNamedItem(newAttr); }, setAttributeNodeNS : function(newAttr){ return this.attributes.setNamedItemNS(newAttr); }, removeAttributeNode : function(oldAttr){ return this.attributes.removeNamedItem(oldAttr.nodeName); }, removeAttributeNS : function(namespaceURI, localName){ var old = this.getAttributeNodeNS(namespaceURI, localName); old && this.removeAttributeNode(old); }, hasAttributeNS : function(namespaceURI, localName){ return this.getAttributeNodeNS(namespaceURI, localName)!=null; }, getAttributeNS : function(namespaceURI, localName){ var attr = this.getAttributeNodeNS(namespaceURI, localName); return attr && attr.value || ''; }, setAttributeNS : function(namespaceURI, qualifiedName, value){ var attr = this.ownerDocument.createAttributeNS(namespaceURI, qualifiedName); attr.value = attr.nodeValue = "" + value; this.setAttributeNode(attr) }, getAttributeNodeNS : function(namespaceURI, localName){ return this.attributes.getNamedItemNS(namespaceURI, localName); }, getElementsByTagName : function(tagName){ return new LiveNodeList(this,function(base){ var ls = []; _visitNode(base,function(node){ if(node !== base && node.nodeType == ELEMENT_NODE && (tagName === '*' || node.tagName == tagName)){ ls.push(node); } }); return ls; }); }, getElementsByTagNameNS : function(namespaceURI, localName){ return new LiveNodeList(this,function(base){ var ls = []; _visitNode(base,function(node){ if(node !== base && node.nodeType === ELEMENT_NODE && (namespaceURI === '*' || node.namespaceURI === namespaceURI) && (localName === '*' || node.localName == localName)){ ls.push(node); } }); return ls; }); } }; Document.prototype.getElementsByTagName = Element.prototype.getElementsByTagName; Document.prototype.getElementsByTagNameNS = Element.prototype.getElementsByTagNameNS; _extends(Element,Node); function Attr() { }; Attr.prototype.nodeType = ATTRIBUTE_NODE; _extends(Attr,Node); function CharacterData() { }; CharacterData.prototype = { data : '', substringData : function(offset, count) { return this.data.substring(offset, offset+count); }, appendData: function(text) { text = this.data+text; this.nodeValue = this.data = text; this.length = text.length; }, insertData: function(offset,text) { this.replaceData(offset,0,text); }, appendChild:function(newChild){ throw new Error(ExceptionMessage[3]) return Node.prototype.appendChild.apply(this,arguments) }, deleteData: function(offset, count) { this.replaceData(offset,count,""); }, replaceData: function(offset, count, text) { var start = this.data.substring(0,offset); var end = this.data.substring(offset+count); text = start + text + end; this.nodeValue = this.data = text; this.length = text.length; } } _extends(CharacterData,Node); function Text() { }; Text.prototype = { nodeName : "#text", nodeType : TEXT_NODE, splitText : function(offset) { var text = this.data; var newText = text.substring(offset); text = text.substring(0, offset); this.data = this.nodeValue = text; this.length = text.length; var newNode = this.ownerDocument.createTextNode(newText); if(this.parentNode){ this.parentNode.insertBefore(newNode, this.nextSibling); } return newNode; } } _extends(Text,CharacterData); function Comment() { }; Comment.prototype = { nodeName : "#comment", nodeType : COMMENT_NODE } _extends(Comment,CharacterData); function CDATASection() { }; CDATASection.prototype = { nodeName : "#cdata-section", nodeType : CDATA_SECTION_NODE } _extends(CDATASection,CharacterData); function DocumentType() { }; DocumentType.prototype.nodeType = DOCUMENT_TYPE_NODE; _extends(DocumentType,Node); function Notation() { }; Notation.prototype.nodeType = NOTATION_NODE; _extends(Notation,Node); function Entity() { }; Entity.prototype.nodeType = ENTITY_NODE; _extends(Entity,Node); function EntityReference() { }; EntityReference.prototype.nodeType = ENTITY_REFERENCE_NODE; _extends(EntityReference,Node); function DocumentFragment() { }; DocumentFragment.prototype.nodeName = "#document-fragment"; DocumentFragment.prototype.nodeType = DOCUMENT_FRAGMENT_NODE; _extends(DocumentFragment,Node); function ProcessingInstruction() { } ProcessingInstruction.prototype.nodeType = PROCESSING_INSTRUCTION_NODE; _extends(ProcessingInstruction,Node); function XMLSerializer(){} XMLSerializer.prototype.serializeToString = function(node){ var buf = []; serializeToString(node,buf); return buf.join(''); } Node.prototype.toString =function(){ return XMLSerializer.prototype.serializeToString(this); } function serializeToString(node,buf){ switch(node.nodeType){ case ELEMENT_NODE: var attrs = node.attributes; var len = attrs.length; var child = node.firstChild; var nodeName = node.tagName; var isHTML = htmlns === node.namespaceURI buf.push('<',nodeName); for(var i=0;i<len;i++){ serializeToString(attrs.item(i),buf,isHTML); } if(child || isHTML && !/^(?:meta|link|img|br|hr|input|button)$/i.test(nodeName)){ buf.push('>'); if(isHTML && /^script$/i.test(nodeName)){ if(child){ buf.push(child.data); } }else{ while(child){ serializeToString(child,buf); child = child.nextSibling; } } buf.push('</',nodeName,'>'); }else{ buf.push('/>'); } return; case DOCUMENT_NODE: case DOCUMENT_FRAGMENT_NODE: var child = node.firstChild; while(child){ serializeToString(child,buf); child = child.nextSibling; } return; case ATTRIBUTE_NODE: return buf.push(' ',node.name,'="',node.value.replace(/[<&"]/g,_xmlEncoder),'"'); case TEXT_NODE: return buf.push(node.data.replace(/[<&]/g,_xmlEncoder)); case CDATA_SECTION_NODE: return buf.push( '<![CDATA[',node.data,']]>'); case COMMENT_NODE: return buf.push( "<!--",node.data,"-->"); case DOCUMENT_TYPE_NODE: var pubid = node.publicId; var sysid = node.systemId; buf.push('<!DOCTYPE ',node.name); if(pubid){ buf.push(' PUBLIC "',pubid); if (sysid && sysid!='.') { buf.push( '" "',sysid); } buf.push('">'); }else if(sysid && sysid!='.'){ buf.push(' SYSTEM "',sysid,'">'); }else{ var sub = node.internalSubset; if(sub){ buf.push(" [",sub,"]"); } buf.push(">"); } return; case PROCESSING_INSTRUCTION_NODE: return buf.push( "<?",node.target," ",node.data,"?>"); case ENTITY_REFERENCE_NODE: return buf.push( '&',node.nodeName,';'); default: buf.push('??',node.nodeName); } } function importNode(doc,node,deep){ var node2; switch (node.nodeType) { case ELEMENT_NODE: node2 = node.cloneNode(false); node2.ownerDocument = doc; case DOCUMENT_FRAGMENT_NODE: break; case ATTRIBUTE_NODE: deep = true; break; } if(!node2){ node2 = node.cloneNode(false);//false } node2.ownerDocument = doc; node2.parentNode = null; if(deep){ var child = node.firstChild; while(child){ node2.appendChild(importNode(doc,child,deep)); child = child.nextSibling; } } return node2; } function cloneNode(doc,node,deep){ var node2 = new node.constructor(); for(var n in node){ var v = node[n]; if(typeof v != 'object' ){ if(v != node2[n]){ node2[n] = v; } } } if(node.childNodes){ node2.childNodes = new NodeList(); } node2.ownerDocument = doc; switch (node2.nodeType) { case ELEMENT_NODE: var attrs = node.attributes; var attrs2 = node2.attributes = new NamedNodeMap(); var len = attrs.length attrs2._ownerElement = node2; for(var i=0;i<len;i++){ node2.setAttributeNode(cloneNode(doc,attrs.item(i),true)); } break;; case ATTRIBUTE_NODE: deep = true; } if(deep){ var child = node.firstChild; while(child){ node2.appendChild(cloneNode(doc,child,deep)); child = child.nextSibling; } } return node2; } function __set__(object,key,value){ object[key] = value } try{ if(Object.defineProperty){ Object.defineProperty(LiveNodeList.prototype,'length',{ get:function(){ _updateLiveList(this); return this.$$length; } }); Object.defineProperty(Node.prototype,'textContent',{ get:function(){ return getTextContent(this); }, set:function(data){ switch(this.nodeType){ case 1: case 11: while(this.firstChild){ this.removeChild(this.firstChild); } if(data || String(data)){ this.appendChild(this.ownerDocument.createTextNode(data)); } break; default: this.data = data; this.value = value; this.nodeValue = data; } } }) function getTextContent(node){ switch(node.nodeType){ case 1: case 11: var buf = []; node = node.firstChild; while(node){ if(node.nodeType!==7 && node.nodeType !==8){ buf.push(getTextContent(node)); } node = node.nextSibling; } return buf.join(''); default: return node.nodeValue; } } __set__ = function(object,key,value){ object['$$'+key] = value } } }catch(e){//ie8 } return DOMImplementation; }); ace.define("ace/mode/xml/dom-parser",["require","exports","module","ace/mode/xml/sax","ace/mode/xml/dom"], function(require, exports, module) { 'use strict'; var XMLReader = require('./sax'), DOMImplementation = require('./dom'); function DOMParser(options){ this.options = options ||{locator:{}}; } DOMParser.prototype.parseFromString = function(source,mimeType){ var options = this.options; var sax = new XMLReader(); var domBuilder = options.domBuilder || new DOMHandler();//contentHandler and LexicalHandler var errorHandler = options.errorHandler; var locator = options.locator; var defaultNSMap = options.xmlns||{}; var entityMap = {'lt':'<','gt':'>','amp':'&','quot':'"','apos':"'"} if(locator){ domBuilder.setDocumentLocator(locator) } sax.errorHandler = buildErrorHandler(errorHandler,domBuilder,locator); sax.domBuilder = options.domBuilder || domBuilder; if(/\/x?html?$/.test(mimeType)){ entityMap.nbsp = '\xa0'; entityMap.copy = '\xa9'; defaultNSMap['']= 'http://www.w3.org/1999/xhtml'; } if(source){ sax.parse(source,defaultNSMap,entityMap); }else{ sax.errorHandler.error("invalid document source"); } return domBuilder.document; } function buildErrorHandler(errorImpl,domBuilder,locator){ if(!errorImpl){ if(domBuilder instanceof DOMHandler){ return domBuilder; } errorImpl = domBuilder ; } var errorHandler = {} var isCallback = errorImpl instanceof Function; locator = locator||{} function build(key){ var fn = errorImpl[key]; if(!fn){ if(isCallback){ fn = errorImpl.length == 2?function(msg){errorImpl(key,msg)}:errorImpl; }else{ var i=arguments.length; while(--i){ if(fn = errorImpl[arguments[i]]){ break; } } } } errorHandler[key] = fn && function(msg){ fn(msg+_locator(locator), msg, locator); }||function(){}; } build('warning','warn'); build('error','warn','warning'); build('fatalError','warn','warning','error'); return errorHandler; } function DOMHandler() { this.cdata = false; } function position(locator,node){ node.lineNumber = locator.lineNumber; node.columnNumber = locator.columnNumber; } DOMHandler.prototype = { startDocument : function() { this.document = new DOMImplementation().createDocument(null, null, null); if (this.locator) { this.document.documentURI = this.locator.systemId; } }, startElement:function(namespaceURI, localName, qName, attrs) { var doc = this.document; var el = doc.createElementNS(namespaceURI, qName||localName); var len = attrs.length; appendElement(this, el); this.currentElement = el; this.locator && position(this.locator,el) for (var i = 0 ; i < len; i++) { var namespaceURI = attrs.getURI(i); var value = attrs.getValue(i); var qName = attrs.getQName(i); var attr = doc.createAttributeNS(namespaceURI, qName); if( attr.getOffset){ position(attr.getOffset(1),attr) } attr.value = attr.nodeValue = value; el.setAttributeNode(attr) } }, endElement:function(namespaceURI, localName, qName) { var current = this.currentElement var tagName = current.tagName; this.currentElement = current.parentNode; }, startPrefixMapping:function(prefix, uri) { }, endPrefixMapping:function(prefix) { }, processingInstruction:function(target, data) { var ins = this.document.createProcessingInstruction(target, data); this.locator && position(this.locator,ins) appendElement(this, ins); }, ignorableWhitespace:function(ch, start, length) { }, characters:function(chars, start, length) { chars = _toString.apply(this,arguments) if(this.currentElement && chars){ if (this.cdata) { var charNode = this.document.createCDATASection(chars); this.currentElement.appendChild(charNode); } else { var charNode = this.document.createTextNode(chars); this.currentElement.appendChild(charNode); } this.locator && position(this.locator,charNode) } }, skippedEntity:function(name) { }, endDocument:function() { this.document.normalize(); }, setDocumentLocator:function (locator) { if(this.locator = locator){// && !('lineNumber' in locator)){ locator.lineNumber = 0; } }, comment:function(chars, start, length) { chars = _toString.apply(this,arguments) var comm = this.document.createComment(chars); this.locator && position(this.locator,comm) appendElement(this, comm); }, startCDATA:function() { this.cdata = true; }, endCDATA:function() { this.cdata = false; }, startDTD:function(name, publicId, systemId) { var impl = this.document.implementation; if (impl && impl.createDocumentType) { var dt = impl.createDocumentType(name, publicId, systemId); this.locator && position(this.locator,dt) appendElement(this, dt); } }, warning:function(error) { console.warn(error,_locator(this.locator)); }, error:function(error) { console.error(error,_locator(this.locator)); }, fatalError:function(error) { console.error(error,_locator(this.locator)); throw error; } } function _locator(l){ if(l){ return '\n@'+(l.systemId ||'')+'#[line:'+l.lineNumber+',col:'+l.columnNumber+']' } } function _toString(chars,start,length){ if(typeof chars == 'string'){ return chars.substr(start,length) }else{//java sax connect width xmldom on rhino(what about: "? && !(chars instanceof String)") if(chars.length >= start+length || start){ return new java.lang.String(chars,start,length)+''; } return chars; } } "endDTD,startEntity,endEntity,attributeDecl,elementDecl,externalEntityDecl,internalEntityDecl,resolveEntity,getExternalSubset,notationDecl,unparsedEntityDecl".replace(/\w+/g,function(key){ DOMHandler.prototype[key] = function(){return null} }) function appendElement (hander,node) { if (!hander.currentElement) { hander.document.appendChild(node); } else { hander.currentElement.appendChild(node); } }//appendChild and setAttributeNS are preformance key return { DOMParser: DOMParser }; }); ace.define("ace/mode/xml_worker",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/worker/mirror","ace/mode/xml/dom-parser"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var Mirror = require("../worker/mirror").Mirror; var DOMParser = require("./xml/dom-parser").DOMParser; var Worker = exports.Worker = function(sender) { Mirror.call(this, sender); this.setTimeout(400); this.context = null; }; oop.inherits(Worker, Mirror); (function() { this.setOptions = function(options) { this.context = options.context; }; this.onUpdate = function() { var value = this.doc.getValue(); if (!value) return; var parser = new DOMParser(); var errors = []; parser.options.errorHandler = { fatalError: function(fullMsg, errorMsg, locator) { errors.push({ row: locator.lineNumber, column: locator.columnNumber, text: errorMsg, type: "error" }); }, error: function(fullMsg, errorMsg, locator) { errors.push({ row: locator.lineNumber, column: locator.columnNumber, text: errorMsg, type: "error" }); }, warning: function(fullMsg, errorMsg, locator) { errors.push({ row: locator.lineNumber, column: locator.columnNumber, text: errorMsg, type: "warning" }); } }; parser.parseFromString(value); this.sender.emit("error", errors); }; }).call(Worker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/libs/pdfjs-1.3.91/pdf.js
9,534
/* Copyright 2012 Mozilla Foundation * * 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. */ /*jshint globalstrict: false */ /* globals PDFJS */ // Initializing PDFJS global object (if still undefined) if (typeof PDFJS === 'undefined') { (typeof window !== 'undefined' ? window : this).PDFJS = {}; } PDFJS.version = '1.3.91'; PDFJS.build = 'd1e83b5'; (function pdfjsWrapper() { // Use strict in our context only - users might not want it 'use strict'; var globalScope = (typeof window === 'undefined') ? this : window; var isWorker = (typeof window === 'undefined'); var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { TEXT: 1, LINK: 2, FREETEXT: 3, LINE: 4, SQUARE: 5, CIRCLE: 6, POLYGON: 7, POLYLINE: 8, HIGHLIGHT: 9, UNDERLINE: 10, SQUIGGLY: 11, STRIKEOUT: 12, STAMP: 13, CARET: 14, INK: 15, POPUP: 16, FILEATTACHMENT: 17, SOUND: 18, MOVIE: 19, WIDGET: 20, SCREEN: 21, PRINTERMARK: 22, TRAPNET: 23, WATERMARK: 24, THREED: 25, REDACT: 26 }; var AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, PRINT: 0x04, NOZOOM: 0x08, NOROTATE: 0x10, NOVIEW: 0x20, READONLY: 0x40, LOCKED: 0x80, TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; var AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, BEVELED: 3, INSET: 4, UNDERLINE: 5 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; // The global PDFJS object exposes the API // In production, it will be declared outside a global wrapper // In development, it will be declared here if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } globalScope.PDFJS.pdfBug = false; PDFJS.VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = PDFJS.OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Deprecated API function -- treated as warnings. function deprecated(details) { warn('Deprecated API usage: ' + details); } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; // Combines two URLs. The baseUrl shall be absolute URL. If the url is an // absolute URL, it will be returned as is. function combineUrl(baseUrl, url) { if (!url) { return baseUrl; } return new URL(url, baseUrl).href; } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url) { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': case 'tel': return true; default: return false; } } PDFJS.isValidUrl = isValidUrl; function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } PDFJS.shadow = shadow; var LinkTarget = PDFJS.LinkTarget = { NONE: 0, // Default value. SELF: 1, BLANK: 2, PARENT: 3, TOP: 4, }; var LinkTargetStringMap = [ '', '_self', '_blank', '_parent', '_top' ]; function isExternalLinkTargetSet() { if (PDFJS.openExternalLinksInNewWindow) { deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'); if (PDFJS.externalLinkTarget === LinkTarget.NONE) { PDFJS.externalLinkTarget = LinkTarget.BLANK; } // Reset the deprecated parameter, to suppress further warnings. PDFJS.openExternalLinksInNewWindow = false; } switch (PDFJS.externalLinkTarget) { case LinkTarget.NONE: return false; case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return true; } warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget); // Reset the external link target, to suppress further warnings. PDFJS.externalLinkTarget = LinkTarget.NONE; return false; } PDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet; var PasswordResponses = PDFJS.PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); PDFJS.PasswordException = PasswordException; var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); PDFJS.UnknownErrorException = UnknownErrorException; var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); PDFJS.InvalidPDFException = InvalidPDFException; var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); PDFJS.MissingPDFException = MissingPDFException; var UnexpectedResponseException = (function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; })(); PDFJS.UnexpectedResponseException = UnexpectedResponseException; var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); function bytesToString(bytes) { assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return (data[start] << 24) >> 24; } function readUint16(data, offset) { return (data[offset] << 8) | data[offset + 1]; } function readUint32(data, offset) { return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { return shadow(PDFJS, 'isLittleEndian', isLittleEndian()); } }); // Lazy test if the userAgent support CanvasTypedArrays function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays()); } }); var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = PDFJS.Util = (function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); /** * PDF page viewport created based on scale, rotation and offset. * @class * @alias PDFJS.PageViewport */ var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() { /** * @constructor * @private * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. * @param scale {number} scale of the viewport. * @param rotation {number} rotations of the viewport in degrees. * @param offsetX {number} offset X * @param offsetY {number} offset Y * @param dontFlip {boolean} if true, axis Y will not be flipped. */ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ { /** * Clones viewport with additional properties. * @param args {Object} (optional) If specified, may contain the 'scale' or * 'rotation' properties to override the corresponding properties in * the cloned viewport. * @returns {PDFJS.PageViewport} Cloned viewport. */ clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, /** * Converts PDF rectangle to the viewport coordinates. * @param rect {Array} xMin, yMin, xMax and yMax coordinates. * @returns {Array} Contains corresponding coordinates of the rectangle * in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isInt(v) { return typeof v === 'number' && ((v | 0) === v); } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isName(v) { return v instanceof Name; } function isCmd(v, cmd) { return v instanceof Cmd && (cmd === undefined || v.cmd === cmd); } function isDict(v, type) { if (!(v instanceof Dict)) { return false; } if (!type) { return true; } var dictType = v.get('Type'); return isName(dictType) && dictType.name === type; } function isArray(v) { return v instanceof Array; } function isStream(v) { return typeof v === 'object' && v !== null && v.getBytes !== undefined; } function isArrayBuffer(v) { return typeof v === 'object' && v !== null && v.byteLength !== undefined; } function isRef(v) { return v instanceof Ref; } /** * Promise Capability object. * * @typedef {Object} PromiseCapability * @property {Promise} promise - A promise object. * @property {function} resolve - Fullfills the promise. * @property {function} reject - Rejects the promise. */ /** * Creates a promise capability object. * @alias PDFJS.createPromiseCapability * * @return {PromiseCapability} A capability object contains: * - a Promise, resolve and reject methods. */ function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } PDFJS.createPromiseCapability = createPromiseCapability; /** * Polyfill for Promises: * The following promise implementation tries to generally implement the * Promise/A+ spec. Some notable differences from other promise libaries are: * - There currently isn't a seperate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (value) { return new globalScope.Promise(function (resolve) { resolve(value); }); }; } if (typeof globalScope.Promise.reject !== 'function') { globalScope.Promise.reject = function (reason) { return new globalScope.Promise(function (resolve, reject) { reject(reason); }); }; } if (typeof globalScope.Promise.prototype.catch !== 'function') { globalScope.Promise.prototype.catch = function (onReject) { return globalScope.Promise.prototype.then(undefined, onReject); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status === STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof handler.onResolve === 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof handler.onReject === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; try { resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } catch (e) { this._reject(e); } } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} array of data and/or promises to wait for. * @return {Promise} New dependant promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if value is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param value resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(value) { return new Promise(function (resolve) { resolve(value); }); }; /** * Creates rejected promise * @param reason rejection value * @returns {Promise} */ Promise.reject = function Promise_reject(reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status === STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = resolve; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; }, catch: function Promise_catch(onReject) { return this.then(undefined, onReject); } }; globalScope.Promise = Promise; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = {}; this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); PDFJS.createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } // Blob builder is deprecated in FF14 and removed in FF18. var bb = new MozBlobBuilder(); bb.append(data); return bb.getBlob(contentType); }; PDFJS.createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType) { if (!PDFJS.disableCreateObjectURL && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = PDFJS.createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(sourceName, targetName, comObj) { this.sourceName = sourceName; this.targetName = targetName; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacksCapabilities = this.callbacksCapabilities = {}; var ah = this.actionHandler = {}; this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.targetName !== this.sourceName) { return; } if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(data.error); } else { callback.resolve(data.data); } } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var sourceName = this.sourceName; var targetName = data.sourceName; Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { if (reason instanceof Error) { // Serialize error to avoid "DataCloneError" reason = reason + ''; } comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, error: reason }); }); } else { action[0].call(action[1], data.data); } } else { error('Unknown action from worker: ' + data.action); } }.bind(this); comObj.addEventListener('message', this._onComObjOnMessage); } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, transfers) { var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data }; this.postMessage(message, transfers); }, /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that other side will callback with the response. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) { var callbackId = this.callbackIndex++; var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, /** * Sends raw message to the comObj. * @private * @param message {Object} Raw message. * @param transfers List of transfers/ArrayBuffers, or undefined. */ postMessage: function (message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } }, destroy: function () { this.comObj.removeEventListener('message', this._onComObjOnMessage); } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.onerror = (function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }); img.src = imageUrl; } // Polyfill from https://github.com/Polymer/URL /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ (function checkURLConstructor(scope) { /* jshint ignore:start */ // feature detect for URL constructor var hasWorkingUrl = false; if (typeof URL === 'function' && ('origin' in URL.prototype)) { try { var u = new URL('b', 'http://a'); u.pathname = 'c%20d'; hasWorkingUrl = u.href === 'http://a/c%20d'; } catch(e) {} } if (hasWorkingUrl) return; var relative = Object.create(null); relative['ftp'] = 21; relative['file'] = 0; relative['gopher'] = 70; relative['http'] = 80; relative['https'] = 443; relative['ws'] = 80; relative['wss'] = 443; var relativePathDotMapping = Object.create(null); relativePathDotMapping['%2e'] = '.'; relativePathDotMapping['.%2e'] = '..'; relativePathDotMapping['%2e.'] = '..'; relativePathDotMapping['%2e%2e'] = '..'; function isRelativeScheme(scheme) { return relative[scheme] !== undefined; } function invalid() { clear.call(this); this._isInvalid = true; } function IDNAToASCII(h) { if ('' == h) { invalid.call(this) } // XXX return h.toLowerCase() } function percentEscape(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ? ` [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } function percentEscapeQuery(c) { // XXX This actually needs to encode c using encoding and then // convert the bytes one-by-one. var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?') [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } var EOF = undefined, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; function parse(input, stateOverride, base) { function err(message) { errors.push(message) } var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = []; loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) { var c = input[cursor]; switch (state) { case 'scheme start': if (c && ALPHA.test(c)) { buffer += c.toLowerCase(); // ASCII-safe state = 'scheme'; } else if (!stateOverride) { buffer = ''; state = 'no scheme'; continue; } else { err('Invalid scheme.'); break loop; } break; case 'scheme': if (c && ALPHANUMERIC.test(c)) { buffer += c.toLowerCase(); // ASCII-safe } else if (':' == c) { this._scheme = buffer; buffer = ''; if (stateOverride) { break loop; } if (isRelativeScheme(this._scheme)) { this._isRelative = true; } if ('file' == this._scheme) { state = 'relative'; } else if (this._isRelative && base && base._scheme == this._scheme) { state = 'relative or authority'; } else if (this._isRelative) { state = 'authority first slash'; } else { state = 'scheme data'; } } else if (!stateOverride) { buffer = ''; cursor = 0; state = 'no scheme'; continue; } else if (EOF == c) { break loop; } else { err('Code point not allowed in scheme: ' + c) break loop; } break; case 'scheme data': if ('?' == c) { this._query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } else { // XXX error handling if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._schemeData += percentEscape(c); } } break; case 'no scheme': if (!base || !(isRelativeScheme(base._scheme))) { err('Missing scheme.'); invalid.call(this); } else { state = 'relative'; continue; } break; case 'relative or authority': if ('/' == c && '/' == input[cursor+1]) { state = 'authority ignore slashes'; } else { err('Expected /, got: ' + c); state = 'relative'; continue } break; case 'relative': this._isRelative = true; if ('file' != this._scheme) this._scheme = base._scheme; if (EOF == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._username = base._username; this._password = base._password; break loop; } else if ('/' == c || '\\' == c) { if ('\\' == c) err('\\ is an invalid code point.'); state = 'relative slash'; } else if ('?' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = '?'; this._username = base._username; this._password = base._password; state = 'query'; } else if ('#' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._fragment = '#'; this._username = base._username; this._password = base._password; state = 'fragment'; } else { var nextC = input[cursor+1] var nextNextC = input[cursor+2] if ( 'file' != this._scheme || !ALPHA.test(c) || (nextC != ':' && nextC != '|') || (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; this._path = base._path.slice(); this._path.pop(); } state = 'relative path'; continue; } break; case 'relative slash': if ('/' == c || '\\' == c) { if ('\\' == c) { err('\\ is an invalid code point.'); } if ('file' == this._scheme) { state = 'file host'; } else { state = 'authority ignore slashes'; } } else { if ('file' != this._scheme) { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; } state = 'relative path'; continue; } break; case 'authority first slash': if ('/' == c) { state = 'authority second slash'; } else { err("Expected '/', got: " + c); state = 'authority ignore slashes'; continue; } break; case 'authority second slash': state = 'authority ignore slashes'; if ('/' != c) { err("Expected '/', got: " + c); continue; } break; case 'authority ignore slashes': if ('/' != c && '\\' != c) { state = 'authority'; continue; } else { err('Expected authority, got: ' + c); } break; case 'authority': if ('@' == c) { if (seenAt) { err('@ already seen.'); buffer += '%40'; } seenAt = true; for (var i = 0; i < buffer.length; i++) { var cp = buffer[i]; if ('\t' == cp || '\n' == cp || '\r' == cp) { err('Invalid whitespace in authority.'); continue; } // XXX check URL code points if (':' == cp && null === this._password) { this._password = ''; continue; } var tempC = percentEscape(cp); (null !== this._password) ? this._password += tempC : this._username += tempC; } buffer = ''; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { cursor -= buffer.length; buffer = ''; state = 'host'; continue; } else { buffer += c; } break; case 'file host': if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) { state = 'relative path'; } else if (buffer.length == 0) { state = 'relative path start'; } else { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; } continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid whitespace in file host.'); } else { buffer += c; } break; case 'host': case 'hostname': if (':' == c && !seenBracket) { // XXX host parsing this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'port'; if ('hostname' == stateOverride) { break loop; } } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; if (stateOverride) { break loop; } continue; } else if ('\t' != c && '\n' != c && '\r' != c) { if ('[' == c) { seenBracket = true; } else if (']' == c) { seenBracket = false; } buffer += c; } else { err('Invalid code point in host/hostname: ' + c); } break; case 'port': if (/[0-9]/.test(c)) { buffer += c; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) { if ('' != buffer) { var temp = parseInt(buffer, 10); if (temp != relative[this._scheme]) { this._port = temp + ''; } buffer = ''; } if (stateOverride) { break loop; } state = 'relative path start'; continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid code point in port: ' + c); } else { invalid.call(this); } break; case 'relative path start': if ('\\' == c) err("'\\' not allowed in path."); state = 'relative path'; if ('/' != c && '\\' != c) { continue; } break; case 'relative path': if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) { if ('\\' == c) { err('\\ not allowed in relative path.'); } var tmp; if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { buffer = tmp; } if ('..' == buffer) { this._path.pop(); if ('/' != c && '\\' != c) { this._path.push(''); } } else if ('.' == buffer && '/' != c && '\\' != c) { this._path.push(''); } else if ('.' != buffer) { if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') { buffer = buffer[0] + ':'; } this._path.push(buffer); } buffer = ''; if ('?' == c) { this._query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } } else if ('\t' != c && '\n' != c && '\r' != c) { buffer += percentEscape(c); } break; case 'query': if (!stateOverride && '#' == c) { this._fragment = '#'; state = 'fragment'; } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._query += percentEscapeQuery(c); } break; case 'fragment': if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._fragment += c; } break; } cursor++; } } function clear() { this._scheme = ''; this._schemeData = ''; this._username = ''; this._password = null; this._host = ''; this._port = ''; this._path = []; this._query = ''; this._fragment = ''; this._isInvalid = false; this._isRelative = false; } // Does not process domain names or IP addresses. // Does not handle encoding for the query parameter. function jURL(url, base /* , encoding */) { if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base)); this._url = url; clear.call(this); var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); // encoding = encoding || 'utf-8' parse.call(this, input, null, base); } jURL.prototype = { toString: function() { return this.href; }, get href() { if (this._isInvalid) return this._url; var authority = ''; if ('' != this._username || null != this._password) { authority = this._username + (null != this._password ? ':' + this._password : '') + '@'; } return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; }, set href(href) { clear.call(this); parse.call(this, href); }, get protocol() { return this._scheme + ':'; }, set protocol(protocol) { if (this._isInvalid) return; parse.call(this, protocol + ':', 'scheme start'); }, get host() { return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; }, set host(host) { if (this._isInvalid || !this._isRelative) return; parse.call(this, host, 'host'); }, get hostname() { return this._host; }, set hostname(hostname) { if (this._isInvalid || !this._isRelative) return; parse.call(this, hostname, 'hostname'); }, get port() { return this._port; }, set port(port) { if (this._isInvalid || !this._isRelative) return; parse.call(this, port, 'port'); }, get pathname() { return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; }, set pathname(pathname) { if (this._isInvalid || !this._isRelative) return; this._path = []; parse.call(this, pathname, 'relative path start'); }, get search() { return this._isInvalid || !this._query || '?' == this._query ? '' : this._query; }, set search(search) { if (this._isInvalid || !this._isRelative) return; this._query = '?'; if ('?' == search[0]) search = search.slice(1); parse.call(this, search, 'query'); }, get hash() { return this._isInvalid || !this._fragment || '#' == this._fragment ? '' : this._fragment; }, set hash(hash) { if (this._isInvalid) return; this._fragment = '#'; if ('#' == hash[0]) hash = hash.slice(1); parse.call(this, hash, 'fragment'); }, get origin() { var host; if (this._isInvalid || !this._scheme) { return ''; } // javascript: Gecko returns String(""), WebKit/Blink String("null") // Gecko throws error for "data://" // data: Gecko returns "", Blink returns "data://", WebKit returns "null" // Gecko returns String("") for file: mailto: // WebKit/Blink returns String("SCHEME://") for file: mailto: switch (this._scheme) { case 'data': case 'file': case 'javascript': case 'mailto': return 'null'; } host = this.host; if (!host) { return ''; } return this._scheme + '://' + host; } }; // Copy over the static methods var OriginalURL = scope.URL; if (OriginalURL) { jURL.createObjectURL = function(blob) { // IE extension allows a second optional options argument. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx return OriginalURL.createObjectURL.apply(OriginalURL, arguments); }; jURL.revokeObjectURL = function(url) { OriginalURL.revokeObjectURL(url); }; } scope.URL = jURL; /* jshint ignore:end */ })(globalScope); var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536 /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /** * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font renderer * that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will happen * automatically if the browser doesn't support workers or sending typed arrays * to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled in * development mode. If unspecified in the production build, the worker will be * loaded based on the location of the pdf.js file. It is recommended that * the workerSrc is set in a custom application to prevent issues caused by * third-party frameworks and libraries. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable streaming of PDF file data. By default PDF.js attempts to load PDF * in chunks. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableStream = (PDFJS.disableStream === undefined ? false : PDFJS.disableStream); /** * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js * will automatically keep fetching more data even if it isn't needed to display * the current page. This default behavior can be disabled. * * NOTE: It is also necessary to disable streaming, see above, * in order for disabling of pre-fetching to work correctly. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Disables fullscreen support, and by extension Presentation Mode, * in browsers which support the fullscreen API. * @var {boolean} */ PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen); /** * Enables CSS only zooming. * @var {boolean} */ PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom); /** * Controls the logging level. * The constants from PDFJS.VERBOSITY_LEVELS should be used: * - errors * - warnings [default] * - infos * @var {number} */ PDFJS.verbosity = (PDFJS.verbosity === undefined ? PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity); /** * The maximum supported canvas size in total pixels e.g. width * height. * The default value is 4096 * 4096. Use -1 for no limit. * @var {number} */ PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels); /** * (Deprecated) Opens external links in a new window if enabled. * The default behavior opens external links in the PDF.js window. * * NOTE: This property has been deprecated, please use * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead. * @var {boolean} */ PDFJS.openExternalLinksInNewWindow = ( PDFJS.openExternalLinksInNewWindow === undefined ? false : PDFJS.openExternalLinksInNewWindow); /** * Specifies the |target| attribute for external links. * The constants from PDFJS.LinkTarget should be used: * - NONE [default] * - SELF * - BLANK * - PARENT * - TOP * @var {number} */ PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ? PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget); /** * Determines if we can eval strings as JS. Primarily used to improve * performance for font rendering. * @var {boolean} */ PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported); /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded, * use atob() to convert it to a binary string first. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. * @property {number} length - The PDF file length. It's used for progress * reports and range requests operations. * @property {PDFDataRangeTransport} range * @property {number} rangeChunkSize - Optional parameter to specify * maximum number of bytes fetched per range request. The default value is * 2^16 = 65536. * @property {PDFWorker} worker - The worker that will be used for the loading * and parsing of the PDF data. */ /** * @typedef {Object} PDFDocumentStats * @property {Array} streamTypes - Used stream types in the document (an item * is set to true if specific stream ID was used in the document). * @property {Array} fontTypes - Used font type in the document (an item is set * to true if specific font ID was used in the document). */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src * Can be a url to where a PDF is located, a typed array (Uint8Array) * already populated with data or parameter object. * * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used * if you want to manually serve range requests for data in the PDF. * * @param {function} passwordCallback (deprecated) It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @param {function} progressCallback (deprecated) It is used to be able to * monitor the loading progress of the PDF file (necessary to implement e.g. * a loading bar). The callback receives an {Object} with the properties: * {number} loaded and {number} total. * * @return {PDFDocumentLoadingTask} */ PDFJS.getDocument = function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { var task = new PDFDocumentLoadingTask(); // Support of the obsolete arguments (for compatibility with API v1.0) if (arguments.length > 1) { deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument'); } if (pdfDataRangeTransport) { if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { // Not a PDFDataRangeTransport instance, trying to add missing properties. pdfDataRangeTransport = Object.create(pdfDataRangeTransport); pdfDataRangeTransport.length = src.length; pdfDataRangeTransport.initialData = src.initialData; if (!pdfDataRangeTransport.abort) { pdfDataRangeTransport.abort = function () {}; } } src = Object.create(src); src.range = pdfDataRangeTransport; } task.onPassword = passwordCallback || null; task.onProgress = progressCallback || null; var source; if (typeof src === 'string') { source = { url: src }; } else if (isArrayBuffer(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if (typeof src !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!src.url && !src.data && !src.range) { error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; var rangeTransport = null; var worker = null; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { // The full path is required in the 'url' field. params[key] = combineUrl(window.location.href, source[key]); continue; } else if (key === 'range') { rangeTransport = source[key]; continue; } else if (key === 'worker') { worker = source[key]; continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { // Converting string or array-like data to Uint8Array. var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = stringToBytes(pdfBytes); } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else if (isArrayBuffer(pdfBytes)) { params[key] = new Uint8Array(pdfBytes); } else { error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.'); } continue; } params[key] = source[key]; } params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; if (!worker) { // Worker was not provided -- creating and owning our own. worker = new PDFWorker(); task._worker = worker; } var docId = task.docId; worker.promise.then(function () { if (task.destroyed) { throw new Error('Loading aborted'); } return _fetchDocument(worker, params, rangeTransport, docId).then( function (workerId) { if (task.destroyed) { throw new Error('Loading aborted'); } var messageHandler = new MessageHandler(docId, workerId, worker.port); messageHandler.send('Ready', null); var transport = new WorkerTransport(messageHandler, task, rangeTransport); task._transport = transport; }); }, task._capability.reject); return task; }; /** * Starts fetching of specified PDF document/data. * @param {PDFWorker} worker * @param {Object} source * @param {PDFDataRangeTransport} pdfDataRangeTransport * @param {string} docId Unique document id, used as MessageHandler id. * @returns {Promise} The promise, which is resolved when worker id of * MessageHandler is known. * @private */ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { if (worker.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } source.disableAutoFetch = PDFJS.disableAutoFetch; source.disableStream = PDFJS.disableStream; source.chunkedViewerLoading = !!pdfDataRangeTransport; if (pdfDataRangeTransport) { source.length = pdfDataRangeTransport.length; source.initialData = pdfDataRangeTransport.initialData; } return worker.messageHandler.sendWithPromise('GetDocRequest', { docId: docId, source: source, disableRange: PDFJS.disableRange, maxImageSize: PDFJS.maxImageSize, cMapUrl: PDFJS.cMapUrl, cMapPacked: PDFJS.cMapPacked, disableFontFace: PDFJS.disableFontFace, disableCreateObjectURL: PDFJS.disableCreateObjectURL, verbosity: PDFJS.verbosity }).then(function (workerId) { if (worker.destroyed) { throw new Error('Worker was destroyed'); } return workerId; }); } /** * PDF document loading operation. * @class * @alias PDFDocumentLoadingTask */ var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { var nextDocumentId = 0; /** @constructs PDFDocumentLoadingTask */ function PDFDocumentLoadingTask() { this._capability = createPromiseCapability(); this._transport = null; this._worker = null; /** * Unique document loading task id -- used in MessageHandlers. * @type {string} */ this.docId = 'd' + (nextDocumentId++); /** * Shows if loading task is destroyed. * @type {boolean} */ this.destroyed = false; /** * Callback to request a password if wrong or no password was provided. * The callback receives two parameters: function that needs to be called * with new password and reason (see {PasswordResponses}). */ this.onPassword = null; /** * Callback to be able to monitor the loading progress of the PDF file * (necessary to implement e.g. a loading bar). The callback receives * an {Object} with the properties: {number} loaded and {number} total. */ this.onProgress = null; /** * Callback to when unsupported feature is used. The callback receives * an {PDFJS.UNSUPPORTED_FEATURES} argument. */ this.onUnsupportedFeature = null; } PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */ { /** * @return {Promise} */ get promise() { return this._capability.promise; }, /** * Aborts all network requests and destroys worker. * @return {Promise} A promise that is resolved after destruction activity * is completed. */ destroy: function () { this.destroyed = true; var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); return transportDestroyed.then(function () { this._transport = null; if (this._worker) { this._worker.destroy(); this._worker = null; } }.bind(this)); }, /** * Registers callbacks to indicate the document loading completion. * * @param {function} onFulfilled The callback for the loading completion. * @param {function} onRejected The callback for the loading failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; })(); /** * Abstract class to support range requests file loading. * @class * @alias PDFJS.PDFDataRangeTransport * @param {number} length * @param {Uint8Array} initialData */ var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() { function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = createPromiseCapability(); } PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */ { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { this._readyCapability.promise.then(function () { var listeners = this._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }.bind(this)); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { this._readyCapability.promise.then(function () { var listeners = this._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }.bind(this)); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); }, abort: function PDFDataRangeTransport_abort() { } }; return PDFDataRangeTransport; })(); PDFJS.PDFDataRangeTransport = PDFDataRangeTransport; /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class * @alias PDFDocumentProxy */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport, loadingTask) { this.pdfInfo = pdfInfo; this.transport = transport; this.loadingTask = loadingTask; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. * * This can be slow for large documents: use getDestination instead */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @param {string} id The named destination to get. * @return {Promise} A promise that is resolved with all information * of the given named destination. */ getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named attachments to their content. */ getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { return this.transport.getJavaScript(); }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb array, * dest: dest obj, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, /** * @return {Promise} A promise this is resolved with current stats about * document structures (see {@link PDFDocumentStats}). */ getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { return this.loadingTask.destroy(); } }; return PDFDocumentProxy; })(); /** * Page getTextContent parameters. * * @typedef {Object} getTextContentParameters * @param {boolean} normalizeWhitespace - replaces all occurrences of * whitespace with standard spaces (0x20). The default value is `false`. */ /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page annotation parameters. * * @typedef {Object} GetAnnotationsParameters * @param {string} intent - Determines the annotations that will be fetched, * can be either 'display' (viewable annotations) or 'print' * (printable annotations). * If the parameter is omitted, all annotations are fetched. */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {Array} transform - (optional) Additional transform, applied * just before viewport transform. * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (deprecated) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * PDF page operator list. * * @typedef {Object} PDFOperatorList * @property {Array} fnArray - Array containing the operator functions. * @property {Array} argsArray - Array containing the arguments of the * functions. */ /** * Proxy to a PDFPage in the worker thread. * @class * @alias PDFPageProxy */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = !!globalScope.PDFJS.enableStats; this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingCleanup = false; this.intentStates = {}; this.destroyed = false; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0); }, /** * @param {GetAnnotationsParameters} params - Annotation parameters. * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations(params) { var intent = (params && params.intent) || null; if (!this.annotationsPromise || this.annotationsIntent !== intent) { this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent); this.annotationsIntent = intent; } return this.annotationsPromise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingCleanup = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { deprecated('render is used with continueCallback parameter'); renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingCleanup) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingCleanup = true; } self._tryCleanup(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} A promise resolved with an {@link PDFOperatorList} * object that represents page's operator list. */ getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; if (!intentState.opListReadCapability) { var opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = createPromiseCapability(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, /** * @param {getTextContentParameters} params - getTextContent parameters. * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent(params) { var normalizeWhitespace = (params && params.normalizeWhitespace) || false; return this.transport.messageHandler.sendWithPromise('GetTextContent', { pageIndex: this.pageNumber - 1, normalizeWhitespace: normalizeWhitespace, }); }, /** * Destroys page object. */ _destroy: function PDFPageProxy_destroy() { this.destroyed = true; this.transport.pageCache[this.pageIndex] = null; var waitOn = []; Object.keys(this.intentStates).forEach(function(intent) { var intentState = this.intentStates[intent]; intentState.renderTasks.forEach(function(renderTask) { var renderCompleted = renderTask.capability.promise. catch(function () {}); // ignoring failures waitOn.push(renderCompleted); renderTask.cancel(); }); }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; return Promise.all(waitOn); }, /** * Cleans up resources allocated by the page. (deprecated) */ destroy: function() { deprecated('page destroy method, use cleanup() instead'); this.cleanup(); }, /** * Cleans up resources allocated by the page. */ cleanup: function PDFPageProxy_cleanup() { this.pendingCleanup = true; this._tryCleanup(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryCleanup: function PDFPageProxy_tryCleanup() { if (!this.pendingCleanup || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; // TODO Refactor RenderPageRequest to separate rendering // and operator list logic if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryCleanup(); } } }; return PDFPageProxy; })(); /** * PDF.js web worker abstraction, it controls instantiation of PDF documents and * WorkerTransport for them. If creation of a web worker is not possible, * a "fake" worker will be used instead. * @class */ var PDFWorker = (function PDFWorkerClosure() { var nextFakeWorkerId = 0; // Loads worker code into main thread. function setupFakeWorkerGlobal() { if (!PDFJS.fakeWorkerFilesLoadedCapability) { PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. Util.loadScript(PDFJS.workerSrc, function() { PDFJS.fakeWorkerFilesLoadedCapability.resolve(); }); } return PDFJS.fakeWorkerFilesLoadedCapability.promise; } function PDFWorker(name) { this.name = name; this.destroyed = false; this._readyCapability = createPromiseCapability(); this._port = null; this._webWorker = null; this._messageHandler = null; this._initialize(); } PDFWorker.prototype = /** @lends PDFWorker.prototype */ { get promise() { return this._readyCapability.promise; }, get port() { return this._port; }, get messageHandler() { return this._messageHandler; }, _initialize: function PDFWorker_initialize() { // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fullfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an // Uint8Array as it arrives on the worker. (Chrome added this with v.15.) if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { var workerSrc = PDFJS.workerSrc; if (!workerSrc) { error('No PDFJS.workerSrc specified'); } try { // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', 'worker', worker); messageHandler.on('test', function PDFWorker_test(data) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); messageHandler.destroy(); worker.terminate(); return; // worker was destroyed } var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this._messageHandler = messageHandler; this._port = worker; this._webWorker = worker; if (!data.supportTransfers) { PDFJS.postMessageTransfers = false; } this._readyCapability.resolve(); } else { this._setupFakeWorker(); messageHandler.destroy(); worker.terminate(); } }.bind(this)); messageHandler.on('console_log', function (data) { console.log.apply(console, data); }); messageHandler.on('console_error', function (data) { console.error.apply(console, data); }); var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. this._setupFakeWorker(); }, _setupFakeWorker: function PDFWorker_setupFakeWorker() { warn('Setting up fake worker.'); globalScope.PDFJS.disableWorker = true; setupFakeWorkerGlobal().then(function () { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); return; } // If we don't use a worker, just post/sendMessage to the main thread. var port = { _listeners: [], postMessage: function (obj) { var e = {data: obj}; this._listeners.forEach(function (listener) { listener.call(this, e); }, this); }, addEventListener: function (name, listener) { this._listeners.push(listener); }, removeEventListener: function (name, listener) { var i = this._listeners.indexOf(listener); this._listeners.splice(i, 1); }, terminate: function () {} }; this._port = port; // All fake workers use the same port, making id unique. var id = 'fake' + (nextFakeWorkerId++); // If the main thread is our worker, setup the handling for the // messages -- the main thread sends to it self. var workerHandler = new MessageHandler(id + '_worker', id, port); PDFJS.WorkerMessageHandler.setup(workerHandler, port); var messageHandler = new MessageHandler(id, id + '_worker', port); this._messageHandler = messageHandler; this._readyCapability.resolve(); }.bind(this)); }, /** * Destroys the worker instance. */ destroy: function PDFWorker_destroy() { this.destroyed = true; if (this._webWorker) { // We need to terminate only web worker created resource. this._webWorker.terminate(); this._webWorker = null; } this._port = null; if (this._messageHandler) { this._messageHandler.destroy(); this._messageHandler = null; } } }; return PDFWorker; })(); PDFJS.PDFWorker = PDFWorker; /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) { this.messageHandler = messageHandler; this.loadingTask = loadingTask; this.pdfDataRangeTransport = pdfDataRangeTransport; this.commonObjs = new PDFObjects(); this.fontLoader = new FontLoader(loadingTask.docId); this.destroyed = false; this.destroyCapability = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = createPromiseCapability(); this.setupMessageHandler(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { if (this.destroyCapability) { return this.destroyCapability.promise; } this.destroyed = true; this.destroyCapability = createPromiseCapability(); var waitOn = []; // We need to wait for all renderings to be completed, e.g. // timeout/rAF can take a long time. this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } }); this.pageCache = []; this.pagePromises = []; var self = this; // We also need to wait for the worker to finish its long running tasks. var terminated = this.messageHandler.sendWithPromise('Terminate', null); waitOn.push(terminated); Promise.all(waitOn).then(function () { self.fontLoader.clear(); if (self.pdfDataRangeTransport) { self.pdfDataRangeTransport.abort(); self.pdfDataRangeTransport = null; } if (self.messageHandler) { self.messageHandler.destroy(); self.messageHandler = null; } self.destroyCapability.resolve(); }, this.destroyCapability.reject); return this.destroyCapability.promise; }, setupMessageHandler: function WorkerTransport_setupMessageHandler() { var messageHandler = this.messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); pdfDataRangeTransport.addProgressiveReadListener(function(chunk) { messageHandler.send('OnDataRange', { chunk: chunk }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var loadingTask = this.loadingTask; var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask); this.pdfDocument = pdfDocument; loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportNeedPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject( new InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject( new MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject( new UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject( new UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) { if (this.pdfDataRangeTransport) { this.pdfDataRangeTransport.transportReady(); } }, this); messageHandler.on('StartRenderPage', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; var font; if ('error' in exportedData) { var error = exportedData.error; warn('Error during font loading: ' + error); this.commonObjs.resolve(id, error); break; } else { font = new FontFaceObject(exportedData); } this.fontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { error(data.error); } }, this); messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var featureId = data.featureId; var loadingTask = this.loadingTask; if (loadingTask.onUnsupportedFeature) { loadingTask.onUnsupportedFeature(featureId); } PDFJS.UnsupportedManager.notify(featureId); }, this); messageHandler.on('JpegDecode', function(data) { if (this.destroyed) { return Promise.reject('Worker was terminated'); } var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject( new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height}); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }, this); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { if (pageNumber <= 0 || pageNumber > this.numPages || (pageNumber|0) !== pageNumber) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { if (this.destroyed) { throw new Error('Transport destroyed'); } var page = new PDFPageProxy(pageIndex, pageInfo, this); this.pageCache[pageIndex] = page; return page; }.bind(this)); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex, intent: intent, }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id }); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null). then(function transportMetadata(results) { return { info: results[0], metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null) }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.sendWithPromise('Cleanup', null). then(function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.cleanup(); } } this.commonObjs.clear(); this.fontLoader.clear(); }.bind(this)); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = {}; } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: createPromiseCapability(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = {}; } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class * @alias RenderTask */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ this.onContinue = null; } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Promise for rendering task completion. * @return {Promise} */ get promise() { return this._internalRenderTask.capability.promise; }, /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, /** * Registers callbacks to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.useRequestAnimationFrame = false; this.cancelled = false; this.capability = createPromiseCapability(); this.task = new RenderTask(this); // caching this-bound methods this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); } InternalRenderTask.prototype = { initalizeGraphics: function InternalRenderTask_initalizeGraphics(transparency) { if (this.cancelled) { return; } if (PDFJS.pdfBug && 'StepperManager' in globalScope && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.transform, params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue.call(this.task, this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { if (this.useRequestAnimationFrame) { window.requestAnimationFrame(this._nextBound); } else { Promise.resolve(undefined).then(this._nextBound); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); /** * (Deprecated) Global observer of unsupported feature usages. Use * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance. */ PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead'); listeners.push(cb); }, notify: function (featureId) { for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); var Metadata = PDFJS.Metadata = (function MetadataClosure() { function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = {}; this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; return Metadata; })(); // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; // Maximum font size that would be used during canvas fillText operations. var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; // Heuristic value used when enforcing minimum line widths. var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based one. if (!ctx.mozCurrentTransform) { ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { function CachedCanvases() { this.cache = Object.create(null); } CachedCanvases.prototype = { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (this.cache[id] !== undefined) { canvasEntry = this.cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } this.cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { for (var id in this.cache) { var canvasEntry = this.cache[id]; // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. canvasEntry.canvas.width = 0; canvasEntry.canvas.height = 0; delete this.cache[id]; } } }; return CachedCanvases; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; // Defines the number of steps before checking the execution time var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; this.cachedCanvases = new CachedCanvases(); if (canvasCtx) { // NOTE: if mozCurrentTransform is polyfilled, then the current state of // the transformation must already be set in canvasCtx._transformMatrix. addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var srcLength = src.byteLength; var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } else if (sourceCtx.mozDashOffset !== undefined) { destCtx.mozDash = sourceCtx.mozDash; destCtx.mozDashOffset = sourceCtx.mozDashOffset; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8; } } } function composeSMaskAlpha(maskData, layerData, transferMap) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; layerData[i] = (layerData[i] * alpha * scale) | 0; } } function composeSMaskLuminosity(maskData, layerData, transferMap) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskData[i - 2] * 152) + // * 0.59 .... (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = transferMap ? (layerData[i] * transferMap[y >> 8]) >> 8 : (layerData[i] * y) >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data, transferMap); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (!smask.transferMap && WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, creating temporary // transparent canvas when we have blend modes. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); if (transparency) { var transparentCanvas = this.cachedCanvases.getCanvas( 'transparent', width, height, true); this.compositeCtx = this.ctx; this.transparentCanvas = transparentCanvas.canvas; this.ctx = transparentCanvas.context; this.ctx.save(); // The transform can be applied before rendering, transferring it to // the new canvas. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); } this.ctx.save(); if (transform) { this.ctx.transform.apply(this.ctx, transform); } this.ctx.transform.apply(this.ctx, viewport.transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen === i) { return i; } var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'); var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i === argsArrayLen) { return i; } // If the execution took longer then a certain amount of time and // `continueCallback` is specified, interrupt the execution. if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { this.ctx.restore(); if (this.transparentCanvas) { this.ctx = this.compositeCtx; this.ctx.drawImage(this.transparentCanvas, 0, 0); this.transparentCanvas = null; } this.cachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { this.endSMaskGroup(); } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); copyCtxState(groupCtx, this.ctx); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.activeSMask = null; }, restore: function CanvasGraphics_restore() { if (this.stateStack.length !== 0) { if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.current = this.stateStack.pop(); this.ctx.restore(); // Ensure that the clipping path is reset (fixes issue6413.pdf). this.pendingClip = null; this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, // Path constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; // Prevent drawing too thin lines by enforcing a minimum line width. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); if (this.baseTransform) { ctx.setTransform.apply(ctx, this.baseTransform); } ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.fill(); ctx.mozFillRule = 'nonzero'; } else { ctx.fill('evenodd'); } this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var spacingDir = vertical ? 1 : -1; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (isNum(glyph)) { x += spacingDir * glyph * fontSize / 1000; continue; } var restoreNeeded = false; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0) { // Some standard fonts may not have the exact width: rescale per // character if measured width is greater than expected glyph width // and subpixel-aa is enabled, otherwise just center the glyph. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; if (width < measuredWidth && this.isFontSubpixelAAEnabled) { var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } else if (width !== measuredWidth) { scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; } } if (simpleFillText && !accent) { // common case ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } var charWidth = width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { // Type3 fonts - each glyph is a "mini-PDF" var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var spacingDir = font.vertical ? 1 : -1; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width, spacingLength; if (isTextInvisible || fontSize === 0) { return; } this.cachedGetSinglePixelWidth = null; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (isNum(glyph)) { spacingLength = spacingDir * glyph * fontSize / 1000; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { warn('Type3 character \"' + glyph.operatorListId + '\" is not available'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + spacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); pattern = new TilingPattern(IR, color, this.ctx, this.objs, this.commonObjs, baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (isArray(matrix) && 6 === matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (isArray(bbox) && 4 === bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implmenting: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, transferMap: group.smask.transferMap || null }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (isArray(rect) && 4 === rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, paintXObject: function CanvasGraphics_paintXObject() { warn('Unsupported \'paintXObject\' command.'); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.clip(); ctx.mozFillRule = 'nonzero'; } else { ctx.clip('evenodd'); } } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { var inverse = this.ctx.mozCurrentTransformInverse; // max of the current horizontal and vertical scale this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[j]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if (PDFJS.disableWebGL) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); tmpCanvas.context.drawImage(canvas, 0, 0); canvas = tmpCanvas.canvas; } else { tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, 0, 0); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { //var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; //var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { // Obtain scale from matrix and current transformation matrix. scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.objs = objs; this.commonObjs = commonObjs; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var objs = this.objs; var commonObjs = this.commonObjs; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); function FontLoader(docId) { this.docId = docId; this.styleElement = null; this.nativeFontFaces = []; this.loadTestFontId = 0; this.loadingContext = { requests: [], nextRequestId: 0 }; } FontLoader.prototype = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = this.styleElement; if (!styleElement) { styleElement = this.styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = this.styleElement; if (styleElement) { styleElement.parentNode.removeChild(styleElement); styleElement = this.styleElement = null; } this.nativeFontFaces.forEach(function(nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }, bind: function fontLoaderBind(fonts, callback) { assert(!isWorker, 'bind() shall be called from main thread'); var rules = []; var fontsToLoad = []; var fontLoadPromises = []; var getNativeFontPromise = function(nativeFontFace) { // Return a promise that is always fulfilled, even when the font fails to // load. return nativeFontFace.loaded.catch(function(e) { warn('Failed to load font "' + nativeFontFace.family + '": ' + e); }); }; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; if (FontLoader.isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { this.addNativeFontFace(nativeFontFace); fontLoadPromises.push(getNativeFontPromise(nativeFontFace)); } } else { var rule = font.createFontFaceRule(); if (rule) { this.insertRule(rule); rules.push(rule); fontsToLoad.push(font); } } } var request = this.queueLoadingCallback(callback); if (FontLoader.isFontLoadingAPISupported) { Promise.all(fontLoadPromises).then(function() { request.complete(); }); } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) { this.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = this.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; this.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; FontLoader.isFontLoadingAPISupported = (!isWorker && typeof document !== 'undefined' && !!document.fonts); Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', { get: function () { var supported = false; // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var userAgent = window.navigator.userAgent; var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent); if (m && m[1] >= 14) { supported = true; } // TODO other browsers if (userAgent === 'node') { supported = true; } return shadow(FontLoader, 'isSyncFontLoadingSupported', supported); }, enumerable: true, configurable: true }); var FontFaceObject = (function FontFaceObjectClosure() { function FontFaceObject(translatedData) { this.compiledGlyphs = {}; // importing translated data for (var i in translatedData) { this[i] = translatedData[i]; } } Object.defineProperty(FontFaceObject, 'isEvalSupported', { get: function () { var evalSupport = false; if (PDFJS.isEvalSupported) { try { /* jshint evil: true */ new Function(''); evalSupport = true; } catch (e) {} } return shadow(this, 'isEvalSupported', evalSupport); }, enumerable: true, configurable: true }); FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this); } return nativeFontFace; }, createFontFaceRule: function FontFaceObject_createFontFaceRule() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + window.btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this, url); } return rule; }, getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var cmds = objs.get(this.loadedName + '_path_' + character); var current, i, len; // If we can, compile cmds into JS for MAXIMUM SPEED if (FontFaceObject.isEvalSupported) { var args, js = ''; for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.args !== undefined) { args = current.args.join(','); } else { args = ''; } js += 'c.' + current.cmd + '(' + args + ');\n'; } /* jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } else { // But fall back on using Function.prototype.apply() if we're // blocked from using eval() for whatever reason (like CSP policies) this.compiledGlyphs[character] = function(c, size) { for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.cmd === 'scale') { current.args = [size, -size]; } c[current.cmd].apply(c, current.args); } }; } } return this.compiledGlyphs[character]; } }; return FontFaceObject; })(); /** * Optimised CSS custom property getter/setter. * @class */ var CustomStyle = (function CustomStyleClosure() { // As noted on: http://www.zachstronaut.com/posts/2009/02/17/ // animate-css-transforms-firefox-webkit.html // in some versions of IE9 it is critical that ms appear in this list // before Moz var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var _cache = {}; function CustomStyle() {} CustomStyle.getProp = function get(propName, element) { // check cache only when no element is given if (arguments.length === 1 && typeof _cache[propName] === 'string') { return _cache[propName]; } element = element || document.documentElement; var style = element.style, prefixed, uPropName; // test standard property first if (typeof style[propName] === 'string') { return (_cache[propName] = propName); } // capitalize uPropName = propName.charAt(0).toUpperCase() + propName.slice(1); // test vendor specific properties for (var i = 0, l = prefixes.length; i < l; i++) { prefixed = prefixes[i] + uPropName; if (typeof style[prefixed] === 'string') { return (_cache[propName] = prefixed); } } //if all fails then set to undefined return (_cache[propName] = 'undefined'); }; CustomStyle.setProp = function set(propName, element, str) { var prop = this.getProp(propName); if (prop !== 'undefined') { element.style[prop] = str; } }; return CustomStyle; })(); PDFJS.CustomStyle = CustomStyle; var ANNOT_MIN_SIZE = 10; // px var AnnotationLayer = (function AnnotationLayerClosure() { // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont() function setTextStyles(element, item, fontObj) { var style = element.style; style.fontSize = item.fontSize + 'px'; style.direction = item.fontDirection < 0 ? 'rtl': 'ltr'; if (!fontObj) { return; } style.fontWeight = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); style.fontStyle = fontObj.italic ? 'italic' : 'normal'; var fontName = fontObj.loadedName; var fontFamily = fontName ? '"' + fontName + '", ' : ''; // Use a reasonable default font if the font doesn't specify a fallback var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } function getContainer(data, page, viewport) { var container = document.createElement('section'); var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; container.setAttribute('data-annotation-id', data.id); data.rect = Util.normalizeRect([ data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1] ]); CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')'); CustomStyle.setProp('transformOrigin', container, -data.rect[0] + 'px ' + -data.rect[1] + 'px'); if (data.borderStyle.width > 0) { container.style.borderWidth = data.borderStyle.width + 'px'; if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) { // Underline styles only have a bottom border, so we do not need // to adjust for all borders. This yields a similar result as // Adobe Acrobat/Reader. width = width - 2 * data.borderStyle.width; height = height - 2 * data.borderStyle.width; } var horizontalRadius = data.borderStyle.horizontalCornerRadius; var verticalRadius = data.borderStyle.verticalCornerRadius; if (horizontalRadius > 0 || verticalRadius > 0) { var radius = horizontalRadius + 'px / ' + verticalRadius + 'px'; CustomStyle.setProp('borderRadius', container, radius); } switch (data.borderStyle.style) { case AnnotationBorderStyleType.SOLID: container.style.borderStyle = 'solid'; break; case AnnotationBorderStyleType.DASHED: container.style.borderStyle = 'dashed'; break; case AnnotationBorderStyleType.BEVELED: warn('Unimplemented border style: beveled'); break; case AnnotationBorderStyleType.INSET: warn('Unimplemented border style: inset'); break; case AnnotationBorderStyleType.UNDERLINE: container.style.borderBottomStyle = 'solid'; break; default: break; } if (data.color) { container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); } else { // Transparent (invisible) border, so do not draw it at all. container.style.borderWidth = 0; } } container.style.left = data.rect[0] + 'px'; container.style.top = data.rect[1] + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; return container; } function getHtmlElementForTextWidgetAnnotation(item, page) { var element = document.createElement('div'); var width = item.rect[2] - item.rect[0]; var height = item.rect[3] - item.rect[1]; element.style.width = width + 'px'; element.style.height = height + 'px'; element.style.display = 'table'; var content = document.createElement('div'); content.textContent = item.fieldValue; var textAlignment = item.textAlignment; content.style.textAlign = ['left', 'center', 'right'][textAlignment]; content.style.verticalAlign = 'middle'; content.style.display = 'table-cell'; var fontObj = item.fontRefName ? page.commonObjs.getData(item.fontRefName) : null; setTextStyles(content, item, fontObj); element.appendChild(content); return element; } function getHtmlElementForTextAnnotation(item, page, viewport) { var rect = item.rect; // sanity check because of OOo-generated PDFs if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) { rect[3] = rect[1] + ANNOT_MIN_SIZE; } if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) { rect[2] = rect[0] + (rect[3] - rect[1]); // make it square } var container = getContainer(item, page, viewport); container.className = 'annotText'; var image = document.createElement('img'); image.style.height = container.style.height; image.style.width = container.style.width; var iconName = item.name; image.src = PDFJS.imageResourcesPath + 'annotation-' + iconName.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: iconName}); var contentWrapper = document.createElement('div'); contentWrapper.className = 'annotTextContentWrapper'; contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px'; contentWrapper.style.top = '-10px'; var content = document.createElement('div'); content.className = 'annotTextContent'; content.setAttribute('hidden', true); var i, ii; if (item.hasBgColor && item.color) { var color = item.color; // Enlighten the color (70%) var BACKGROUND_ENLIGHT = 0.7; var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; content.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0); } var title = document.createElement('h1'); var text = document.createElement('p'); title.textContent = item.title; if (!item.content && !item.title) { content.setAttribute('hidden', true); } else { var e = document.createElement('span'); var lines = item.content.split(/(?:\r\n?|\n)/); for (i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; e.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { e.appendChild(document.createElement('br')); } } text.appendChild(e); var pinned = false; var showAnnotation = function showAnnotation(pin) { if (pin) { pinned = true; } if (content.hasAttribute('hidden')) { container.style.zIndex += 1; content.removeAttribute('hidden'); } }; var hideAnnotation = function hideAnnotation(unpin) { if (unpin) { pinned = false; } if (!content.hasAttribute('hidden') && !pinned) { container.style.zIndex -= 1; content.setAttribute('hidden', true); } }; var toggleAnnotation = function toggleAnnotation() { if (pinned) { hideAnnotation(true); } else { showAnnotation(true); } }; image.addEventListener('click', function image_clickHandler() { toggleAnnotation(); }, false); image.addEventListener('mouseover', function image_mouseOverHandler() { showAnnotation(); }, false); image.addEventListener('mouseout', function image_mouseOutHandler() { hideAnnotation(); }, false); content.addEventListener('click', function content_clickHandler() { hideAnnotation(true); }, false); } content.appendChild(title); content.appendChild(text); contentWrapper.appendChild(content); container.appendChild(image); container.appendChild(contentWrapper); return container; } function getHtmlElementForLinkAnnotation(item, page, viewport, linkService) { function bindLink(link, dest) { link.href = linkService.getDestinationHash(dest); link.onclick = function annotationsLayerBuilderLinksOnclick() { if (dest) { linkService.navigateTo(dest); } return false; }; if (dest) { link.className = 'internalLink'; } } function bindNamedAction(link, action) { link.href = linkService.getAnchorUrl(''); link.onclick = function annotationsLayerBuilderNamedActionOnClick() { linkService.executeNamedAction(action); return false; }; link.className = 'internalLink'; } var container = getContainer(item, page, viewport); container.className = 'annotLink'; var link = document.createElement('a'); link.href = link.title = item.url || ''; if (item.url && isExternalLinkTargetSet()) { link.target = LinkTargetStringMap[PDFJS.externalLinkTarget]; } if (!item.url) { if (item.action) { bindNamedAction(link, item.action); } else { bindLink(link, ('dest' in item) ? item.dest : null); } } container.appendChild(link); return container; } function getHtmlElement(data, page, viewport, linkService) { switch (data.annotationType) { case AnnotationType.WIDGET: return getHtmlElementForTextWidgetAnnotation(data, page); case AnnotationType.TEXT: return getHtmlElementForTextAnnotation(data, page, viewport); case AnnotationType.LINK: return getHtmlElementForLinkAnnotation(data, page, viewport, linkService); default: throw new Error('Unsupported annotationType: ' + data.annotationType); } } function render(viewport, div, annotations, page, linkService) { for (var i = 0, ii = annotations.length; i < ii; i++) { var data = annotations[i]; if (!data || !data.hasHtml) { continue; } var element = getHtmlElement(data, page, viewport, linkService); div.appendChild(element); } } function update(viewport, div, annotations) { for (var i = 0, ii = annotations.length; i < ii; i++) { var data = annotations[i]; var element = div.querySelector( '[data-annotation-id="' + data.id + '"]'); if (element) { CustomStyle.setProp('transform', element, 'matrix(' + viewport.transform.join(',') + ')'); } } div.removeAttribute('hidden'); } return { render: render, update: update }; })(); PDFJS.AnnotationLayer = AnnotationLayer; /** * Text layer render parameters. * * @typedef {Object} TextLayerRenderParameters * @property {TextContent} textContent - Text content to render (the object is * returned by the page's getTextContent() method). * @property {HTMLElement} container - HTML element that will contain text runs. * @property {PDFJS.PageViewport} viewport - The target viewport to properly * layout the text runs. * @property {Array} textDivs - (optional) HTML elements that are correspond * the text items of the textContent input. This is output and shall be * initially be set to empty array. * @property {number} timeout - (optional) Delay in milliseconds before * rendering of the text runs occurs. */ var renderTextLayer = (function renderTextLayerClosure() { var MAX_TEXT_DIVS_TO_RENDER = 100000; var NonWhitespaceRegexp = /\S/; function isAllWhitespace(str) { return !NonWhitespaceRegexp.test(str); } function appendText(textDivs, viewport, geom, styles) { var style = styles[geom.fontName]; var textDiv = document.createElement('div'); textDivs.push(textDiv); if (isAllWhitespace(geom.str)) { textDiv.dataset.isWhitespace = true; return; } var tx = PDFJS.Util.transform(viewport.transform, geom.transform); var angle = Math.atan2(tx[1], tx[0]); if (style.vertical) { angle += Math.PI / 2; } var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3])); var fontAscent = fontHeight; if (style.ascent) { fontAscent = style.ascent * fontAscent; } else if (style.descent) { fontAscent = (1 + style.descent) * fontAscent; } var left; var top; if (angle === 0) { left = tx[4]; top = tx[5] - fontAscent; } else { left = tx[4] + (fontAscent * Math.sin(angle)); top = tx[5] - (fontAscent * Math.cos(angle)); } textDiv.style.left = left + 'px'; textDiv.style.top = top + 'px'; textDiv.style.fontSize = fontHeight + 'px'; textDiv.style.fontFamily = style.fontFamily; textDiv.textContent = geom.str; // |fontName| is only used by the Font Inspector. This test will succeed // when e.g. the Font Inspector is off but the Stepper is on, but it's // not worth the effort to do a more accurate test. if (PDFJS.pdfBug) { textDiv.dataset.fontName = geom.fontName; } // Storing into dataset will convert number into string. if (angle !== 0) { textDiv.dataset.angle = angle * (180 / Math.PI); } // We don't bother scaling single-char text divs, because it has very // little effect on text highlighting. This makes scrolling on docs with // lots of such divs a lot faster. if (geom.str.length > 1) { if (style.vertical) { textDiv.dataset.canvasWidth = geom.height * viewport.scale; } else { textDiv.dataset.canvasWidth = geom.width * viewport.scale; } } } function render(task) { if (task._canceled) { return; } var textLayerFrag = task._container; var textDivs = task._textDivs; var capability = task._capability; var textDivsLength = textDivs.length; // No point in rendering many divs as it would make the browser // unusable even after the divs are rendered. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { capability.resolve(); return; } var canvas = document.createElement('canvas'); canvas.mozOpaque = true; var ctx = canvas.getContext('2d', {alpha: false}); var lastFontSize; var lastFontFamily; for (var i = 0; i < textDivsLength; i++) { var textDiv = textDivs[i]; if (textDiv.dataset.isWhitespace !== undefined) { continue; } var fontSize = textDiv.style.fontSize; var fontFamily = textDiv.style.fontFamily; // Only build font string and set to context if different from last. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) { ctx.font = fontSize + ' ' + fontFamily; lastFontSize = fontSize; lastFontFamily = fontFamily; } var width = ctx.measureText(textDiv.textContent).width; if (width > 0) { textLayerFrag.appendChild(textDiv); var transform; if (textDiv.dataset.canvasWidth !== undefined) { // Dataset values come of type string. var textScale = textDiv.dataset.canvasWidth / width; transform = 'scaleX(' + textScale + ')'; } else { transform = ''; } var rotation = textDiv.dataset.angle; if (rotation) { transform = 'rotate(' + rotation + 'deg) ' + transform; } if (transform) { PDFJS.CustomStyle.setProp('transform' , textDiv, transform); } } } capability.resolve(); } /** * Text layer rendering task. * * @param {TextContent} textContent * @param {HTMLElement} container * @param {PDFJS.PageViewport} viewport * @param {Array} textDivs * @private */ function TextLayerRenderTask(textContent, container, viewport, textDivs) { this._textContent = textContent; this._container = container; this._viewport = viewport; textDivs = textDivs || []; this._textDivs = textDivs; this._canceled = false; this._capability = createPromiseCapability(); this._renderTimer = null; } TextLayerRenderTask.prototype = { get promise() { return this._capability.promise; }, cancel: function TextLayer_cancel() { this._canceled = true; if (this._renderTimer !== null) { clearTimeout(this._renderTimer); this._renderTimer = null; } this._capability.reject('canceled'); }, _render: function TextLayer_render(timeout) { var textItems = this._textContent.items; var styles = this._textContent.styles; var textDivs = this._textDivs; var viewport = this._viewport; for (var i = 0, len = textItems.length; i < len; i++) { appendText(textDivs, viewport, textItems[i], styles); } if (!timeout) { // Render right away render(this); } else { // Schedule var self = this; this._renderTimer = setTimeout(function() { render(self); self._renderTimer = null; }, timeout); } } }; /** * Starts rendering of the text layer. * * @param {TextLayerRenderParameters} renderParameters * @returns {TextLayerRenderTask} */ function renderTextLayer(renderParameters) { var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs); task._render(renderParameters.timeout); return task; } return renderTextLayer; })(); PDFJS.renderTextLayer = renderTextLayer; var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = (function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); } else { c = (c >> 1) & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = (crc >>> 8) ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } function encode(imgData, kind) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = (width + 7) >> 3; break; case ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } // prefix every row with predictor 0 var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; // no prediction literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === ImageKind.GRAYSCALE_1BPP) { // inverting for B/W offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; // skipping predictor for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([ width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, // bit depth colorType, // color type 0x00, // compression method 0x00, // filter method 0x00 // interlace method ]); var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; // compression method and flags idat[pi++] = 0x9c; // flags var pos = 0; while (len > maxBlockLength) { // writing non-final DEFLATE blocks type 0 and length of 65535 idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } // writing non-final DEFLATE blocks type 0 idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = (~len & 0xffff) & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); // checksum idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; // PNG will consists: header, IHDR+data, IDAT+data, and IEND. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return PDFJS.createObjectURL(data, 'image/png'); } return function convertImgDataToPng(imgData) { var kind = (imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind); return encode(imgData, kind); }; })(); var SVGExtraState = (function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; // Default foreground and background colors this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; // Clipping this.clipId = ''; this.pendingClip = false; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; })(); var SVGGraphics = (function SVGGraphicsClosure() { function createScratchSVG(width, height) { var NS = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(NS, 'svg:svg'); svg.setAttributeNS(null, 'version', '1.1'); svg.setAttributeNS(null, 'width', width + 'px'); svg.setAttributeNS(null, 'height', height + 'px'); svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height); return svg; } function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({'fnId': 92, 'fn': 'group', 'items': []}); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if(opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } /** * Formats float number. * @param value {number} number to format. * @returns {string} */ function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } /** * Formats transform matrix. The standard rotation, scale and translate * matrices are replaced by their shorter forms, and for identity matrix * returns empty string to save the memory. * @param m {Array} matrix to format. * @returns {string} */ function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs) { this.current = new SVGExtraState(); this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = {}; this.cssStyle = null; } var NS = 'http://www.w3.org/2000/svg'; var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.pgrp.appendChild(this.tgrp); }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; var self = this; for (var i = 0; i < fnArrayLen; i++) { if (OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function(resolve) { self.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function(resolve) { self.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = PDFJS.Util.transform(this.transformMatrix, transformMatrix); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { this.svg = createScratchSVG(viewport.width, viewport.height); this.viewport = viewport; return this.loadDependencies(operatorList).then(function () { this.transformMatrix = IDENTITY_MATRIX; this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform)); this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.defs = document.createElementNS(NS, 'svg:defs'); this.pgrp.appendChild(this.defs); this.pgrp.appendChild(this.tgrp); this.svg.appendChild(this.pgrp); var opTree = this.convertOpList(operatorList); this.executeOpTree(opTree); return this.svg; }.bind(this)); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in OPS) { REVOPS[OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]}); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for(var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case OPS.beginText: this.beginText(); break; case OPS.setLeading: this.setLeading(args); break; case OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case OPS.setFont: this.setFont(args); break; case OPS.showText: this.showText(args[0]); break; case OPS.showSpacedText: this.showText(args[0]); break; case OPS.endText: this.endText(); break; case OPS.moveText: this.moveText(args[0], args[1]); break; case OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case OPS.setHScale: this.setHScale(args[0]); break; case OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setLineWidth: this.setLineWidth(args[0]); break; case OPS.setLineJoin: this.setLineJoin(args[0]); break; case OPS.setLineCap: this.setLineCap(args[0]); break; case OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case OPS.setDash: this.setDash(args[0], args[1]); break; case OPS.setGState: this.setGState(args[0]); break; case OPS.fill: this.fill(); break; case OPS.eoFill: this.eoFill(); break; case OPS.stroke: this.stroke(); break; case OPS.fillStroke: this.fillStroke(); break; case OPS.eoFillStroke: this.eoFillStroke(); break; case OPS.clip: this.clip('nonzero'); break; case OPS.eoClip: this.clip('evenodd'); break; case OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case OPS.closePath: this.closePath(); break; case OPS.closeStroke: this.closeStroke(); break; case OPS.closeFillStroke: this.closeFillStroke(); break; case OPS.nextLine: this.nextLine(); break; case OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.constructPath: this.constructPath(args[0], args[1]); break; case OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: warn('Unimplemented method '+ fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = document.createElementNS(NS, 'svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = IDENTITY_MATRIX; this.current.lineMatrix = IDENTITY_MATRIX; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.txtElement = document.createElementNS(NS, 'svg:text'); this.current.txtgrp = document.createElementNS(NS, 'svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } current.xcoords.push(current.x + x * textHScale); var width = glyph.width; var character = glyph.fontChar; var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; current.tspan.textContent += character; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)' ); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this.tgrp.appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = document.createElementNS(NS, 'svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() { if (this.current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, // Path properties setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = document.createElementNS(NS, 'svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x) , pf(y)); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.path.setAttributeNS(null, 'fill', 'none'); this.tgrp.appendChild(current.path); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } // Saving a reference in current.element so that it can be addressed // in 'fill' and 'stroke' current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { var current = this.current; if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, clip: function SVGGraphics_clip(type) { var current = this.current; // Add current path to clipping path current.clipId = 'clippath' + clipCount; clipCount++; this.clippath = document.createElementNS(NS, 'svg:clipPath'); this.clippath.setAttributeNS(null, 'id', current.clipId); var clipElement = current.element.cloneNode(); if (type === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.clippath.appendChild(clipElement); this.defs.appendChild(this.clippath); // Create a new group with that attribute current.pendingClip = true; this.cgrp = document.createElementNS(NS, 'svg:g'); this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')'); this.pgrp.appendChild(this.cgrp); }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': break; case 'FL': break; case 'Font': this.setFont(value); break; case 'CA': break; case 'ca': break; case 'BM': break; case 'SMask': break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); }, fillStroke: function SVGGraphics_fillStroke() { // Order is important since stroke wants fill to be none. // First stroke, then if fill needed, it will be overwritten. this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this.tgrp.appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var current = this.current; var imgObj = this.objs.get(objId); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', imgObj.width + 'px'); imgEl.setAttributeNS(null, 'height', imgObj.height + 'px'); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this.tgrp.appendChild(imgEl); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var current = this.current; var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData); var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); current.element = cliprect; this.clip('nonzero'); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this.tgrp.appendChild(imgEl); } if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = document.createElementNS(NS, 'svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')'); this.defs.appendChild(mask); this.tgrp.appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); if (isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() { this.restore(); } }; return SVGGraphics; })(); PDFJS.SVGGraphics = SVGGraphics; }).call((typeof window === 'undefined') ? this : window); if (!PDFJS.workerSrc && typeof document !== 'undefined') { // workerSrc is not set -- using last script url to define default location PDFJS.workerSrc = (function () { 'use strict'; var pdfJsSrc = document.currentScript.src; return pdfJsSrc && pdfJsSrc.replace(/\.js$/i, '.worker.js'); })(); }
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/mode-ejs.js
2,941
ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|async|await|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode "[0-2][0-7]{0,2}|" + // oct "3[0-7][0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ DocCommentHighlightRules.getStartRule("doc-start"), comments("no_regex"), { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "punctuation.operator", regex : /[.](?![.])/, next : "property" }, { token : "keyword.operator", regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], property: [{ token : "text", regex : "\\s+" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", next: "function_arguments" }, { token : "punctuation.operator", regex : /[.](?![.])/ }, { token : "support.function", regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : "support.function.dom", regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : "support.constant", regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : "identifier", regex : identifierRe }, { regex: "", token: "empty", next: "no_regex" } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("start"), { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); } else if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); if (!options || options.jsx != false) JSX.call(this); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); function JSX() { var tagRegex = identifierRe.replace("\\d", "\\d\\-"); var jsxTag = { onMatch : function(val, state, stack) { var offset = val.charAt(1) == "/" ? 2 : 1; if (offset == 1) { if (state != this.nextState) stack.unshift(this.next, this.nextState, 0); else stack.unshift(this.next); stack[2]++; } else if (offset == 2) { if (state == this.nextState) { stack[1]--; if (!stack[1] || stack[1] < 0) { stack.shift(); stack.shift(); } } } return [{ type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", value: val.slice(0, offset) }, { type: "meta.tag.tag-name.xml", value: val.substr(offset) }]; }, regex : "</?" + tagRegex + "", next: "jsxAttributes", nextState: "jsx" }; this.$rules.start.unshift(jsxTag); var jsxJsRule = { regex: "{", token: "paren.quasi.start", push: "start" }; this.$rules.jsx = [ jsxJsRule, jsxTag, {include : "reference"}, {defaultToken: "string"} ]; this.$rules.jsxAttributes = [{ token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", onMatch : function(value, currentState, stack) { if (currentState == stack[0]) stack.shift(); if (value.length == 2) { if (stack[0] == this.nextState) stack[1]--; if (!stack[1] || stack[1] < 0) { stack.splice(0, 2); } } this.next = stack[0] || "start"; return [{type: this.token, value: value}]; }, nextState: "jsx" }, jsxJsRule, comments("jsxAttributes"), { token : "entity.other.attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { token : "text.tag-whitespace.xml", regex : "\\s+" }, { token : "string.attribute-value.xml", regex : "'", stateName : "jsx_attr_q", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', stateName : "jsx_attr_qq", push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, jsxTag ]; this.$rules.reference = [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }]; } function comments(next) { return [ { token : "comment", // multi line comment regex : /\/\*/, next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] }, { token : "comment", regex : "\\/\\/", next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] } ]; } exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_completions",["require","exports","module"], function(require, exports, module) { "use strict"; var propertyMap = { "background": {"#$0": 1}, "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, "background-image": {"url('/$0')": 1}, "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, "background-attachment": {"scroll": 1, "fixed": 1}, "background-size": {"cover": 1, "contain": 1}, "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, "border-color": {"#$0": 1}, "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, "border-collapse": {"collapse": 1, "separate": 1}, "bottom": {"px": 1, "em": 1, "%": 1}, "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, "empty-cells": {"show": 1, "hide": 1}, "float": {"left": 1, "right": 1, "none": 1}, "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, "font-size": {"px": 1, "em": 1, "%": 1}, "font-weight": {"bold": 1, "normal": 1}, "font-style": {"italic": 1, "normal": 1}, "font-variant": {"normal": 1, "small-caps": 1}, "height": {"px": 1, "em": 1, "%": 1}, "left": {"px": 1, "em": 1, "%": 1}, "letter-spacing": {"normal": 1}, "line-height": {"normal": 1}, "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, "margin": {"px": 1, "em": 1, "%": 1}, "margin-right": {"px": 1, "em": 1, "%": 1}, "margin-left": {"px": 1, "em": 1, "%": 1}, "margin-top": {"px": 1, "em": 1, "%": 1}, "margin-bottom": {"px": 1, "em": 1, "%": 1}, "max-height": {"px": 1, "em": 1, "%": 1}, "max-width": {"px": 1, "em": 1, "%": 1}, "min-height": {"px": 1, "em": 1, "%": 1}, "min-width": {"px": 1, "em": 1, "%": 1}, "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "padding": {"px": 1, "em": 1, "%": 1}, "padding-top": {"px": 1, "em": 1, "%": 1}, "padding-right": {"px": 1, "em": 1, "%": 1}, "padding-bottom": {"px": 1, "em": 1, "%": 1}, "padding-left": {"px": 1, "em": 1, "%": 1}, "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, "right": {"px": 1, "em": 1, "%": 1}, "table-layout": {"fixed": 1, "auto": 1}, "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, "top": {"px": 1, "em": 1, "%": 1}, "vertical-align": {"top": 1, "bottom": 1}, "visibility": {"hidden": 1, "visible": 1}, "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, "width": {"px": 1, "em": 1, "%": 1}, "word-spacing": {"normal": 1}, "filter": {"alpha(opacity=$0100)": 1}, "text-shadow": {"$02px 2px 2px #777": 1}, "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, "-moz-border-radius": 1, "-moz-border-radius-topright": 1, "-moz-border-radius-bottomright": 1, "-moz-border-radius-topleft": 1, "-moz-border-radius-bottomleft": 1, "-webkit-border-radius": 1, "-webkit-border-top-right-radius": 1, "-webkit-border-top-left-radius": 1, "-webkit-border-bottom-right-radius": 1, "-webkit-border-bottom-left-radius": 1, "-moz-box-shadow": 1, "-webkit-box-shadow": 1, "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } }; var CssCompletions = function() { }; (function() { this.completionsDefined = false; this.defineCompletions = function() { if (document) { var style = document.createElement('c').style; for (var i in style) { if (typeof style[i] !== 'string') continue; var name = i.replace(/[A-Z]/g, function(x) { return '-' + x.toLowerCase(); }); if (!propertyMap.hasOwnProperty(name)) propertyMap[name] = 1; } } this.completionsDefined = true; } this.getCompletions = function(state, session, pos, prefix) { if (!this.completionsDefined) { this.defineCompletions(); } var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (state==='ruleset'){ var line = session.getLine(pos.row).substr(0, pos.column); if (/:[^;]+$/.test(line)) { /([\w\-]+):[^:]*$/.test(line); return this.getPropertyValueCompletions(state, session, pos, prefix); } else { return this.getPropertyCompletions(state, session, pos, prefix); } } return []; }; this.getPropertyCompletions = function(state, session, pos, prefix) { var properties = Object.keys(propertyMap); return properties.map(function(property){ return { caption: property, snippet: property + ': $0', meta: "property", score: Number.MAX_VALUE }; }); }; this.getPropertyValueCompletions = function(state, session, pos, prefix) { var line = session.getLine(pos.row).substr(0, pos.column); var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; if (!property) return []; var values = []; if (property in propertyMap && typeof propertyMap[property] === "object") { values = Object.keys(propertyMap[property]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "property value", score: Number.MAX_VALUE }; }); }; }).call(CssCompletions.prototype); exports.CssCompletions = CssCompletions; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssCompletions = require("./css_completions").CssCompletions; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.$completer = new CssCompletions(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": {"manifest": 1}, "head": {}, "title": {}, "base": {"href": 1, "target": 1}, "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, "noscript": {"href": 1}, "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, "section": {}, "nav": {}, "article": {"pubdate": 1}, "aside": {}, "h1": {}, "h2": {}, "h3": {}, "h4": {}, "h5": {}, "h6": {}, "header": {}, "footer": {}, "address": {}, "main": {}, "p": {}, "hr": {}, "pre": {}, "blockquote": {"cite": 1}, "ol": {"start": 1, "reversed": 1}, "ul": {}, "li": {"value": 1}, "dl": {}, "dt": {}, "dd": {}, "figure": {}, "figcaption": {}, "div": {}, "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, "em": {}, "strong": {}, "small": {}, "s": {}, "cite": {}, "q": {"cite": 1}, "dfn": {}, "abbr": {}, "data": {}, "time": {"datetime": 1}, "code": {}, "var": {}, "samp": {}, "kbd": {}, "sub": {}, "sup": {}, "i": {}, "b": {}, "u": {}, "mark": {}, "ruby": {}, "rt": {}, "rp": {}, "bdi": {}, "bdo": {}, "span": {}, "br": {}, "wbr": {}, "ins": {"cite": 1, "datetime": 1}, "del": {"cite": 1, "datetime": 1}, "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, "param": {"name": 1, "value": 1}, "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, "source": {"src": 1, "type": 1, "media": 1}, "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, "canvas": {"width": 1, "height": 1}, "map": {"name": 1}, "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, "svg": {}, "math": {}, "table": {"summary": 1}, "caption": {}, "colgroup": {"span": 1}, "col": {"span": 1}, "tbody": {}, "thead": {}, "tfoot": {}, "tr": {}, "td": {"headers": 1, "rowspan": 1, "colspan": 1}, "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, "fieldset": {"disabled": 1, "form": 1, "name": 1}, "legend": {}, "label": {"form": 1, "for": 1}, "input": { "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, "datalist": {}, "optgroup": {"disabled": 1, "label": 1}, "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, "output": {"for": 1, "form": 1, "name": 1}, "progress": {"value": 1, "max": 1}, "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, "details": {"open": 1}, "summary": {}, "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, "menu": {"type": 1, "label": 1}, "dialog": {"open": 1} }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } function findAttributeName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "attribute-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompletions(state, session, pos, prefix); if (is(token, "attribute-value")) return this.getAttributeValueCompletions(state, session, pos, prefix); var line = session.getLine(pos.row).substr(0, pos.column); if (/&[A-z]*$/i.test(line)) return this.getHTMLEntityCompletions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(Object.keys(attributeMap[tagName])); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; this.getAttributeValueCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); var attributeName = findAttributeName(session, pos); if (!tagName) return []; var values = []; if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { values = Object.keys(attributeMap[tagName][attributeName]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "attribute value", score: Number.MAX_VALUE }; }); }; this.getHTMLEntityCompletions = function(state, session, pos, prefix) { var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; return values.map(function(value){ return { caption: value, snippet: value, meta: "html entity", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/ruby_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var constantOtherSymbol = exports.constantOtherSymbol = { token : "constant.other.symbol.ruby", // symbol regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?" }; var qString = exports.qString = { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }; var qqString = exports.qqString = { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }; var tString = exports.tString = { token : "string", // backtick string regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]" }; var constantNumericHex = exports.constantNumericHex = { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b" }; var constantNumericFloat = exports.constantNumericFloat = { token : "constant.numeric", // float regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b" }; var RubyHighlightRules = function() { var builtinFunctions = ( "abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" + "assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" + "assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" + "assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" + "assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" + "assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" + "attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" + "caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" + "exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" + "gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" + "link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" + "p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" + "raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" + "set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" + "throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" + "render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" + "content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" + "fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" + "time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" + "select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" + "file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" + "protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" + "send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" + "validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" + "validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" + "authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" + "filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" + "translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" + "cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" + "has_many|has_one|belongs_to|has_and_belongs_to_many" ); var keywords = ( "alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" + "__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" + "redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield" ); var buildinConstants = ( "true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" + "RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING" ); var builtinVariables = ( "$DEBUG|$defout|$FILENAME|$LOAD_PATH|$SAFE|$stdin|$stdout|$stderr|$VERBOSE|" + "$!|root_url|flash|session|cookies|params|request|response|logger|self" ); var keywordMapper = this.$keywords = this.createKeywordMapper({ "keyword": keywords, "constant.language": buildinConstants, "variable.language": builtinVariables, "support.function": builtinFunctions, "invalid.deprecated": "debugger" // TODO is this a remnant from js mode? }, "identifier"); this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "comment", // multi line comment regex : "^=begin(?:$|\\s.*$)", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, [{ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); return "paren.lparen"; } if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1) return "paren.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.start", regex : /"/, push : [{ token : "constant.language.escape", regex : /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/ }, { token : "paren.start", regex : /#{/, push : "start" }, { token : "string.end", regex : /"/, next : "pop" }, { defaultToken: "string" }] }, { token : "string.start", regex : /`/, push : [{ token : "constant.language.escape", regex : /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/ }, { token : "paren.start", regex : /#{/, push : "start" }, { token : "string.end", regex : /`/, next : "pop" }, { defaultToken: "string" }] }, { token : "string.start", regex : /'/, push : [{ token : "constant.language.escape", regex : /\\['\\]/ }, { token : "string.end", regex : /'/, next : "pop" }, { defaultToken: "string" }] }], { token : "text", // namespaces aren't symbols regex : "::" }, { token : "variable.instance", // instance variable regex : "@{1,2}[a-zA-Z_\\d]+" }, { token : "support.class", // class name regex : "[A-Z][a-zA-Z_\\d]+" }, constantOtherSymbol, constantNumericHex, constantNumericFloat, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "punctuation.separator.key-value", regex : "=>" }, { stateName: "heredoc", onMatch : function(value, currentState, stack) { var next = value[2] == '-' ? "indentedHeredoc" : "heredoc"; var tokens = value.split(this.splitRegex); stack.push(next, tokens[3]); return [ {type:"constant", value: tokens[1]}, {type:"string", value: tokens[2]}, {type:"support.class", value: tokens[3]}, {type:"string", value: tokens[4]} ]; }, regex : "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)", rules: { heredoc: [{ onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }], indentedHeredoc: [{ token: "string", regex: "^ +" }, { onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }] } }, { regex : "$", token : "empty", next : function(currentState, stack) { if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc") return stack[0]; return currentState; } }, { token : "string.character", regex : "\\B\\?." }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : "^=end(?:$|\\s.*$)", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ] }; this.normalizeRules(); }; oop.inherits(RubyHighlightRules, TextHighlightRules); exports.RubyHighlightRules = RubyHighlightRules; }); ace.define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != "#") return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != "#") break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent!= -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start"; else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start"; else return ""; }; }).call(FoldMode.prototype); }); ace.define("ace/mode/ruby",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/ruby_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/coffee"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var FoldMode = require("./folding/coffee").FoldMode; var Mode = function() { this.HighlightRules = RubyHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new FoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); var startingClassOrMethod = line.match(/^\s*(class|def|module)\s.*$/); var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/); var startingConditional = line.match(/^\s*(if|else|when)\s*/) if (match || startingClassOrMethod || startingDoBlock || startingConditional) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return /^\s+(end|else)$/.test(line + input) || this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, session, row) { var line = session.getLine(row); if (/}/.test(line)) return this.$outdent.autoOutdent(session, row); var indent = this.$getIndent(line); var prevLine = session.getLine(row - 1); var prevIndent = this.$getIndent(prevLine); var tab = session.getTabString(); if (prevIndent.length <= indent.length) { if (indent.slice(-tab.length) == tab) session.remove(new Range(row, indent.length-tab.length, row, indent.length)); } }; this.$id = "ace/mode/ruby"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/ejs",["require","exports","module","ace/lib/oop","ace/mode/html_highlight_rules","ace/mode/javascript_highlight_rules","ace/lib/oop","ace/mode/html","ace/mode/javascript","ace/mode/css","ace/mode/ruby"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var EjsHighlightRules = function(start, end) { HtmlHighlightRules.call(this); if (!start) start = "(?:<%|<\\?|{{)"; if (!end) end = "(?:%>|\\?>|}})"; for (var i in this.$rules) { this.$rules[i].unshift({ token : "markup.list.meta.tag", regex : start + "(?![>}])[-=]?", push : "ejs-start" }); } this.embedRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "ejs-", [{ token : "markup.list.meta.tag", regex : "-?" + end, next : "pop" }, { token: "comment", regex: "//.*?" + end, next: "pop" }]); this.normalizeRules(); }; oop.inherits(EjsHighlightRules, HtmlHighlightRules); exports.EjsHighlightRules = EjsHighlightRules; var oop = require("../lib/oop"); var HtmlMode = require("./html").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var RubyMode = require("./ruby").Mode; var Mode = function() { HtmlMode.call(this); this.HighlightRules = EjsHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode, "ejs-": JavaScriptMode }); }; oop.inherits(Mode, HtmlMode); (function() { this.$id = "ace/mode/ejs"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/libs/pdfjs-1.6.210p1/pdf.js
11,515
/* Copyright 2012 Mozilla Foundation * * 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. */ /* jshint globalstrict: false */ /* umdutils ignore */ (function (root, factory) { 'use strict'; if (typeof define === 'function' && define.amd) { define('pdfjs-dist/build/pdf', ['exports'], factory); } else if (typeof exports !== 'undefined') { factory(exports); } else { factory((root.pdfjsDistBuildPdf = {})); } }(this, function (exports) { // Use strict in our context only - users might not want it 'use strict'; var pdfjsVersion = '1.6.210'; var pdfjsBuild = '4ce2356'; var pdfjsFilePath = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : null; var pdfjsLibs = {}; (function pdfjsWrapper() { (function (root, factory) { { factory((root.pdfjsSharedUtil = {})); } }(this, function (exports) { var globalScope = (typeof window !== 'undefined') ? window : (typeof global !== 'undefined') ? global : (typeof self !== 'undefined') ? self : this; var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { TEXT: 1, LINK: 2, FREETEXT: 3, LINE: 4, SQUARE: 5, CIRCLE: 6, POLYGON: 7, POLYLINE: 8, HIGHLIGHT: 9, UNDERLINE: 10, SQUIGGLY: 11, STRIKEOUT: 12, STAMP: 13, CARET: 14, INK: 15, POPUP: 16, FILEATTACHMENT: 17, SOUND: 18, MOVIE: 19, WIDGET: 20, SCREEN: 21, PRINTERMARK: 22, TRAPNET: 23, WATERMARK: 24, THREED: 25, REDACT: 26 }; var AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, PRINT: 0x04, NOZOOM: 0x08, NOROTATE: 0x10, NOVIEW: 0x20, READONLY: 0x40, LOCKED: 0x80, TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; var AnnotationFieldFlag = { READONLY: 0x0000001, REQUIRED: 0x0000002, NOEXPORT: 0x0000004, MULTILINE: 0x0001000, PASSWORD: 0x0002000, NOTOGGLETOOFF: 0x0004000, RADIO: 0x0008000, PUSHBUTTON: 0x0010000, COMBO: 0x0020000, EDIT: 0x0040000, SORT: 0x0080000, FILESELECT: 0x0100000, MULTISELECT: 0x0200000, DONOTSPELLCHECK: 0x0400000, DONOTSCROLL: 0x0800000, COMB: 0x1000000, RICHTEXT: 0x2000000, RADIOSINUNISON: 0x2000000, COMMITONSELCHANGE: 0x4000000, }; var AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, BEVELED: 3, INSET: 4, UNDERLINE: 5 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; var VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; var verbosity = VERBOSITY_LEVELS.warnings; function setVerbosityLevel(level) { verbosity = level; } function getVerbosityLevel() { return verbosity; } // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (verbosity >= VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (verbosity >= VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Deprecated API function -- display regardless of the PDFJS.verbosity setting. function deprecated(details) { console.log('Deprecated API usage: ' + details); } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { if (verbosity >= VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; // Checks if URLs have the same origin. For non-HTTP based URLs, returns false. function isSameOrigin(baseUrl, otherUrl) { try { var base = new URL(baseUrl); if (!base.origin || base.origin === 'null') { return false; // non-HTTP url } } catch (e) { return false; } var other = new URL(otherUrl, base); return base.origin === other.origin; } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url || typeof url !== 'string') { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': case 'tel': return true; default: return false; } } function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } function getLookupTableFactory(initializer) { var lookup; return function () { if (initializer) { lookup = Object.create(null); initializer(lookup); initializer = null; } return lookup; }; } var PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); var UnexpectedResponseException = (function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; })(); var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); var NullCharactersRegExp = /\x00/g; function removeNullCharacters(str) { if (typeof str !== 'string') { warn('The argument for removeNullCharacters must be a string.'); return str; } return str.replace(NullCharactersRegExp, ''); } function bytesToString(bytes) { assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } /** * Gets length of the array (Array, Uint8Array, or string) in bytes. * @param {Array|Uint8Array|string} arr * @returns {number} */ function arrayByteLength(arr) { if (arr.length !== undefined) { return arr.length; } assert(arr.byteLength !== undefined); return arr.byteLength; } /** * Combines array items (arrays) into single Uint8Array object. * @param {Array} arr - the array of the arrays (Array, Uint8Array, or string). * @returns {Uint8Array} */ function arraysToBytes(arr) { // Shortcut: if first and only item is Uint8Array, return it. if (arr.length === 1 && (arr[0] instanceof Uint8Array)) { return arr[0]; } var resultLength = 0; var i, ii = arr.length; var item, itemLength ; for (i = 0; i < ii; i++) { item = arr[i]; itemLength = arrayByteLength(item); resultLength += itemLength; } var pos = 0; var data = new Uint8Array(resultLength); for (i = 0; i < ii; i++) { item = arr[i]; if (!(item instanceof Uint8Array)) { if (typeof item === 'string') { item = stringToBytes(item); } else { item = new Uint8Array(item); } } itemLength = item.byteLength; data.set(item, pos); pos += itemLength; } return data; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return (data[start] << 24) >> 24; } function readUint16(data, offset) { return (data[offset] << 8) | data[offset + 1]; } function readUint32(data, offset) { return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } // Checks if it's possible to eval JS expressions. function isEvalSupported() { try { /* jshint evil: true */ new Function(''); return true; } catch (e) { return false; } } var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); exports.Uint32ArrayView = Uint32ArrayView; var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = (function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; var ROMAN_NUMBER_MAP = [ '', 'C', 'CC', 'CCC', 'CD', 'D', 'DC', 'DCC', 'DCCC', 'CM', '', 'X', 'XX', 'XXX', 'XL', 'L', 'LX', 'LXX', 'LXXX', 'XC', '', 'I', 'II', 'III', 'IV', 'V', 'VI', 'VII', 'VIII', 'IX' ]; /** * Converts positive integers to (upper case) Roman numerals. * @param {integer} number - The number that should be converted. * @param {boolean} lowerCase - Indicates if the result should be converted * to lower case letters. The default is false. * @return {string} The resulting Roman number. */ Util.toRoman = function Util_toRoman(number, lowerCase) { assert(isInt(number) && number > 0, 'The number should be a positive integer.'); var pos, romanBuf = []; // Thousands while (number >= 1000) { number -= 1000; romanBuf.push('M'); } // Hundreds pos = (number / 100) | 0; number %= 100; romanBuf.push(ROMAN_NUMBER_MAP[pos]); // Tens pos = (number / 10) | 0; number %= 10; romanBuf.push(ROMAN_NUMBER_MAP[10 + pos]); // Ones romanBuf.push(ROMAN_NUMBER_MAP[20 + number]); var romanStr = romanBuf.join(''); return (lowerCase ? romanStr.toLowerCase() : romanStr); }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); /** * PDF page viewport created based on scale, rotation and offset. * @class * @alias PageViewport */ var PageViewport = (function PageViewportClosure() { /** * @constructor * @private * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. * @param scale {number} scale of the viewport. * @param rotation {number} rotations of the viewport in degrees. * @param offsetX {number} offset X * @param offsetY {number} offset Y * @param dontFlip {boolean} if true, axis Y will not be flipped. */ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = /** @lends PageViewport.prototype */ { /** * Clones viewport with additional properties. * @param args {Object} (optional) If specified, may contain the 'scale' or * 'rotation' properties to override the corresponding properties in * the cloned viewport. * @returns {PageViewport} Cloned viewport. */ clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, /** * Converts PDF rectangle to the viewport coordinates. * @param rect {Array} xMin, yMin, xMax and yMax coordinates. * @returns {Array} Contains corresponding coordinates of the rectangle * in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isInt(v) { return typeof v === 'number' && ((v | 0) === v); } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isArray(v) { return v instanceof Array; } function isArrayBuffer(v) { return typeof v === 'object' && v !== null && v.byteLength !== undefined; } // Checks if ch is one of the following characters: SPACE, TAB, CR or LF. function isSpace(ch) { return (ch === 0x20 || ch === 0x09 || ch === 0x0D || ch === 0x0A); } /** * Promise Capability object. * * @typedef {Object} PromiseCapability * @property {Promise} promise - A promise object. * @property {function} resolve - Fulfills the promise. * @property {function} reject - Rejects the promise. */ /** * Creates a promise capability object. * @alias createPromiseCapability * * @return {PromiseCapability} A capability object contains: * - a Promise, resolve and reject methods. */ function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } /** * Polyfill for Promises: * The following promise implementation tries to generally implement the * Promise/A+ spec. Some notable differences from other promise libraries are: * - There currently isn't a separate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (value) { return new globalScope.Promise(function (resolve) { resolve(value); }); }; } if (typeof globalScope.Promise.reject !== 'function') { globalScope.Promise.reject = function (reason) { return new globalScope.Promise(function (resolve, reject) { reject(reason); }); }; } if (typeof globalScope.Promise.prototype.catch !== 'function') { globalScope.Promise.prototype.catch = function (onReject) { return globalScope.Promise.prototype.then(undefined, onReject); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status === STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof handler.onResolve === 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof handler.onReject === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; try { resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } catch (e) { this._reject(e); } } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} promises array of data and/or promises to wait for. * @return {Promise} New dependent promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if value is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param value resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(value) { return new Promise(function (resolve) { resolve(value); }); }; /** * Creates rejected promise * @param reason rejection value * @returns {Promise} */ Promise.reject = function Promise_reject(reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status === STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = resolve; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; }, catch: function Promise_catch(onReject) { return this.then(undefined, onReject); } }; globalScope.Promise = Promise; })(); (function WeakMapClosure() { if (globalScope.WeakMap) { return; } var id = 0; function WeakMap() { this.id = '$weakmap' + (id++); } WeakMap.prototype = { has: function(obj) { return !!Object.getOwnPropertyDescriptor(obj, this.id); }, get: function(obj, defaultValue) { return this.has(obj) ? obj[this.id] : defaultValue; }, set: function(obj, value) { Object.defineProperty(obj, this.id, { value: value, enumerable: false, configurable: true }); }, delete: function(obj) { delete obj[this.id]; } }; globalScope.WeakMap = WeakMap; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = Object.create(null); this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); var createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } warn('The "Blob" constructor is not supported.'); }; var createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType, forceDataSchema) { if (!forceDataSchema && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(sourceName, targetName, comObj) { this.sourceName = sourceName; this.targetName = targetName; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacksCapabilities = this.callbacksCapabilities = Object.create(null); var ah = this.actionHandler = Object.create(null); this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.targetName !== this.sourceName) { return; } if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(data.error); } else { callback.resolve(data.data); } } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var sourceName = this.sourceName; var targetName = data.sourceName; Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { if (reason instanceof Error) { // Serialize error to avoid "DataCloneError" reason = reason + ''; } comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, error: reason }); }); } else { action[0].call(action[1], data.data); } } else { error('Unknown action from worker: ' + data.action); } }.bind(this); comObj.addEventListener('message', this._onComObjOnMessage); } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, transfers) { var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data }; this.postMessage(message, transfers); }, /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that other side will callback with the response. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) { var callbackId = this.callbackIndex++; var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, /** * Sends raw message to the comObj. * @private * @param message {Object} Raw message. * @param transfers List of transfers/ArrayBuffers, or undefined. */ postMessage: function (message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } }, destroy: function () { this.comObj.removeEventListener('message', this._onComObjOnMessage); } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.onerror = (function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }); img.src = imageUrl; } // Polyfill from https://github.com/Polymer/URL /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ (function checkURLConstructor(scope) { // feature detect for URL constructor var hasWorkingUrl = false; try { if (typeof URL === 'function' && typeof URL.prototype === 'object' && ('origin' in URL.prototype)) { var u = new URL('b', 'http://a'); u.pathname = 'c%20d'; hasWorkingUrl = u.href === 'http://a/c%20d'; } } catch(e) { } if (hasWorkingUrl) { return; } var relative = Object.create(null); relative['ftp'] = 21; relative['file'] = 0; relative['gopher'] = 70; relative['http'] = 80; relative['https'] = 443; relative['ws'] = 80; relative['wss'] = 443; var relativePathDotMapping = Object.create(null); relativePathDotMapping['%2e'] = '.'; relativePathDotMapping['.%2e'] = '..'; relativePathDotMapping['%2e.'] = '..'; relativePathDotMapping['%2e%2e'] = '..'; function isRelativeScheme(scheme) { return relative[scheme] !== undefined; } function invalid() { clear.call(this); this._isInvalid = true; } function IDNAToASCII(h) { if ('' === h) { invalid.call(this); } // XXX return h.toLowerCase(); } function percentEscape(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ? ` [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) === -1 ) { return c; } return encodeURIComponent(c); } function percentEscapeQuery(c) { // XXX This actually needs to encode c using encoding and then // convert the bytes one-by-one. var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?') [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) === -1 ) { return c; } return encodeURIComponent(c); } var EOF, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; function parse(input, stateOverride, base) { function err(message) { errors.push(message); } var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = []; loop: while ((input[cursor - 1] !== EOF || cursor === 0) && !this._isInvalid) { var c = input[cursor]; switch (state) { case 'scheme start': if (c && ALPHA.test(c)) { buffer += c.toLowerCase(); // ASCII-safe state = 'scheme'; } else if (!stateOverride) { buffer = ''; state = 'no scheme'; continue; } else { err('Invalid scheme.'); break loop; } break; case 'scheme': if (c && ALPHANUMERIC.test(c)) { buffer += c.toLowerCase(); // ASCII-safe } else if (':' === c) { this._scheme = buffer; buffer = ''; if (stateOverride) { break loop; } if (isRelativeScheme(this._scheme)) { this._isRelative = true; } if ('file' === this._scheme) { state = 'relative'; } else if (this._isRelative && base && base._scheme === this._scheme) { state = 'relative or authority'; } else if (this._isRelative) { state = 'authority first slash'; } else { state = 'scheme data'; } } else if (!stateOverride) { buffer = ''; cursor = 0; state = 'no scheme'; continue; } else if (EOF === c) { break loop; } else { err('Code point not allowed in scheme: ' + c); break loop; } break; case 'scheme data': if ('?' === c) { this._query = '?'; state = 'query'; } else if ('#' === c) { this._fragment = '#'; state = 'fragment'; } else { // XXX error handling if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) { this._schemeData += percentEscape(c); } } break; case 'no scheme': if (!base || !(isRelativeScheme(base._scheme))) { err('Missing scheme.'); invalid.call(this); } else { state = 'relative'; continue; } break; case 'relative or authority': if ('/' === c && '/' === input[cursor+1]) { state = 'authority ignore slashes'; } else { err('Expected /, got: ' + c); state = 'relative'; continue; } break; case 'relative': this._isRelative = true; if ('file' !== this._scheme) { this._scheme = base._scheme; } if (EOF === c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._username = base._username; this._password = base._password; break loop; } else if ('/' === c || '\\' === c) { if ('\\' === c) { err('\\ is an invalid code point.'); } state = 'relative slash'; } else if ('?' === c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = '?'; this._username = base._username; this._password = base._password; state = 'query'; } else if ('#' === c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._fragment = '#'; this._username = base._username; this._password = base._password; state = 'fragment'; } else { var nextC = input[cursor+1]; var nextNextC = input[cursor+2]; if ('file' !== this._scheme || !ALPHA.test(c) || (nextC !== ':' && nextC !== '|') || (EOF !== nextNextC && '/' !== nextNextC && '\\' !== nextNextC && '?' !== nextNextC && '#' !== nextNextC)) { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; this._path = base._path.slice(); this._path.pop(); } state = 'relative path'; continue; } break; case 'relative slash': if ('/' === c || '\\' === c) { if ('\\' === c) { err('\\ is an invalid code point.'); } if ('file' === this._scheme) { state = 'file host'; } else { state = 'authority ignore slashes'; } } else { if ('file' !== this._scheme) { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; } state = 'relative path'; continue; } break; case 'authority first slash': if ('/' === c) { state = 'authority second slash'; } else { err('Expected \'/\', got: ' + c); state = 'authority ignore slashes'; continue; } break; case 'authority second slash': state = 'authority ignore slashes'; if ('/' !== c) { err('Expected \'/\', got: ' + c); continue; } break; case 'authority ignore slashes': if ('/' !== c && '\\' !== c) { state = 'authority'; continue; } else { err('Expected authority, got: ' + c); } break; case 'authority': if ('@' === c) { if (seenAt) { err('@ already seen.'); buffer += '%40'; } seenAt = true; for (var i = 0; i < buffer.length; i++) { var cp = buffer[i]; if ('\t' === cp || '\n' === cp || '\r' === cp) { err('Invalid whitespace in authority.'); continue; } // XXX check URL code points if (':' === cp && null === this._password) { this._password = ''; continue; } var tempC = percentEscape(cp); if (null !== this._password) { this._password += tempC; } else { this._username += tempC; } } buffer = ''; } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) { cursor -= buffer.length; buffer = ''; state = 'host'; continue; } else { buffer += c; } break; case 'file host': if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) { if (buffer.length === 2 && ALPHA.test(buffer[0]) && (buffer[1] === ':' || buffer[1] === '|')) { state = 'relative path'; } else if (buffer.length === 0) { state = 'relative path start'; } else { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; } continue; } else if ('\t' === c || '\n' === c || '\r' === c) { err('Invalid whitespace in file host.'); } else { buffer += c; } break; case 'host': case 'hostname': if (':' === c && !seenBracket) { // XXX host parsing this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'port'; if ('hostname' === stateOverride) { break loop; } } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c) { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; if (stateOverride) { break loop; } continue; } else if ('\t' !== c && '\n' !== c && '\r' !== c) { if ('[' === c) { seenBracket = true; } else if (']' === c) { seenBracket = false; } buffer += c; } else { err('Invalid code point in host/hostname: ' + c); } break; case 'port': if (/[0-9]/.test(c)) { buffer += c; } else if (EOF === c || '/' === c || '\\' === c || '?' === c || '#' === c || stateOverride) { if ('' !== buffer) { var temp = parseInt(buffer, 10); if (temp !== relative[this._scheme]) { this._port = temp + ''; } buffer = ''; } if (stateOverride) { break loop; } state = 'relative path start'; continue; } else if ('\t' === c || '\n' === c || '\r' === c) { err('Invalid code point in port: ' + c); } else { invalid.call(this); } break; case 'relative path start': if ('\\' === c) { err('\'\\\' not allowed in path.'); } state = 'relative path'; if ('/' !== c && '\\' !== c) { continue; } break; case 'relative path': if (EOF === c || '/' === c || '\\' === c || (!stateOverride && ('?' === c || '#' === c))) { if ('\\' === c) { err('\\ not allowed in relative path.'); } var tmp; if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { buffer = tmp; } if ('..' === buffer) { this._path.pop(); if ('/' !== c && '\\' !== c) { this._path.push(''); } } else if ('.' === buffer && '/' !== c && '\\' !== c) { this._path.push(''); } else if ('.' !== buffer) { if ('file' === this._scheme && this._path.length === 0 && buffer.length === 2 && ALPHA.test(buffer[0]) && buffer[1] === '|') { buffer = buffer[0] + ':'; } this._path.push(buffer); } buffer = ''; if ('?' === c) { this._query = '?'; state = 'query'; } else if ('#' === c) { this._fragment = '#'; state = 'fragment'; } } else if ('\t' !== c && '\n' !== c && '\r' !== c) { buffer += percentEscape(c); } break; case 'query': if (!stateOverride && '#' === c) { this._fragment = '#'; state = 'fragment'; } else if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) { this._query += percentEscapeQuery(c); } break; case 'fragment': if (EOF !== c && '\t' !== c && '\n' !== c && '\r' !== c) { this._fragment += c; } break; } cursor++; } } function clear() { this._scheme = ''; this._schemeData = ''; this._username = ''; this._password = null; this._host = ''; this._port = ''; this._path = []; this._query = ''; this._fragment = ''; this._isInvalid = false; this._isRelative = false; } // Does not process domain names or IP addresses. // Does not handle encoding for the query parameter. function JURL(url, base /* , encoding */) { if (base !== undefined && !(base instanceof JURL)) { base = new JURL(String(base)); } this._url = url; clear.call(this); var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); // encoding = encoding || 'utf-8' parse.call(this, input, null, base); } JURL.prototype = { toString: function() { return this.href; }, get href() { if (this._isInvalid) { return this._url; } var authority = ''; if ('' !== this._username || null !== this._password) { authority = this._username + (null !== this._password ? ':' + this._password : '') + '@'; } return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; }, set href(href) { clear.call(this); parse.call(this, href); }, get protocol() { return this._scheme + ':'; }, set protocol(protocol) { if (this._isInvalid) { return; } parse.call(this, protocol + ':', 'scheme start'); }, get host() { return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; }, set host(host) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, host, 'host'); }, get hostname() { return this._host; }, set hostname(hostname) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, hostname, 'hostname'); }, get port() { return this._port; }, set port(port) { if (this._isInvalid || !this._isRelative) { return; } parse.call(this, port, 'port'); }, get pathname() { return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; }, set pathname(pathname) { if (this._isInvalid || !this._isRelative) { return; } this._path = []; parse.call(this, pathname, 'relative path start'); }, get search() { return this._isInvalid || !this._query || '?' === this._query ? '' : this._query; }, set search(search) { if (this._isInvalid || !this._isRelative) { return; } this._query = '?'; if ('?' === search[0]) { search = search.slice(1); } parse.call(this, search, 'query'); }, get hash() { return this._isInvalid || !this._fragment || '#' === this._fragment ? '' : this._fragment; }, set hash(hash) { if (this._isInvalid) { return; } this._fragment = '#'; if ('#' === hash[0]) { hash = hash.slice(1); } parse.call(this, hash, 'fragment'); }, get origin() { var host; if (this._isInvalid || !this._scheme) { return ''; } // javascript: Gecko returns String(""), WebKit/Blink String("null") // Gecko throws error for "data://" // data: Gecko returns "", Blink returns "data://", WebKit returns "null" // Gecko returns String("") for file: mailto: // WebKit/Blink returns String("SCHEME://") for file: mailto: switch (this._scheme) { case 'data': case 'file': case 'javascript': case 'mailto': return 'null'; } host = this.host; if (!host) { return ''; } return this._scheme + '://' + host; } }; // Copy over the static methods var OriginalURL = scope.URL; if (OriginalURL) { JURL.createObjectURL = function(blob) { // IE extension allows a second optional options argument. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx return OriginalURL.createObjectURL.apply(OriginalURL, arguments); }; JURL.revokeObjectURL = function(url) { OriginalURL.revokeObjectURL(url); }; } scope.URL = JURL; })(globalScope); exports.FONT_IDENTITY_MATRIX = FONT_IDENTITY_MATRIX; exports.IDENTITY_MATRIX = IDENTITY_MATRIX; exports.OPS = OPS; exports.VERBOSITY_LEVELS = VERBOSITY_LEVELS; exports.UNSUPPORTED_FEATURES = UNSUPPORTED_FEATURES; exports.AnnotationBorderStyleType = AnnotationBorderStyleType; exports.AnnotationFieldFlag = AnnotationFieldFlag; exports.AnnotationFlag = AnnotationFlag; exports.AnnotationType = AnnotationType; exports.FontType = FontType; exports.ImageKind = ImageKind; exports.InvalidPDFException = InvalidPDFException; exports.MessageHandler = MessageHandler; exports.MissingDataException = MissingDataException; exports.MissingPDFException = MissingPDFException; exports.NotImplementedException = NotImplementedException; exports.PageViewport = PageViewport; exports.PasswordException = PasswordException; exports.PasswordResponses = PasswordResponses; exports.StatTimer = StatTimer; exports.StreamType = StreamType; exports.TextRenderingMode = TextRenderingMode; exports.UnexpectedResponseException = UnexpectedResponseException; exports.UnknownErrorException = UnknownErrorException; exports.Util = Util; exports.XRefParseException = XRefParseException; exports.arrayByteLength = arrayByteLength; exports.arraysToBytes = arraysToBytes; exports.assert = assert; exports.bytesToString = bytesToString; exports.createBlob = createBlob; exports.createPromiseCapability = createPromiseCapability; exports.createObjectURL = createObjectURL; exports.deprecated = deprecated; exports.error = error; exports.getLookupTableFactory = getLookupTableFactory; exports.getVerbosityLevel = getVerbosityLevel; exports.globalScope = globalScope; exports.info = info; exports.isArray = isArray; exports.isArrayBuffer = isArrayBuffer; exports.isBool = isBool; exports.isEmptyObj = isEmptyObj; exports.isInt = isInt; exports.isNum = isNum; exports.isString = isString; exports.isSpace = isSpace; exports.isSameOrigin = isSameOrigin; exports.isValidUrl = isValidUrl; exports.isLittleEndian = isLittleEndian; exports.isEvalSupported = isEvalSupported; exports.loadJpegStream = loadJpegStream; exports.log2 = log2; exports.readInt8 = readInt8; exports.readUint16 = readUint16; exports.readUint32 = readUint32; exports.removeNullCharacters = removeNullCharacters; exports.setVerbosityLevel = setVerbosityLevel; exports.shadow = shadow; exports.string32 = string32; exports.stringToBytes = stringToBytes; exports.stringToPDFString = stringToPDFString; exports.stringToUTF8String = stringToUTF8String; exports.utf8StringToString = utf8StringToString; exports.warn = warn; })); (function (root, factory) { { factory((root.pdfjsDisplayDOMUtils = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var removeNullCharacters = sharedUtil.removeNullCharacters; var warn = sharedUtil.warn; /** * Optimised CSS custom property getter/setter. * @class */ var CustomStyle = (function CustomStyleClosure() { // As noted on: http://www.zachstronaut.com/posts/2009/02/17/ // animate-css-transforms-firefox-webkit.html // in some versions of IE9 it is critical that ms appear in this list // before Moz var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var _cache = Object.create(null); function CustomStyle() {} CustomStyle.getProp = function get(propName, element) { // check cache only when no element is given if (arguments.length === 1 && typeof _cache[propName] === 'string') { return _cache[propName]; } element = element || document.documentElement; var style = element.style, prefixed, uPropName; // test standard property first if (typeof style[propName] === 'string') { return (_cache[propName] = propName); } // capitalize uPropName = propName.charAt(0).toUpperCase() + propName.slice(1); // test vendor specific properties for (var i = 0, l = prefixes.length; i < l; i++) { prefixed = prefixes[i] + uPropName; if (typeof style[prefixed] === 'string') { return (_cache[propName] = prefixed); } } //if all fails then set to undefined return (_cache[propName] = 'undefined'); }; CustomStyle.setProp = function set(propName, element, str) { var prop = this.getProp(propName); if (prop !== 'undefined') { element.style[prop] = str; } }; return CustomStyle; })(); function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } var LinkTarget = { NONE: 0, // Default value. SELF: 1, BLANK: 2, PARENT: 3, TOP: 4, }; var LinkTargetStringMap = [ '', '_self', '_blank', '_parent', '_top' ]; /** * @typedef ExternalLinkParameters * @typedef {Object} ExternalLinkParameters * @property {string} url - An absolute URL. * @property {LinkTarget} target - The link target. * @property {string} rel - The link relationship. */ /** * Adds various attributes (href, title, target, rel) to hyperlinks. * @param {HTMLLinkElement} link - The link element. * @param {ExternalLinkParameters} params */ function addLinkAttributes(link, params) { var url = params && params.url; link.href = link.title = (url ? removeNullCharacters(url) : ''); if (url) { var target = params.target; if (typeof target === 'undefined') { target = getDefaultSetting('externalLinkTarget'); } link.target = LinkTargetStringMap[target]; var rel = params.rel; if (typeof rel === 'undefined') { rel = getDefaultSetting('externalLinkRel'); } link.rel = rel; } } // Gets the file name from a given URL. function getFilenameFromUrl(url) { var anchor = url.indexOf('#'); var query = url.indexOf('?'); var end = Math.min( anchor > 0 ? anchor : url.length, query > 0 ? query : url.length); return url.substring(url.lastIndexOf('/', end) + 1, end); } function getDefaultSetting(id) { // The list of the settings and their default is maintained for backward // compatibility and shall not be extended or modified. See also global.js. var globalSettings = sharedUtil.globalScope.PDFJS; switch (id) { case 'pdfBug': return globalSettings ? globalSettings.pdfBug : false; case 'disableAutoFetch': return globalSettings ? globalSettings.disableAutoFetch : false; case 'disableStream': return globalSettings ? globalSettings.disableStream : false; case 'disableRange': return globalSettings ? globalSettings.disableRange : false; case 'disableFontFace': return globalSettings ? globalSettings.disableFontFace : false; case 'disableCreateObjectURL': return globalSettings ? globalSettings.disableCreateObjectURL : false; case 'disableWebGL': return globalSettings ? globalSettings.disableWebGL : true; case 'cMapUrl': return globalSettings ? globalSettings.cMapUrl : null; case 'cMapPacked': return globalSettings ? globalSettings.cMapPacked : false; case 'postMessageTransfers': return globalSettings ? globalSettings.postMessageTransfers : true; case 'workerSrc': return globalSettings ? globalSettings.workerSrc : null; case 'disableWorker': return globalSettings ? globalSettings.disableWorker : false; case 'maxImageSize': return globalSettings ? globalSettings.maxImageSize : -1; case 'imageResourcesPath': return globalSettings ? globalSettings.imageResourcesPath : ''; case 'isEvalSupported': return globalSettings ? globalSettings.isEvalSupported : true; case 'externalLinkTarget': if (!globalSettings) { return LinkTarget.NONE; } switch (globalSettings.externalLinkTarget) { case LinkTarget.NONE: case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return globalSettings.externalLinkTarget; } warn('PDFJS.externalLinkTarget is invalid: ' + globalSettings.externalLinkTarget); // Reset the external link target, to suppress further warnings. globalSettings.externalLinkTarget = LinkTarget.NONE; return LinkTarget.NONE; case 'externalLinkRel': return globalSettings ? globalSettings.externalLinkRel : 'noreferrer'; case 'enableStats': return !!(globalSettings && globalSettings.enableStats); default: throw new Error('Unknown default setting: ' + id); } } function isExternalLinkTargetSet() { var externalLinkTarget = getDefaultSetting('externalLinkTarget'); switch (externalLinkTarget) { case LinkTarget.NONE: return false; case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return true; } } exports.CustomStyle = CustomStyle; exports.addLinkAttributes = addLinkAttributes; exports.isExternalLinkTargetSet = isExternalLinkTargetSet; exports.getFilenameFromUrl = getFilenameFromUrl; exports.LinkTarget = LinkTarget; exports.hasCanvasTypedArrays = hasCanvasTypedArrays; exports.getDefaultSetting = getDefaultSetting; })); (function (root, factory) { { factory((root.pdfjsDisplayFontLoader = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var assert = sharedUtil.assert; var bytesToString = sharedUtil.bytesToString; var string32 = sharedUtil.string32; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; function FontLoader(docId) { this.docId = docId; this.styleElement = null; this.nativeFontFaces = []; this.loadTestFontId = 0; this.loadingContext = { requests: [], nextRequestId: 0 }; } FontLoader.prototype = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = this.styleElement; if (!styleElement) { styleElement = this.styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = this.styleElement; if (styleElement) { styleElement.parentNode.removeChild(styleElement); styleElement = this.styleElement = null; } this.nativeFontFaces.forEach(function(nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }, bind: function fontLoaderBind(fonts, callback) { var rules = []; var fontsToLoad = []; var fontLoadPromises = []; var getNativeFontPromise = function(nativeFontFace) { // Return a promise that is always fulfilled, even when the font fails to // load. return nativeFontFace.loaded.catch(function(e) { warn('Failed to load font "' + nativeFontFace.family + '": ' + e); }); }; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; if (FontLoader.isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { this.addNativeFontFace(nativeFontFace); fontLoadPromises.push(getNativeFontPromise(nativeFontFace)); } } else { var rule = font.createFontFaceRule(); if (rule) { this.insertRule(rule); rules.push(rule); fontsToLoad.push(font); } } } var request = this.queueLoadingCallback(callback); if (FontLoader.isFontLoadingAPISupported) { Promise.all(fontLoadPromises).then(function() { request.complete(); }); } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) { this.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = this.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; this.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; FontLoader.isFontLoadingAPISupported = typeof document !== 'undefined' && !!document.fonts; Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', { get: function () { if (typeof navigator === 'undefined') { // node.js - we can pretend sync font loading is supported. return shadow(FontLoader, 'isSyncFontLoadingSupported', true); } var supported = false; // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(navigator.userAgent); if (m && m[1] >= 14) { supported = true; } // TODO other browsers return shadow(FontLoader, 'isSyncFontLoadingSupported', supported); }, enumerable: true, configurable: true }); var IsEvalSupportedCached = { get value() { return shadow(this, 'value', sharedUtil.isEvalSupported()); } }; var FontFaceObject = (function FontFaceObjectClosure() { function FontFaceObject(translatedData, options) { this.compiledGlyphs = Object.create(null); // importing translated data for (var i in translatedData) { this[i] = translatedData[i]; } this.options = options; } FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (this.options.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); if (this.options.fontRegistry) { this.options.fontRegistry.registerFont(this); } return nativeFontFace; }, createFontFaceRule: function FontFaceObject_createFontFaceRule() { if (!this.data) { return null; } if (this.options.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; if (this.options.fontRegistry) { this.options.fontRegistry.registerFont(this, url); } return rule; }, getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var cmds = objs.get(this.loadedName + '_path_' + character); var current, i, len; // If we can, compile cmds into JS for MAXIMUM SPEED if (this.options.isEvalSupported && IsEvalSupportedCached.value) { var args, js = ''; for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.args !== undefined) { args = current.args.join(','); } else { args = ''; } js += 'c.' + current.cmd + '(' + args + ');\n'; } /* jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } else { // But fall back on using Function.prototype.apply() if we're // blocked from using eval() for whatever reason (like CSP policies) this.compiledGlyphs[character] = function(c, size) { for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.cmd === 'scale') { current.args = [size, -size]; } c[current.cmd].apply(c, current.args); } }; } } return this.compiledGlyphs[character]; } }; return FontFaceObject; })(); exports.FontFaceObject = FontFaceObject; exports.FontLoader = FontLoader; })); (function (root, factory) { { factory((root.pdfjsDisplayMetadata = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var error = sharedUtil.error; function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = Object.create(null); this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; exports.Metadata = Metadata; })); (function (root, factory) { { factory((root.pdfjsDisplaySVG = {}), root.pdfjsSharedUtil); } }(this, function (exports, sharedUtil) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var Util = sharedUtil.Util; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var warn = sharedUtil.warn; var createObjectURL = sharedUtil.createObjectURL; var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = (function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); } else { c = (c >> 1) & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = (crc >>> 8) ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } function encode(imgData, kind, forceDataSchema) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = (width + 7) >> 3; break; case ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } // prefix every row with predictor 0 var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; // no prediction literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === ImageKind.GRAYSCALE_1BPP) { // inverting for B/W offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; // skipping predictor for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([ width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, // bit depth colorType, // color type 0x00, // compression method 0x00, // filter method 0x00 // interlace method ]); var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; // compression method and flags idat[pi++] = 0x9c; // flags var pos = 0; while (len > maxBlockLength) { // writing non-final DEFLATE blocks type 0 and length of 65535 idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } // writing non-final DEFLATE blocks type 0 idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = (~len & 0xffff) & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); // checksum idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; // PNG will consists: header, IHDR+data, IDAT+data, and IEND. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return createObjectURL(data, 'image/png', forceDataSchema); } return function convertImgDataToPng(imgData, forceDataSchema) { var kind = (imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind); return encode(imgData, kind, forceDataSchema); }; })(); var SVGExtraState = (function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; // Default foreground and background colors this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; // Clipping this.clipId = ''; this.pendingClip = false; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; })(); var SVGGraphics = (function SVGGraphicsClosure() { function createScratchSVG(width, height) { var NS = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(NS, 'svg:svg'); svg.setAttributeNS(null, 'version', '1.1'); svg.setAttributeNS(null, 'width', width + 'px'); svg.setAttributeNS(null, 'height', height + 'px'); svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height); return svg; } function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({'fnId': 92, 'fn': 'group', 'items': []}); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if(opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } /** * Formats float number. * @param value {number} number to format. * @returns {string} */ function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } /** * Formats transform matrix. The standard rotation, scale and translate * matrices are replaced by their shorter forms, and for identity matrix * returns empty string to save the memory. * @param m {Array} matrix to format. * @returns {string} */ function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs, forceDataSchema) { this.current = new SVGExtraState(); this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = Object.create(null); this.cssStyle = null; this.forceDataSchema = !!forceDataSchema; } var NS = 'http://www.w3.org/2000/svg'; var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.pgrp.appendChild(this.tgrp); }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; var self = this; for (var i = 0; i < fnArrayLen; i++) { if (OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function(resolve) { self.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function(resolve) { self.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = Util.transform(this.transformMatrix, transformMatrix); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { this.svg = createScratchSVG(viewport.width, viewport.height); this.viewport = viewport; return this.loadDependencies(operatorList).then(function () { this.transformMatrix = IDENTITY_MATRIX; this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform)); this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.defs = document.createElementNS(NS, 'svg:defs'); this.pgrp.appendChild(this.defs); this.pgrp.appendChild(this.tgrp); this.svg.appendChild(this.pgrp); var opTree = this.convertOpList(operatorList); this.executeOpTree(opTree); return this.svg; }.bind(this)); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in OPS) { REVOPS[OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]}); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for(var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case OPS.beginText: this.beginText(); break; case OPS.setLeading: this.setLeading(args); break; case OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case OPS.setFont: this.setFont(args); break; case OPS.showText: this.showText(args[0]); break; case OPS.showSpacedText: this.showText(args[0]); break; case OPS.endText: this.endText(); break; case OPS.moveText: this.moveText(args[0], args[1]); break; case OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case OPS.setHScale: this.setHScale(args[0]); break; case OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setLineWidth: this.setLineWidth(args[0]); break; case OPS.setLineJoin: this.setLineJoin(args[0]); break; case OPS.setLineCap: this.setLineCap(args[0]); break; case OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case OPS.setDash: this.setDash(args[0], args[1]); break; case OPS.setGState: this.setGState(args[0]); break; case OPS.fill: this.fill(); break; case OPS.eoFill: this.eoFill(); break; case OPS.stroke: this.stroke(); break; case OPS.fillStroke: this.fillStroke(); break; case OPS.eoFillStroke: this.eoFillStroke(); break; case OPS.clip: this.clip('nonzero'); break; case OPS.eoClip: this.clip('evenodd'); break; case OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case OPS.closePath: this.closePath(); break; case OPS.closeStroke: this.closeStroke(); break; case OPS.closeFillStroke: this.closeFillStroke(); break; case OPS.nextLine: this.nextLine(); break; case OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.constructPath: this.constructPath(args[0], args[1]); break; case OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: warn('Unimplemented method '+ fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = document.createElementNS(NS, 'svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = IDENTITY_MATRIX; this.current.lineMatrix = IDENTITY_MATRIX; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.txtElement = document.createElementNS(NS, 'svg:text'); this.current.txtgrp = document.createElementNS(NS, 'svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } current.xcoords.push(current.x + x * textHScale); var width = glyph.width; var character = glyph.fontChar; var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; current.tspan.textContent += character; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)' ); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this.tgrp.appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = document.createElementNS(NS, 'svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = createObjectURL(fontObj.data, fontObj.mimetype, this.forceDataSchema); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() { if (this.current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, // Path properties setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = document.createElementNS(NS, 'svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x) , pf(y)); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.path.setAttributeNS(null, 'fill', 'none'); this.tgrp.appendChild(current.path); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } // Saving a reference in current.element so that it can be addressed // in 'fill' and 'stroke' current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { var current = this.current; if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, clip: function SVGGraphics_clip(type) { var current = this.current; // Add current path to clipping path current.clipId = 'clippath' + clipCount; clipCount++; this.clippath = document.createElementNS(NS, 'svg:clipPath'); this.clippath.setAttributeNS(null, 'id', current.clipId); var clipElement = current.element.cloneNode(); if (type === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.clippath.appendChild(clipElement); this.defs.appendChild(this.clippath); // Create a new group with that attribute current.pendingClip = true; this.cgrp = document.createElementNS(NS, 'svg:g'); this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')'); this.pgrp.appendChild(this.cgrp); }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': break; case 'FL': break; case 'Font': this.setFont(value); break; case 'CA': break; case 'ca': break; case 'BM': break; case 'SMask': break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); }, fillStroke: function SVGGraphics_fillStroke() { // Order is important since stroke wants fill to be none. // First stroke, then if fill needed, it will be overwritten. this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this.tgrp.appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var current = this.current; var imgObj = this.objs.get(objId); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', imgObj.width + 'px'); imgEl.setAttributeNS(null, 'height', imgObj.height + 'px'); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this.tgrp.appendChild(imgEl); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var current = this.current; var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData, this.forceDataSchema); var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); current.element = cliprect; this.clip('nonzero'); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this.tgrp.appendChild(imgEl); } if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = document.createElementNS(NS, 'svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')'); this.defs.appendChild(mask); this.tgrp.appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); if (isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() { this.restore(); } }; return SVGGraphics; })(); exports.SVGGraphics = SVGGraphics; })); (function (root, factory) { { factory((root.pdfjsDisplayAnnotationLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var AnnotationBorderStyleType = sharedUtil.AnnotationBorderStyleType; var AnnotationType = sharedUtil.AnnotationType; var Util = sharedUtil.Util; var addLinkAttributes = displayDOMUtils.addLinkAttributes; var LinkTarget = displayDOMUtils.LinkTarget; var getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl; var warn = sharedUtil.warn; var CustomStyle = displayDOMUtils.CustomStyle; var getDefaultSetting = displayDOMUtils.getDefaultSetting; /** * @typedef {Object} AnnotationElementParameters * @property {Object} data * @property {HTMLDivElement} layer * @property {PDFPage} page * @property {PageViewport} viewport * @property {IPDFLinkService} linkService * @property {DownloadManager} downloadManager * @property {string} imageResourcesPath * @property {boolean} renderInteractiveForms */ /** * @class * @alias AnnotationElementFactory */ function AnnotationElementFactory() {} AnnotationElementFactory.prototype = /** @lends AnnotationElementFactory.prototype */ { /** * @param {AnnotationElementParameters} parameters * @returns {AnnotationElement} */ create: function AnnotationElementFactory_create(parameters) { var subtype = parameters.data.annotationType; switch (subtype) { case AnnotationType.LINK: return new LinkAnnotationElement(parameters); case AnnotationType.TEXT: return new TextAnnotationElement(parameters); case AnnotationType.WIDGET: var fieldType = parameters.data.fieldType; switch (fieldType) { case 'Tx': return new TextWidgetAnnotationElement(parameters); } return new WidgetAnnotationElement(parameters); case AnnotationType.POPUP: return new PopupAnnotationElement(parameters); case AnnotationType.HIGHLIGHT: return new HighlightAnnotationElement(parameters); case AnnotationType.UNDERLINE: return new UnderlineAnnotationElement(parameters); case AnnotationType.SQUIGGLY: return new SquigglyAnnotationElement(parameters); case AnnotationType.STRIKEOUT: return new StrikeOutAnnotationElement(parameters); case AnnotationType.FILEATTACHMENT: return new FileAttachmentAnnotationElement(parameters); default: return new AnnotationElement(parameters); } } }; /** * @class * @alias AnnotationElement */ var AnnotationElement = (function AnnotationElementClosure() { function AnnotationElement(parameters, isRenderable) { this.isRenderable = isRenderable || false; this.data = parameters.data; this.layer = parameters.layer; this.page = parameters.page; this.viewport = parameters.viewport; this.linkService = parameters.linkService; this.downloadManager = parameters.downloadManager; this.imageResourcesPath = parameters.imageResourcesPath; this.renderInteractiveForms = parameters.renderInteractiveForms; if (isRenderable) { this.container = this._createContainer(); } } AnnotationElement.prototype = /** @lends AnnotationElement.prototype */ { /** * Create an empty container for the annotation's HTML element. * * @private * @memberof AnnotationElement * @returns {HTMLSectionElement} */ _createContainer: function AnnotationElement_createContainer() { var data = this.data, page = this.page, viewport = this.viewport; var container = document.createElement('section'); var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; container.setAttribute('data-annotation-id', data.id); // Do *not* modify `data.rect`, since that will corrupt the annotation // position on subsequent calls to `_createContainer` (see issue 6804). var rect = Util.normalizeRect([ data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1] ]); CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')'); CustomStyle.setProp('transformOrigin', container, -rect[0] + 'px ' + -rect[1] + 'px'); if (data.borderStyle.width > 0) { container.style.borderWidth = data.borderStyle.width + 'px'; if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) { // Underline styles only have a bottom border, so we do not need // to adjust for all borders. This yields a similar result as // Adobe Acrobat/Reader. width = width - 2 * data.borderStyle.width; height = height - 2 * data.borderStyle.width; } var horizontalRadius = data.borderStyle.horizontalCornerRadius; var verticalRadius = data.borderStyle.verticalCornerRadius; if (horizontalRadius > 0 || verticalRadius > 0) { var radius = horizontalRadius + 'px / ' + verticalRadius + 'px'; CustomStyle.setProp('borderRadius', container, radius); } switch (data.borderStyle.style) { case AnnotationBorderStyleType.SOLID: container.style.borderStyle = 'solid'; break; case AnnotationBorderStyleType.DASHED: container.style.borderStyle = 'dashed'; break; case AnnotationBorderStyleType.BEVELED: warn('Unimplemented border style: beveled'); break; case AnnotationBorderStyleType.INSET: warn('Unimplemented border style: inset'); break; case AnnotationBorderStyleType.UNDERLINE: container.style.borderBottomStyle = 'solid'; break; default: break; } if (data.color) { container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); } else { // Transparent (invisible) border, so do not draw it at all. container.style.borderWidth = 0; } } container.style.left = rect[0] + 'px'; container.style.top = rect[1] + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; return container; }, /** * Create a popup for the annotation's HTML element. This is used for * annotations that do not have a Popup entry in the dictionary, but * are of a type that works with popups (such as Highlight annotations). * * @private * @param {HTMLSectionElement} container * @param {HTMLDivElement|HTMLImageElement|null} trigger * @param {Object} data * @memberof AnnotationElement */ _createPopup: function AnnotationElement_createPopup(container, trigger, data) { // If no trigger element is specified, create it. if (!trigger) { trigger = document.createElement('div'); trigger.style.height = container.style.height; trigger.style.width = container.style.width; container.appendChild(trigger); } var popupElement = new PopupElement({ container: container, trigger: trigger, color: data.color, title: data.title, contents: data.contents, hideWrapper: true }); var popup = popupElement.render(); // Position the popup next to the annotation's container. popup.style.left = container.style.width; container.appendChild(popup); }, /** * Render the annotation's HTML element in the empty container. * * @public * @memberof AnnotationElement */ render: function AnnotationElement_render() { throw new Error('Abstract method AnnotationElement.render called'); } }; return AnnotationElement; })(); /** * @class * @alias LinkAnnotationElement */ var LinkAnnotationElement = (function LinkAnnotationElementClosure() { function LinkAnnotationElement(parameters) { AnnotationElement.call(this, parameters, true); } Util.inherit(LinkAnnotationElement, AnnotationElement, { /** * Render the link annotation's HTML element in the empty container. * * @public * @memberof LinkAnnotationElement * @returns {HTMLSectionElement} */ render: function LinkAnnotationElement_render() { this.container.className = 'linkAnnotation'; var link = document.createElement('a'); addLinkAttributes(link, { url: this.data.url, target: (this.data.newWindow ? LinkTarget.BLANK : undefined), }); if (!this.data.url) { if (this.data.action) { this._bindNamedAction(link, this.data.action); } else { this._bindLink(link, (this.data.dest || null)); } } this.container.appendChild(link); return this.container; }, /** * Bind internal links to the link element. * * @private * @param {Object} link * @param {Object} destination * @memberof LinkAnnotationElement */ _bindLink: function LinkAnnotationElement_bindLink(link, destination) { var self = this; link.href = this.linkService.getDestinationHash(destination); link.onclick = function() { if (destination) { self.linkService.navigateTo(destination); } return false; }; if (destination) { link.className = 'internalLink'; } }, /** * Bind named actions to the link element. * * @private * @param {Object} link * @param {Object} action * @memberof LinkAnnotationElement */ _bindNamedAction: function LinkAnnotationElement_bindNamedAction(link, action) { var self = this; link.href = this.linkService.getAnchorUrl(''); link.onclick = function() { self.linkService.executeNamedAction(action); return false; }; link.className = 'internalLink'; } }); return LinkAnnotationElement; })(); /** * @class * @alias TextAnnotationElement */ var TextAnnotationElement = (function TextAnnotationElementClosure() { function TextAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(TextAnnotationElement, AnnotationElement, { /** * Render the text annotation's HTML element in the empty container. * * @public * @memberof TextAnnotationElement * @returns {HTMLSectionElement} */ render: function TextAnnotationElement_render() { this.container.className = 'textAnnotation'; var image = document.createElement('img'); image.style.height = this.container.style.height; image.style.width = this.container.style.width; image.src = this.imageResourcesPath + 'annotation-' + this.data.name.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: this.data.name}); if (!this.data.hasPopup) { this._createPopup(this.container, image, this.data); } this.container.appendChild(image); return this.container; } }); return TextAnnotationElement; })(); /** * @class * @alias WidgetAnnotationElement */ var WidgetAnnotationElement = (function WidgetAnnotationElementClosure() { function WidgetAnnotationElement(parameters) { var isRenderable = parameters.renderInteractiveForms || (!parameters.data.hasAppearance && !!parameters.data.fieldValue); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(WidgetAnnotationElement, AnnotationElement, { /** * Render the widget annotation's HTML element in the empty container. * * @public * @memberof WidgetAnnotationElement * @returns {HTMLSectionElement} */ render: function WidgetAnnotationElement_render() { // Show only the container for unsupported field types. return this.container; } }); return WidgetAnnotationElement; })(); /** * @class * @alias TextWidgetAnnotationElement */ var TextWidgetAnnotationElement = ( function TextWidgetAnnotationElementClosure() { var TEXT_ALIGNMENT = ['left', 'center', 'right']; function TextWidgetAnnotationElement(parameters) { WidgetAnnotationElement.call(this, parameters); } Util.inherit(TextWidgetAnnotationElement, WidgetAnnotationElement, { /** * Render the text widget annotation's HTML element in the empty container. * * @public * @memberof TextWidgetAnnotationElement * @returns {HTMLSectionElement} */ render: function TextWidgetAnnotationElement_render() { this.container.className = 'textWidgetAnnotation'; var element = null; if (this.renderInteractiveForms) { // NOTE: We cannot set the values using `element.value` below, since it // prevents the AnnotationLayer rasterizer in `test/driver.js` // from parsing the elements correctly for the reference tests. if (this.data.multiLine) { element = document.createElement('textarea'); element.textContent = this.data.fieldValue; } else { element = document.createElement('input'); element.type = 'text'; element.setAttribute('value', this.data.fieldValue); } element.disabled = this.data.readOnly; if (this.data.maxLen !== null) { element.maxLength = this.data.maxLen; } if (this.data.comb) { var fieldWidth = this.data.rect[2] - this.data.rect[0]; var combWidth = fieldWidth / this.data.maxLen; element.classList.add('comb'); element.style.letterSpacing = 'calc(' + combWidth + 'px - 1ch)'; } } else { element = document.createElement('div'); element.textContent = this.data.fieldValue; element.style.verticalAlign = 'middle'; element.style.display = 'table-cell'; var font = null; if (this.data.fontRefName) { font = this.page.commonObjs.getData(this.data.fontRefName); } this._setTextStyle(element, font); } if (this.data.textAlignment !== null) { element.style.textAlign = TEXT_ALIGNMENT[this.data.textAlignment]; } this.container.appendChild(element); return this.container; }, /** * Apply text styles to the text in the element. * * @private * @param {HTMLDivElement} element * @param {Object} font * @memberof TextWidgetAnnotationElement */ _setTextStyle: function TextWidgetAnnotationElement_setTextStyle(element, font) { // TODO: This duplicates some of the logic in CanvasGraphics.setFont(). var style = element.style; style.fontSize = this.data.fontSize + 'px'; style.direction = (this.data.fontDirection < 0 ? 'rtl': 'ltr'); if (!font) { return; } style.fontWeight = (font.black ? (font.bold ? '900' : 'bold') : (font.bold ? 'bold' : 'normal')); style.fontStyle = (font.italic ? 'italic' : 'normal'); // Use a reasonable default font if the font doesn't specify a fallback. var fontFamily = font.loadedName ? '"' + font.loadedName + '", ' : ''; var fallbackName = font.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } }); return TextWidgetAnnotationElement; })(); /** * @class * @alias PopupAnnotationElement */ var PopupAnnotationElement = (function PopupAnnotationElementClosure() { function PopupAnnotationElement(parameters) { var isRenderable = !!(parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(PopupAnnotationElement, AnnotationElement, { /** * Render the popup annotation's HTML element in the empty container. * * @public * @memberof PopupAnnotationElement * @returns {HTMLSectionElement} */ render: function PopupAnnotationElement_render() { this.container.className = 'popupAnnotation'; var selector = '[data-annotation-id="' + this.data.parentId + '"]'; var parentElement = this.layer.querySelector(selector); if (!parentElement) { return this.container; } var popup = new PopupElement({ container: this.container, trigger: parentElement, color: this.data.color, title: this.data.title, contents: this.data.contents }); // Position the popup next to the parent annotation's container. // PDF viewers ignore a popup annotation's rectangle. var parentLeft = parseFloat(parentElement.style.left); var parentWidth = parseFloat(parentElement.style.width); CustomStyle.setProp('transformOrigin', this.container, -(parentLeft + parentWidth) + 'px -' + parentElement.style.top); this.container.style.left = (parentLeft + parentWidth) + 'px'; this.container.appendChild(popup.render()); return this.container; } }); return PopupAnnotationElement; })(); /** * @class * @alias PopupElement */ var PopupElement = (function PopupElementClosure() { var BACKGROUND_ENLIGHT = 0.7; function PopupElement(parameters) { this.container = parameters.container; this.trigger = parameters.trigger; this.color = parameters.color; this.title = parameters.title; this.contents = parameters.contents; this.hideWrapper = parameters.hideWrapper || false; this.pinned = false; } PopupElement.prototype = /** @lends PopupElement.prototype */ { /** * Render the popup's HTML element. * * @public * @memberof PopupElement * @returns {HTMLSectionElement} */ render: function PopupElement_render() { var wrapper = document.createElement('div'); wrapper.className = 'popupWrapper'; // For Popup annotations we hide the entire section because it contains // only the popup. However, for Text annotations without a separate Popup // annotation, we cannot hide the entire container as the image would // disappear too. In that special case, hiding the wrapper suffices. this.hideElement = (this.hideWrapper ? wrapper : this.container); this.hideElement.setAttribute('hidden', true); var popup = document.createElement('div'); popup.className = 'popup'; var color = this.color; if (color) { // Enlighten the color. var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; popup.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0); } var contents = this._formatContents(this.contents); var title = document.createElement('h1'); title.textContent = this.title; // Attach the event listeners to the trigger element. this.trigger.addEventListener('click', this._toggle.bind(this)); this.trigger.addEventListener('mouseover', this._show.bind(this, false)); this.trigger.addEventListener('mouseout', this._hide.bind(this, false)); popup.addEventListener('click', this._hide.bind(this, true)); popup.appendChild(title); popup.appendChild(contents); wrapper.appendChild(popup); return wrapper; }, /** * Format the contents of the popup by adding newlines where necessary. * * @private * @param {string} contents * @memberof PopupElement * @returns {HTMLParagraphElement} */ _formatContents: function PopupElement_formatContents(contents) { var p = document.createElement('p'); var lines = contents.split(/(?:\r\n?|\n)/); for (var i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; p.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { p.appendChild(document.createElement('br')); } } return p; }, /** * Toggle the visibility of the popup. * * @private * @memberof PopupElement */ _toggle: function PopupElement_toggle() { if (this.pinned) { this._hide(true); } else { this._show(true); } }, /** * Show the popup. * * @private * @param {boolean} pin * @memberof PopupElement */ _show: function PopupElement_show(pin) { if (pin) { this.pinned = true; } if (this.hideElement.hasAttribute('hidden')) { this.hideElement.removeAttribute('hidden'); this.container.style.zIndex += 1; } }, /** * Hide the popup. * * @private * @param {boolean} unpin * @memberof PopupElement */ _hide: function PopupElement_hide(unpin) { if (unpin) { this.pinned = false; } if (!this.hideElement.hasAttribute('hidden') && !this.pinned) { this.hideElement.setAttribute('hidden', true); this.container.style.zIndex -= 1; } } }; return PopupElement; })(); /** * @class * @alias HighlightAnnotationElement */ var HighlightAnnotationElement = ( function HighlightAnnotationElementClosure() { function HighlightAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(HighlightAnnotationElement, AnnotationElement, { /** * Render the highlight annotation's HTML element in the empty container. * * @public * @memberof HighlightAnnotationElement * @returns {HTMLSectionElement} */ render: function HighlightAnnotationElement_render() { this.container.className = 'highlightAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }); return HighlightAnnotationElement; })(); /** * @class * @alias UnderlineAnnotationElement */ var UnderlineAnnotationElement = ( function UnderlineAnnotationElementClosure() { function UnderlineAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(UnderlineAnnotationElement, AnnotationElement, { /** * Render the underline annotation's HTML element in the empty container. * * @public * @memberof UnderlineAnnotationElement * @returns {HTMLSectionElement} */ render: function UnderlineAnnotationElement_render() { this.container.className = 'underlineAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }); return UnderlineAnnotationElement; })(); /** * @class * @alias SquigglyAnnotationElement */ var SquigglyAnnotationElement = (function SquigglyAnnotationElementClosure() { function SquigglyAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(SquigglyAnnotationElement, AnnotationElement, { /** * Render the squiggly annotation's HTML element in the empty container. * * @public * @memberof SquigglyAnnotationElement * @returns {HTMLSectionElement} */ render: function SquigglyAnnotationElement_render() { this.container.className = 'squigglyAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }); return SquigglyAnnotationElement; })(); /** * @class * @alias StrikeOutAnnotationElement */ var StrikeOutAnnotationElement = ( function StrikeOutAnnotationElementClosure() { function StrikeOutAnnotationElement(parameters) { var isRenderable = !!(parameters.data.hasPopup || parameters.data.title || parameters.data.contents); AnnotationElement.call(this, parameters, isRenderable); } Util.inherit(StrikeOutAnnotationElement, AnnotationElement, { /** * Render the strikeout annotation's HTML element in the empty container. * * @public * @memberof StrikeOutAnnotationElement * @returns {HTMLSectionElement} */ render: function StrikeOutAnnotationElement_render() { this.container.className = 'strikeoutAnnotation'; if (!this.data.hasPopup) { this._createPopup(this.container, null, this.data); } return this.container; } }); return StrikeOutAnnotationElement; })(); /** * @class * @alias FileAttachmentAnnotationElement */ var FileAttachmentAnnotationElement = ( function FileAttachmentAnnotationElementClosure() { function FileAttachmentAnnotationElement(parameters) { AnnotationElement.call(this, parameters, true); this.filename = getFilenameFromUrl(parameters.data.file.filename); this.content = parameters.data.file.content; } Util.inherit(FileAttachmentAnnotationElement, AnnotationElement, { /** * Render the file attachment annotation's HTML element in the empty * container. * * @public * @memberof FileAttachmentAnnotationElement * @returns {HTMLSectionElement} */ render: function FileAttachmentAnnotationElement_render() { this.container.className = 'fileAttachmentAnnotation'; var trigger = document.createElement('div'); trigger.style.height = this.container.style.height; trigger.style.width = this.container.style.width; trigger.addEventListener('dblclick', this._download.bind(this)); if (!this.data.hasPopup && (this.data.title || this.data.contents)) { this._createPopup(this.container, trigger, this.data); } this.container.appendChild(trigger); return this.container; }, /** * Download the file attachment associated with this annotation. * * @private * @memberof FileAttachmentAnnotationElement */ _download: function FileAttachmentAnnotationElement_download() { if (!this.downloadManager) { warn('Download cannot be started due to unavailable download manager'); return; } this.downloadManager.downloadData(this.content, this.filename, ''); } }); return FileAttachmentAnnotationElement; })(); /** * @typedef {Object} AnnotationLayerParameters * @property {PageViewport} viewport * @property {HTMLDivElement} div * @property {Array} annotations * @property {PDFPage} page * @property {IPDFLinkService} linkService * @property {string} imageResourcesPath * @property {boolean} renderInteractiveForms */ /** * @class * @alias AnnotationLayer */ var AnnotationLayer = (function AnnotationLayerClosure() { return { /** * Render a new annotation layer with all annotation elements. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ render: function AnnotationLayer_render(parameters) { var annotationElementFactory = new AnnotationElementFactory(); for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; if (!data) { continue; } var properties = { data: data, layer: parameters.div, page: parameters.page, viewport: parameters.viewport, linkService: parameters.linkService, downloadManager: parameters.downloadManager, imageResourcesPath: parameters.imageResourcesPath || getDefaultSetting('imageResourcesPath'), renderInteractiveForms: parameters.renderInteractiveForms || false, }; var element = annotationElementFactory.create(properties); if (element.isRenderable) { parameters.div.appendChild(element.render()); } } }, /** * Update the annotation elements on existing annotation layer. * * @public * @param {AnnotationLayerParameters} parameters * @memberof AnnotationLayer */ update: function AnnotationLayer_update(parameters) { for (var i = 0, ii = parameters.annotations.length; i < ii; i++) { var data = parameters.annotations[i]; var element = parameters.div.querySelector( '[data-annotation-id="' + data.id + '"]'); if (element) { CustomStyle.setProp('transform', element, 'matrix(' + parameters.viewport.transform.join(',') + ')'); } } parameters.div.removeAttribute('hidden'); } }; })(); exports.AnnotationLayer = AnnotationLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayTextLayer = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var CustomStyle = displayDOMUtils.CustomStyle; var getDefaultSetting = displayDOMUtils.getDefaultSetting; /** * Text layer render parameters. * * @typedef {Object} TextLayerRenderParameters * @property {TextContent} textContent - Text content to render (the object is * returned by the page's getTextContent() method). * @property {HTMLElement} container - HTML element that will contain text runs. * @property {PageViewport} viewport - The target viewport to properly * layout the text runs. * @property {Array} textDivs - (optional) HTML elements that are correspond * the text items of the textContent input. This is output and shall be * initially be set to empty array. * @property {number} timeout - (optional) Delay in milliseconds before * rendering of the text runs occurs. * @property {boolean} enhanceTextSelection - (optional) Whether to turn on the * text selection enhancement. */ var renderTextLayer = (function renderTextLayerClosure() { var MAX_TEXT_DIVS_TO_RENDER = 100000; var NonWhitespaceRegexp = /\S/; function isAllWhitespace(str) { return !NonWhitespaceRegexp.test(str); } // Text layers may contain many thousand div's, and using `styleBuf` avoids // creating many intermediate strings when building their 'style' properties. var styleBuf = ['left: ', 0, 'px; top: ', 0, 'px; font-size: ', 0, 'px; font-family: ', '', ';']; function appendText(task, geom, styles) { // Initialize all used properties to keep the caches monomorphic. var textDiv = document.createElement('div'); var textDivProperties = { style: null, angle: 0, canvasWidth: 0, isWhitespace: false, originalTransform: null, paddingBottom: 0, paddingLeft: 0, paddingRight: 0, paddingTop: 0, scale: 1, }; task._textDivs.push(textDiv); if (isAllWhitespace(geom.str)) { textDivProperties.isWhitespace = true; task._textDivProperties.set(textDiv, textDivProperties); return; } var tx = Util.transform(task._viewport.transform, geom.transform); var angle = Math.atan2(tx[1], tx[0]); var style = styles[geom.fontName]; if (style.vertical) { angle += Math.PI / 2; } var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3])); var fontAscent = fontHeight; if (style.ascent) { fontAscent = style.ascent * fontAscent; } else if (style.descent) { fontAscent = (1 + style.descent) * fontAscent; } var left; var top; if (angle === 0) { left = tx[4]; top = tx[5] - fontAscent; } else { left = tx[4] + (fontAscent * Math.sin(angle)); top = tx[5] - (fontAscent * Math.cos(angle)); } styleBuf[1] = left; styleBuf[3] = top; styleBuf[5] = fontHeight; styleBuf[7] = style.fontFamily; textDivProperties.style = styleBuf.join(''); textDiv.setAttribute('style', textDivProperties.style); textDiv.textContent = geom.str; // |fontName| is only used by the Font Inspector. This test will succeed // when e.g. the Font Inspector is off but the Stepper is on, but it's // not worth the effort to do a more accurate test. We only use `dataset` // here to make the font name available for the debugger. if (getDefaultSetting('pdfBug')) { textDiv.dataset.fontName = geom.fontName; } if (angle !== 0) { textDivProperties.angle = angle * (180 / Math.PI); } // We don't bother scaling single-char text divs, because it has very // little effect on text highlighting. This makes scrolling on docs with // lots of such divs a lot faster. if (geom.str.length > 1) { if (style.vertical) { textDivProperties.canvasWidth = geom.height * task._viewport.scale; } else { textDivProperties.canvasWidth = geom.width * task._viewport.scale; } } task._textDivProperties.set(textDiv, textDivProperties); if (task._enhanceTextSelection) { var angleCos = 1, angleSin = 0; if (angle !== 0) { angleCos = Math.cos(angle); angleSin = Math.sin(angle); } var divWidth = (style.vertical ? geom.height : geom.width) * task._viewport.scale; var divHeight = fontHeight; var m, b; if (angle !== 0) { m = [angleCos, angleSin, -angleSin, angleCos, left, top]; b = Util.getAxialAlignedBoundingBox([0, 0, divWidth, divHeight], m); } else { b = [left, top, left + divWidth, top + divHeight]; } task._bounds.push({ left: b[0], top: b[1], right: b[2], bottom: b[3], div: textDiv, size: [divWidth, divHeight], m: m }); } } function render(task) { if (task._canceled) { return; } var textLayerFrag = task._container; var textDivs = task._textDivs; var capability = task._capability; var textDivsLength = textDivs.length; // No point in rendering many divs as it would make the browser // unusable even after the divs are rendered. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { task._renderingDone = true; capability.resolve(); return; } var canvas = document.createElement('canvas'); canvas.mozOpaque = true; var ctx = canvas.getContext('2d', {alpha: false}); var lastFontSize; var lastFontFamily; for (var i = 0; i < textDivsLength; i++) { var textDiv = textDivs[i]; var textDivProperties = task._textDivProperties.get(textDiv); if (textDivProperties.isWhitespace) { continue; } var fontSize = textDiv.style.fontSize; var fontFamily = textDiv.style.fontFamily; // Only build font string and set to context if different from last. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) { ctx.font = fontSize + ' ' + fontFamily; lastFontSize = fontSize; lastFontFamily = fontFamily; } var width = ctx.measureText(textDiv.textContent).width; textLayerFrag.appendChild(textDiv); var transform = ''; if (textDivProperties.canvasWidth !== 0 && width > 0) { textDivProperties.scale = textDivProperties.canvasWidth / width; transform = 'scaleX(' + textDivProperties.scale + ')'; } if (textDivProperties.angle !== 0) { transform = 'rotate(' + textDivProperties.angle + 'deg) ' + transform; } if (transform !== '') { textDivProperties.originalTransform = transform; CustomStyle.setProp('transform', textDiv, transform); } task._textDivProperties.set(textDiv, textDivProperties); } task._renderingDone = true; capability.resolve(); } function expand(task) { var bounds = task._bounds; var viewport = task._viewport; var expanded = expandBounds(viewport.width, viewport.height, bounds); for (var i = 0; i < expanded.length; i++) { var div = bounds[i].div; var divProperties = task._textDivProperties.get(div); if (divProperties.angle === 0) { divProperties.paddingLeft = bounds[i].left - expanded[i].left; divProperties.paddingTop = bounds[i].top - expanded[i].top; divProperties.paddingRight = expanded[i].right - bounds[i].right; divProperties.paddingBottom = expanded[i].bottom - bounds[i].bottom; task._textDivProperties.set(div, divProperties); continue; } // Box is rotated -- trying to find padding so rotated div will not // exceed its expanded bounds. var e = expanded[i], b = bounds[i]; var m = b.m, c = m[0], s = m[1]; // Finding intersections with expanded box. var points = [[0, 0], [0, b.size[1]], [b.size[0], 0], b.size]; var ts = new Float64Array(64); points.forEach(function (p, i) { var t = Util.applyTransform(p, m); ts[i + 0] = c && (e.left - t[0]) / c; ts[i + 4] = s && (e.top - t[1]) / s; ts[i + 8] = c && (e.right - t[0]) / c; ts[i + 12] = s && (e.bottom - t[1]) / s; ts[i + 16] = s && (e.left - t[0]) / -s; ts[i + 20] = c && (e.top - t[1]) / c; ts[i + 24] = s && (e.right - t[0]) / -s; ts[i + 28] = c && (e.bottom - t[1]) / c; ts[i + 32] = c && (e.left - t[0]) / -c; ts[i + 36] = s && (e.top - t[1]) / -s; ts[i + 40] = c && (e.right - t[0]) / -c; ts[i + 44] = s && (e.bottom - t[1]) / -s; ts[i + 48] = s && (e.left - t[0]) / s; ts[i + 52] = c && (e.top - t[1]) / -c; ts[i + 56] = s && (e.right - t[0]) / s; ts[i + 60] = c && (e.bottom - t[1]) / -c; }); var findPositiveMin = function (ts, offset, count) { var result = 0; for (var i = 0; i < count; i++) { var t = ts[offset++]; if (t > 0) { result = result ? Math.min(t, result) : t; } } return result; }; // Not based on math, but to simplify calculations, using cos and sin // absolute values to not exceed the box (it can but insignificantly). var boxScale = 1 + Math.min(Math.abs(c), Math.abs(s)); divProperties.paddingLeft = findPositiveMin(ts, 32, 16) / boxScale; divProperties.paddingTop = findPositiveMin(ts, 48, 16) / boxScale; divProperties.paddingRight = findPositiveMin(ts, 0, 16) / boxScale; divProperties.paddingBottom = findPositiveMin(ts, 16, 16) / boxScale; task._textDivProperties.set(div, divProperties); } } function expandBounds(width, height, boxes) { var bounds = boxes.map(function (box, i) { return { x1: box.left, y1: box.top, x2: box.right, y2: box.bottom, index: i, x1New: undefined, x2New: undefined }; }); expandBoundsLTR(width, bounds); var expanded = new Array(boxes.length); bounds.forEach(function (b) { var i = b.index; expanded[i] = { left: b.x1New, top: 0, right: b.x2New, bottom: 0 }; }); // Rotating on 90 degrees and extending extended boxes. Reusing the bounds // array and objects. boxes.map(function (box, i) { var e = expanded[i], b = bounds[i]; b.x1 = box.top; b.y1 = width - e.right; b.x2 = box.bottom; b.y2 = width - e.left; b.index = i; b.x1New = undefined; b.x2New = undefined; }); expandBoundsLTR(height, bounds); bounds.forEach(function (b) { var i = b.index; expanded[i].top = b.x1New; expanded[i].bottom = b.x2New; }); return expanded; } function expandBoundsLTR(width, bounds) { // Sorting by x1 coordinate and walk by the bounds in the same order. bounds.sort(function (a, b) { return a.x1 - b.x1 || a.index - b.index; }); // First we see on the horizon is a fake boundary. var fakeBoundary = { x1: -Infinity, y1: -Infinity, x2: 0, y2: Infinity, index: -1, x1New: 0, x2New: 0 }; var horizon = [{ start: -Infinity, end: Infinity, boundary: fakeBoundary }]; bounds.forEach(function (boundary) { // Searching for the affected part of horizon. // TODO red-black tree or simple binary search var i = 0; while (i < horizon.length && horizon[i].end <= boundary.y1) { i++; } var j = horizon.length - 1; while(j >= 0 && horizon[j].start >= boundary.y2) { j--; } var horizonPart, affectedBoundary; var q, k, maxXNew = -Infinity; for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; var xNew; if (affectedBoundary.x2 > boundary.x1) { // In the middle of the previous element, new x shall be at the // boundary start. Extending if further if the affected bondary // placed on top of the current one. xNew = affectedBoundary.index > boundary.index ? affectedBoundary.x1New : boundary.x1; } else if (affectedBoundary.x2New === undefined) { // We have some space in between, new x in middle will be a fair // choice. xNew = (affectedBoundary.x2 + boundary.x1) / 2; } else { // Affected boundary has x2new set, using it as new x. xNew = affectedBoundary.x2New; } if (xNew > maxXNew) { maxXNew = xNew; } } // Set new x1 for current boundary. boundary.x1New = maxXNew; // Adjusts new x2 for the affected boundaries. for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New === undefined) { // Was not set yet, choosing new x if possible. if (affectedBoundary.x2 > boundary.x1) { // Current and affected boundaries intersect. If affected boundary // is placed on top of the current, shrinking the affected. if (affectedBoundary.index > boundary.index) { affectedBoundary.x2New = affectedBoundary.x2; } } else { affectedBoundary.x2New = maxXNew; } } else if (affectedBoundary.x2New > maxXNew) { // Affected boundary is touching new x, pushing it back. affectedBoundary.x2New = Math.max(maxXNew, affectedBoundary.x2); } } // Fixing the horizon. var changedHorizon = [], lastBoundary = null; for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; // Checking which boundary will be visible. var useBoundary = affectedBoundary.x2 > boundary.x2 ? affectedBoundary : boundary; if (lastBoundary === useBoundary) { // Merging with previous. changedHorizon[changedHorizon.length - 1].end = horizonPart.end; } else { changedHorizon.push({ start: horizonPart.start, end: horizonPart.end, boundary: useBoundary }); lastBoundary = useBoundary; } } if (horizon[i].start < boundary.y1) { changedHorizon[0].start = boundary.y1; changedHorizon.unshift({ start: horizon[i].start, end: boundary.y1, boundary: horizon[i].boundary }); } if (boundary.y2 < horizon[j].end) { changedHorizon[changedHorizon.length - 1].end = boundary.y2; changedHorizon.push({ start: boundary.y2, end: horizon[j].end, boundary: horizon[j].boundary }); } // Set x2 new of boundary that is no longer visible (see overlapping case // above). // TODO more efficient, e.g. via reference counting. for (q = i; q <= j; q++) { horizonPart = horizon[q]; affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New !== undefined) { continue; } var used = false; for (k = i - 1; !used && k >= 0 && horizon[k].start >= affectedBoundary.y1; k--) { used = horizon[k].boundary === affectedBoundary; } for (k = j + 1; !used && k < horizon.length && horizon[k].end <= affectedBoundary.y2; k++) { used = horizon[k].boundary === affectedBoundary; } for (k = 0; !used && k < changedHorizon.length; k++) { used = changedHorizon[k].boundary === affectedBoundary; } if (!used) { affectedBoundary.x2New = maxXNew; } } Array.prototype.splice.apply(horizon, [i, j - i + 1].concat(changedHorizon)); }); // Set new x2 for all unset boundaries. horizon.forEach(function (horizonPart) { var affectedBoundary = horizonPart.boundary; if (affectedBoundary.x2New === undefined) { affectedBoundary.x2New = Math.max(width, affectedBoundary.x2); } }); } /** * Text layer rendering task. * * @param {TextContent} textContent * @param {HTMLElement} container * @param {PageViewport} viewport * @param {Array} textDivs * @param {boolean} enhanceTextSelection * @private */ function TextLayerRenderTask(textContent, container, viewport, textDivs, enhanceTextSelection) { this._textContent = textContent; this._container = container; this._viewport = viewport; this._textDivs = textDivs || []; this._textDivProperties = new WeakMap(); this._renderingDone = false; this._canceled = false; this._capability = createPromiseCapability(); this._renderTimer = null; this._bounds = []; this._enhanceTextSelection = !!enhanceTextSelection; } TextLayerRenderTask.prototype = { get promise() { return this._capability.promise; }, cancel: function TextLayer_cancel() { this._canceled = true; if (this._renderTimer !== null) { clearTimeout(this._renderTimer); this._renderTimer = null; } this._capability.reject('canceled'); }, _render: function TextLayer_render(timeout) { var textItems = this._textContent.items; var textStyles = this._textContent.styles; for (var i = 0, len = textItems.length; i < len; i++) { appendText(this, textItems[i], textStyles); } if (!timeout) { // Render right away render(this); } else { // Schedule var self = this; this._renderTimer = setTimeout(function() { render(self); self._renderTimer = null; }, timeout); } }, expandTextDivs: function TextLayer_expandTextDivs(expandDivs) { if (!this._enhanceTextSelection || !this._renderingDone) { return; } if (this._bounds !== null) { expand(this); this._bounds = null; } for (var i = 0, ii = this._textDivs.length; i < ii; i++) { var div = this._textDivs[i]; var divProperties = this._textDivProperties.get(div); if (divProperties.isWhitespace) { continue; } if (expandDivs) { var transform = '', padding = ''; if (divProperties.scale !== 1) { transform = 'scaleX(' + divProperties.scale + ')'; } if (divProperties.angle !== 0) { transform = 'rotate(' + divProperties.angle + 'deg) ' + transform; } if (divProperties.paddingLeft !== 0) { padding += ' padding-left: ' + (divProperties.paddingLeft / divProperties.scale) + 'px;'; transform += ' translateX(' + (-divProperties.paddingLeft / divProperties.scale) + 'px)'; } if (divProperties.paddingTop !== 0) { padding += ' padding-top: ' + divProperties.paddingTop + 'px;'; transform += ' translateY(' + (-divProperties.paddingTop) + 'px)'; } if (divProperties.paddingRight !== 0) { padding += ' padding-right: ' + (divProperties.paddingRight / divProperties.scale) + 'px;'; } if (divProperties.paddingBottom !== 0) { padding += ' padding-bottom: ' + divProperties.paddingBottom + 'px;'; } if (padding !== '') { div.setAttribute('style', divProperties.style + padding); } if (transform !== '') { CustomStyle.setProp('transform', div, transform); } } else { div.style.padding = 0; CustomStyle.setProp('transform', div, divProperties.originalTransform || ''); } } }, }; /** * Starts rendering of the text layer. * * @param {TextLayerRenderParameters} renderParameters * @returns {TextLayerRenderTask} */ function renderTextLayer(renderParameters) { var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs, renderParameters.enhanceTextSelection); task._render(renderParameters.timeout); return task; } return renderTextLayer; })(); exports.renderTextLayer = renderTextLayer; })); (function (root, factory) { { factory((root.pdfjsDisplayWebGL = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayDOMUtils) { var shadow = sharedUtil.shadow; var getDefaultSetting = displayDOMUtils.getDefaultSetting; var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[j]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if (getDefaultSetting('disableWebGL')) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); exports.WebGLUtils = WebGLUtils; })); (function (root, factory) { { factory((root.pdfjsDisplayPatternHelper = {}), root.pdfjsSharedUtil, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayWebGL) { var Util = sharedUtil.Util; var info = sharedUtil.info; var isArray = sharedUtil.isArray; var error = sharedUtil.error; var WebGLUtils = displayWebGL.WebGLUtils; var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough // We need to keep transparent border around our pattern for fill(): // createPattern with 'no-repeat' will bleed edges across entire area. var BORDER_SIZE = 2; var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var paddedWidth = width + BORDER_SIZE * 2; var paddedHeight = height + BORDER_SIZE * 2; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false); tmpCanvas.context.drawImage(canvas, BORDER_SIZE, BORDER_SIZE); canvas = tmpCanvas.canvas; } else { tmpCanvas = cachedCanvases.getCanvas('mesh', paddedWidth, paddedHeight, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, BORDER_SIZE, BORDER_SIZE); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX - BORDER_SIZE * scaleX, offsetY: offsetY - BORDER_SIZE * scaleY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { //var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; //var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { // Obtain scale from matrix and current transformation matrix. scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, canvasGraphicsFactory, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.canvasGraphicsFactory = canvasGraphicsFactory; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var canvasGraphicsFactory = this.canvasGraphicsFactory; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = canvasGraphicsFactory.createCanvasGraphics(tmpCtx); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); exports.getShadingPatternFromIR = getShadingPatternFromIR; exports.TilingPattern = TilingPattern; })); (function (root, factory) { { factory((root.pdfjsDisplayCanvas = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayPatternHelper, root.pdfjsDisplayWebGL); } }(this, function (exports, sharedUtil, displayDOMUtils, displayPatternHelper, displayWebGL) { var FONT_IDENTITY_MATRIX = sharedUtil.FONT_IDENTITY_MATRIX; var IDENTITY_MATRIX = sharedUtil.IDENTITY_MATRIX; var ImageKind = sharedUtil.ImageKind; var OPS = sharedUtil.OPS; var TextRenderingMode = sharedUtil.TextRenderingMode; var Uint32ArrayView = sharedUtil.Uint32ArrayView; var Util = sharedUtil.Util; var assert = sharedUtil.assert; var info = sharedUtil.info; var isNum = sharedUtil.isNum; var isArray = sharedUtil.isArray; var isLittleEndian = sharedUtil.isLittleEndian; var error = sharedUtil.error; var shadow = sharedUtil.shadow; var warn = sharedUtil.warn; var TilingPattern = displayPatternHelper.TilingPattern; var getShadingPatternFromIR = displayPatternHelper.getShadingPatternFromIR; var WebGLUtils = displayWebGL.WebGLUtils; var hasCanvasTypedArrays = displayDOMUtils.hasCanvasTypedArrays; // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; // Maximum font size that would be used during canvas fillText operations. var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; // Heuristic value used when enforcing minimum line widths. var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; var HasCanvasTypedArraysCached = { get value() { return shadow(HasCanvasTypedArraysCached, 'value', hasCanvasTypedArrays()); } }; var IsLittleEndianCached = { get value() { return shadow(IsLittleEndianCached, 'value', isLittleEndian()); } }; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based one. if (!ctx.mozCurrentTransform) { ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { function CachedCanvases() { this.cache = Object.create(null); } CachedCanvases.prototype = { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (this.cache[id] !== undefined) { canvasEntry = this.cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } this.cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { for (var id in this.cache) { var canvasEntry = this.cache[id]; // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. canvasEntry.canvas.width = 0; canvasEntry.canvas.height = 0; delete this.cache[id]; } } }; return CachedCanvases; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; this.resumeSMaskCtx = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; // Defines the number of steps before checking the execution time var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; this.cachedCanvases = new CachedCanvases(); if (canvasCtx) { // NOTE: if mozCurrentTransform is polyfilled, then the current state of // the transformation must already be set in canvasCtx._transformMatrix. addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var srcLength = src.byteLength; var dest32 = HasCanvasTypedArraysCached.value ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (IsLittleEndianCached.value || !HasCanvasTypedArraysCached.value) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8; } } } function composeSMaskAlpha(maskData, layerData, transferMap) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; layerData[i] = (layerData[i] * alpha * scale) | 0; } } function composeSMaskLuminosity(maskData, layerData, transferMap) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskData[i - 2] * 152) + // * 0.59 .... (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = transferMap ? (layerData[i] * transferMap[y >> 8]) >> 8 : (layerData[i] * y) >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data, transferMap); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (!smask.transferMap && WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, creating temporary // transparent canvas when we have blend modes. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); if (transparency) { var transparentCanvas = this.cachedCanvases.getCanvas( 'transparent', width, height, true); this.compositeCtx = this.ctx; this.transparentCanvas = transparentCanvas.canvas; this.ctx = transparentCanvas.context; this.ctx.save(); // The transform can be applied before rendering, transferring it to // the new canvas. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); } this.ctx.save(); if (transform) { this.ctx.transform.apply(this.ctx, transform); } this.ctx.transform.apply(this.ctx, viewport.transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen === i) { return i; } var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'); var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i === argsArrayLen) { return i; } // If the execution took longer then a certain amount of time and // `continueCallback` is specified, interrupt the execution. if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { // Finishing all opened operations such as SMask group painting. if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.ctx.restore(); if (this.transparentCanvas) { this.ctx = this.compositeCtx; this.ctx.save(); this.ctx.setTransform(1, 0, 0, 1, 0, 0); // Avoid apply transform twice this.ctx.drawImage(this.transparentCanvas, 0, 0); this.ctx.restore(); this.transparentCanvas = null; } this.cachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { // If SMask is currrenly used, it needs to be suspended or // finished. Suspend only makes sense when at least one save() // was performed and state needs to be reverted on restore(). if (this.stateStack.length > 0 && (this.stateStack[this.stateStack.length - 1].activeSMask === this.current.activeSMask)) { this.suspendSMaskGroup(); } else { this.endSMaskGroup(); } } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); activeSMask.startTransformInverse = groupCtx.mozCurrentTransformInverse; copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, suspendSMaskGroup: function CanvasGraphics_endSMaskGroup() { // Similar to endSMaskGroup, the intermediate canvas has to be composed // and future ctx state restored. var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); this.ctx.save(); // save is needed since SMask will be resumed. copyCtxState(groupCtx, this.ctx); // Saving state for resuming. this.current.resumeSMaskCtx = groupCtx; // Transform was changed in the SMask canvas, reflecting this change on // this.ctx. var deltaTransform = Util.transform( this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform); this.ctx.transform.apply(this.ctx, deltaTransform); // SMask was composed, the results at the groupCtx can be cleared. groupCtx.save(); groupCtx.setTransform(1, 0, 0, 1, 0, 0); groupCtx.clearRect(0, 0, groupCtx.canvas.width, groupCtx.canvas.height); groupCtx.restore(); }, resumeSMaskGroup: function CanvasGraphics_endSMaskGroup() { // Resuming state saved by suspendSMaskGroup. We don't need to restore // any groupCtx state since restore() command (the only caller) will do // that for us. See also beginSMaskGroup. var groupCtx = this.current.resumeSMaskCtx; var currentCtx = this.ctx; this.ctx = groupCtx; this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); copyCtxState(groupCtx, this.ctx); // Transform was changed in the SMask canvas, reflecting this change on // this.ctx. var deltaTransform = Util.transform( this.current.activeSMask.startTransformInverse, groupCtx.mozCurrentTransform); this.ctx.transform.apply(this.ctx, deltaTransform); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.resumeSMaskCtx = null; }, restore: function CanvasGraphics_restore() { // SMask was suspended, we just need to resume it. if (this.current.resumeSMaskCtx) { this.resumeSMaskGroup(); } // SMask has to be finished once there is no states that are using the // same SMask. if (this.current.activeSMask !== null && (this.stateStack.length === 0 || this.stateStack[this.stateStack.length - 1].activeSMask !== this.current.activeSMask)) { this.endSMaskGroup(); } if (this.stateStack.length !== 0) { this.current = this.stateStack.pop(); this.ctx.restore(); // Ensure that the clipping path is reset (fixes issue6413.pdf). this.pendingClip = null; this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, // Path constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; // Prevent drawing too thin lines by enforcing a minimum line width. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); if (this.baseTransform) { ctx.setTransform.apply(ctx, this.baseTransform); } ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.fill(); ctx.mozFillRule = 'nonzero'; } else { ctx.fill('evenodd'); } this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var spacingDir = vertical ? 1 : -1; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (current.patternFill) { // TODO: Some shading patterns are not applied correctly to text, // e.g. issues 3988 and 5432, and ShowText-ShadingPattern.pdf. ctx.fillStyle = current.fillColor.getPattern(ctx, this); } if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (isNum(glyph)) { x += spacingDir * glyph * fontSize / 1000; continue; } var restoreNeeded = false; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0) { // Some standard fonts may not have the exact width: rescale per // character if measured width is greater than expected glyph width // and subpixel-aa is enabled, otherwise just center the glyph. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; if (width < measuredWidth && this.isFontSubpixelAAEnabled) { var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } else if (width !== measuredWidth) { scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; } } // Only attempt to draw the glyph if it is actually in the embedded font // file or if there isn't a font file so the fallback font is shown. if (glyph.isInFont || font.missingFile) { if (simpleFillText && !accent) { // common case ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } } var charWidth = width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { // Type3 fonts - each glyph is a "mini-PDF" var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var spacingDir = font.vertical ? 1 : -1; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width, spacingLength; if (isTextInvisible || fontSize === 0) { return; } this.cachedGetSinglePixelWidth = null; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (isNum(glyph)) { spacingLength = spacingDir * glyph * fontSize / 1000; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { warn('Type3 character \"' + glyph.operatorListId + '\" is not available'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + spacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); var self = this; var canvasGraphicsFactory = { createCanvasGraphics: function (ctx) { return new CanvasGraphics(ctx, self.commonObjs, self.objs); } }; pattern = new TilingPattern(IR, color, this.ctx, canvasGraphicsFactory, baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (isArray(matrix) && 6 === matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (isArray(bbox) && 4 === bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implementing: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, transferMap: group.smask.transferMap || null, startTransformInverse: null, // used during suspend operation }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; // Reseting mask state, masks will be applied on restore of the group. this.current.activeSMask = null; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); if (this.baseTransform) { this.ctx.setTransform.apply(this.ctx, this.baseTransform); } }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (isArray(rect) && 4 === rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, paintXObject: function CanvasGraphics_paintXObject() { warn('Unsupported \'paintXObject\' command.'); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.clip(); ctx.mozFillRule = 'nonzero'; } else { ctx.clip('evenodd'); } } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { // NOTE: The `save` and `restore` commands used below is a workaround // that is necessary in order to prevent `mozCurrentTransformInverse` // from intermittently returning incorrect values in Firefox, see: // https://github.com/mozilla/pdf.js/issues/7188. this.ctx.save(); var inverse = this.ctx.mozCurrentTransformInverse; this.ctx.restore(); // max of the current horizontal and vertical scale this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); exports.CanvasGraphics = CanvasGraphics; exports.createScratchCanvas = createScratchCanvas; })); (function (root, factory) { { factory((root.pdfjsDisplayAPI = {}), root.pdfjsSharedUtil, root.pdfjsDisplayFontLoader, root.pdfjsDisplayCanvas, root.pdfjsDisplayMetadata, root.pdfjsDisplayDOMUtils); } }(this, function (exports, sharedUtil, displayFontLoader, displayCanvas, displayMetadata, displayDOMUtils, amdRequire) { var InvalidPDFException = sharedUtil.InvalidPDFException; var MessageHandler = sharedUtil.MessageHandler; var MissingPDFException = sharedUtil.MissingPDFException; var PageViewport = sharedUtil.PageViewport; var PasswordResponses = sharedUtil.PasswordResponses; var PasswordException = sharedUtil.PasswordException; var StatTimer = sharedUtil.StatTimer; var UnexpectedResponseException = sharedUtil.UnexpectedResponseException; var UnknownErrorException = sharedUtil.UnknownErrorException; var Util = sharedUtil.Util; var createPromiseCapability = sharedUtil.createPromiseCapability; var error = sharedUtil.error; var deprecated = sharedUtil.deprecated; var getVerbosityLevel = sharedUtil.getVerbosityLevel; var info = sharedUtil.info; var isInt = sharedUtil.isInt; var isArray = sharedUtil.isArray; var isArrayBuffer = sharedUtil.isArrayBuffer; var isSameOrigin = sharedUtil.isSameOrigin; var loadJpegStream = sharedUtil.loadJpegStream; var stringToBytes = sharedUtil.stringToBytes; var globalScope = sharedUtil.globalScope; var warn = sharedUtil.warn; var FontFaceObject = displayFontLoader.FontFaceObject; var FontLoader = displayFontLoader.FontLoader; var CanvasGraphics = displayCanvas.CanvasGraphics; var createScratchCanvas = displayCanvas.createScratchCanvas; var Metadata = displayMetadata.Metadata; var getDefaultSetting = displayDOMUtils.getDefaultSetting; var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536 var isWorkerDisabled = false; var workerSrc; var isPostMessageTransfersDisabled = false; var useRequireEnsure = false; if (typeof window === 'undefined') { // node.js - disable worker and set require.ensure. isWorkerDisabled = true; if (typeof require.ensure === 'undefined') { require.ensure = require('node-ensure'); } useRequireEnsure = true; } if (typeof __webpack_require__ !== 'undefined') { useRequireEnsure = true; } if (typeof requirejs !== 'undefined' && requirejs.toUrl) { workerSrc = requirejs.toUrl('pdfjs-dist/build/pdf.worker.js'); } var dynamicLoaderSupported = typeof requirejs !== 'undefined' && requirejs.load; var fakeWorkerFilesLoader = useRequireEnsure ? (function (callback) { require.ensure([], function () { var worker = require('./pdf.worker.js'); callback(worker.WorkerMessageHandler); }); }) : dynamicLoaderSupported ? (function (callback) { requirejs(['pdfjs-dist/build/pdf.worker'], function (worker) { callback(worker.WorkerMessageHandler); }); }) : null; /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded, * use atob() to convert it to a binary string first. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. * @property {number} length - The PDF file length. It's used for progress * reports and range requests operations. * @property {PDFDataRangeTransport} range * @property {number} rangeChunkSize - Optional parameter to specify * maximum number of bytes fetched per range request. The default value is * 2^16 = 65536. * @property {PDFWorker} worker - The worker that will be used for the loading * and parsing of the PDF data. */ /** * @typedef {Object} PDFDocumentStats * @property {Array} streamTypes - Used stream types in the document (an item * is set to true if specific stream ID was used in the document). * @property {Array} fontTypes - Used font type in the document (an item is set * to true if specific font ID was used in the document). */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src * Can be a url to where a PDF is located, a typed array (Uint8Array) * already populated with data or parameter object. * * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used * if you want to manually serve range requests for data in the PDF. * * @param {function} passwordCallback (deprecated) It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @param {function} progressCallback (deprecated) It is used to be able to * monitor the loading progress of the PDF file (necessary to implement e.g. * a loading bar). The callback receives an {Object} with the properties: * {number} loaded and {number} total. * * @return {PDFDocumentLoadingTask} */ function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { var task = new PDFDocumentLoadingTask(); // Support of the obsolete arguments (for compatibility with API v1.0) if (arguments.length > 1) { deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument'); } if (pdfDataRangeTransport) { if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { // Not a PDFDataRangeTransport instance, trying to add missing properties. pdfDataRangeTransport = Object.create(pdfDataRangeTransport); pdfDataRangeTransport.length = src.length; pdfDataRangeTransport.initialData = src.initialData; if (!pdfDataRangeTransport.abort) { pdfDataRangeTransport.abort = function () {}; } } src = Object.create(src); src.range = pdfDataRangeTransport; } task.onPassword = passwordCallback || null; task.onProgress = progressCallback || null; var source; if (typeof src === 'string') { source = { url: src }; } else if (isArrayBuffer(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if (typeof src !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!src.url && !src.data && !src.range) { error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; var rangeTransport = null; var worker = null; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { // The full path is required in the 'url' field. params[key] = new URL(source[key], window.location).href; continue; } else if (key === 'range') { rangeTransport = source[key]; continue; } else if (key === 'worker') { worker = source[key]; continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { // Converting string or array-like data to Uint8Array. var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = stringToBytes(pdfBytes); } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else if (isArrayBuffer(pdfBytes)) { params[key] = new Uint8Array(pdfBytes); } else { error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.'); } continue; } params[key] = source[key]; } params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; if (!worker) { // Worker was not provided -- creating and owning our own. worker = new PDFWorker(); task._worker = worker; } var docId = task.docId; worker.promise.then(function () { if (task.destroyed) { throw new Error('Loading aborted'); } return _fetchDocument(worker, params, rangeTransport, docId).then( function (workerId) { if (task.destroyed) { throw new Error('Loading aborted'); } var messageHandler = new MessageHandler(docId, workerId, worker.port); var transport = new WorkerTransport(messageHandler, task, rangeTransport); task._transport = transport; messageHandler.send('Ready', null); }); }).catch(task._capability.reject); return task; } /** * Starts fetching of specified PDF document/data. * @param {PDFWorker} worker * @param {Object} source * @param {PDFDataRangeTransport} pdfDataRangeTransport * @param {string} docId Unique document id, used as MessageHandler id. * @returns {Promise} The promise, which is resolved when worker id of * MessageHandler is known. * @private */ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { if (worker.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } source.disableAutoFetch = getDefaultSetting('disableAutoFetch'); source.disableStream = getDefaultSetting('disableStream'); source.chunkedViewerLoading = !!pdfDataRangeTransport; if (pdfDataRangeTransport) { source.length = pdfDataRangeTransport.length; source.initialData = pdfDataRangeTransport.initialData; } return worker.messageHandler.sendWithPromise('GetDocRequest', { docId: docId, source: source, disableRange: getDefaultSetting('disableRange'), maxImageSize: getDefaultSetting('maxImageSize'), cMapUrl: getDefaultSetting('cMapUrl'), cMapPacked: getDefaultSetting('cMapPacked'), disableFontFace: getDefaultSetting('disableFontFace'), disableCreateObjectURL: getDefaultSetting('disableCreateObjectURL'), postMessageTransfers: getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled, }).then(function (workerId) { if (worker.destroyed) { throw new Error('Worker was destroyed'); } return workerId; }); } /** * PDF document loading operation. * @class * @alias PDFDocumentLoadingTask */ var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { var nextDocumentId = 0; /** @constructs PDFDocumentLoadingTask */ function PDFDocumentLoadingTask() { this._capability = createPromiseCapability(); this._transport = null; this._worker = null; /** * Unique document loading task id -- used in MessageHandlers. * @type {string} */ this.docId = 'd' + (nextDocumentId++); /** * Shows if loading task is destroyed. * @type {boolean} */ this.destroyed = false; /** * Callback to request a password if wrong or no password was provided. * The callback receives two parameters: function that needs to be called * with new password and reason (see {PasswordResponses}). */ this.onPassword = null; /** * Callback to be able to monitor the loading progress of the PDF file * (necessary to implement e.g. a loading bar). The callback receives * an {Object} with the properties: {number} loaded and {number} total. */ this.onProgress = null; /** * Callback to when unsupported feature is used. The callback receives * an {UNSUPPORTED_FEATURES} argument. */ this.onUnsupportedFeature = null; } PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */ { /** * @return {Promise} */ get promise() { return this._capability.promise; }, /** * Aborts all network requests and destroys worker. * @return {Promise} A promise that is resolved after destruction activity * is completed. */ destroy: function () { this.destroyed = true; var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); return transportDestroyed.then(function () { this._transport = null; if (this._worker) { this._worker.destroy(); this._worker = null; } }.bind(this)); }, /** * Registers callbacks to indicate the document loading completion. * * @param {function} onFulfilled The callback for the loading completion. * @param {function} onRejected The callback for the loading failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; })(); /** * Abstract class to support range requests file loading. * @class * @alias PDFDataRangeTransport * @param {number} length * @param {Uint8Array} initialData */ var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() { function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = createPromiseCapability(); } PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */ { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { this._readyCapability.promise.then(function () { var listeners = this._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }.bind(this)); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { this._readyCapability.promise.then(function () { var listeners = this._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }.bind(this)); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); }, abort: function PDFDataRangeTransport_abort() { } }; return PDFDataRangeTransport; })(); /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class * @alias PDFDocumentProxy */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport, loadingTask) { this.pdfInfo = pdfInfo; this.transport = transport; this.loadingTask = loadingTask; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. * * This can be slow for large documents: use getDestination instead */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @param {string} id The named destination to get. * @return {Promise} A promise that is resolved with all information * of the given named destination. */ getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, /** * @return {Promise} A promise that is resolved with: * an Array containing the pageLabels that correspond to the pageIndexes, * or `null` when no pageLabels are present in the PDF file. */ getPageLabels: function PDFDocumentProxy_getPageLabels() { return this.transport.getPageLabels(); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named attachments to their content. */ getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { return this.transport.getJavaScript(); }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb Uint8Array, * dest: dest obj, * url: string, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, /** * @return {Promise} A promise this is resolved with current stats about * document structures (see {@link PDFDocumentStats}). */ getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { return this.loadingTask.destroy(); } }; return PDFDocumentProxy; })(); /** * Page getTextContent parameters. * * @typedef {Object} getTextContentParameters * @param {boolean} normalizeWhitespace - replaces all occurrences of * whitespace with standard spaces (0x20). The default value is `false`. * @param {boolean} disableCombineTextItems - do not attempt to combine * same line {@link TextItem}'s. The default value is `false`. */ /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page annotation parameters. * * @typedef {Object} GetAnnotationsParameters * @param {string} intent - Determines the annotations that will be fetched, * can be either 'display' (viewable annotations) or 'print' * (printable annotations). * If the parameter is omitted, all annotations are fetched. */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {boolean} renderInteractiveForms - (optional) Whether or not * interactive form elements are rendered in the display * layer. If so, we do not render them on canvas as well. * @property {Array} transform - (optional) Additional transform, applied * just before viewport transform. * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (deprecated) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * PDF page operator list. * * @typedef {Object} PDFOperatorList * @property {Array} fnArray - Array containing the operator functions. * @property {Array} argsArray - Array containing the arguments of the * functions. */ /** * Proxy to a PDFPage in the worker thread. * @class * @alias PDFPageProxy */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = getDefaultSetting('enableStats'); this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingCleanup = false; this.intentStates = Object.create(null); this.destroyed = false; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PageViewport(this.view, scale, rotate, 0, 0); }, /** * @param {GetAnnotationsParameters} params - Annotation parameters. * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations(params) { var intent = (params && params.intent) || null; if (!this.annotationsPromise || this.annotationsIntent !== intent) { this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent); this.annotationsIntent = intent; } return this.annotationsPromise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingCleanup = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); var renderInteractiveForms = (params.renderInteractiveForms === true ? true : /* Default */ false); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = Object.create(null); } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent, renderInteractiveForms: renderInteractiveForms, }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { deprecated('render is used with continueCallback parameter'); renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingCleanup) { complete(); return; } stats.time('Rendering'); internalRenderTask.initializeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingCleanup = true; } self._tryCleanup(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} A promise resolved with an {@link PDFOperatorList} * object that represents page's operator list. */ getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); var i = intentState.renderTasks.indexOf(opListTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = Object.create(null); } var intentState = this.intentStates[renderingIntent]; var opListTask; if (!intentState.opListReadCapability) { opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = createPromiseCapability(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, /** * @param {getTextContentParameters} params - getTextContent parameters. * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent(params) { return this.transport.messageHandler.sendWithPromise('GetTextContent', { pageIndex: this.pageNumber - 1, normalizeWhitespace: (params && params.normalizeWhitespace === true ? true : /* Default */ false), combineTextItems: (params && params.disableCombineTextItems === true ? false : /* Default */ true), }); }, /** * Destroys page object. */ _destroy: function PDFPageProxy_destroy() { this.destroyed = true; this.transport.pageCache[this.pageIndex] = null; var waitOn = []; Object.keys(this.intentStates).forEach(function(intent) { if (intent === 'oplist') { // Avoid errors below, since the renderTasks are just stubs. return; } var intentState = this.intentStates[intent]; intentState.renderTasks.forEach(function(renderTask) { var renderCompleted = renderTask.capability.promise. catch(function () {}); // ignoring failures waitOn.push(renderCompleted); renderTask.cancel(); }); }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; return Promise.all(waitOn); }, /** * Cleans up resources allocated by the page. (deprecated) */ destroy: function() { deprecated('page destroy method, use cleanup() instead'); this.cleanup(); }, /** * Cleans up resources allocated by the page. */ cleanup: function PDFPageProxy_cleanup() { this.pendingCleanup = true; this._tryCleanup(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryCleanup: function PDFPageProxy_tryCleanup() { if (!this.pendingCleanup || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; // TODO Refactor RenderPageRequest to separate rendering // and operator list logic if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryCleanup(); } } }; return PDFPageProxy; })(); /** * PDF.js web worker abstraction, it controls instantiation of PDF documents and * WorkerTransport for them. If creation of a web worker is not possible, * a "fake" worker will be used instead. * @class */ var PDFWorker = (function PDFWorkerClosure() { var nextFakeWorkerId = 0; function getWorkerSrc() { if (typeof workerSrc !== 'undefined') { return workerSrc; } if (getDefaultSetting('workerSrc')) { return getDefaultSetting('workerSrc'); } if (pdfjsFilePath) { return pdfjsFilePath.replace(/\.js$/i, '.worker.js'); } error('No PDFJS.workerSrc specified'); } var fakeWorkerFilesLoadedCapability; // Loads worker code into main thread. function setupFakeWorkerGlobal() { var WorkerMessageHandler; if (!fakeWorkerFilesLoadedCapability) { fakeWorkerFilesLoadedCapability = createPromiseCapability(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. var loader = fakeWorkerFilesLoader || function (callback) { Util.loadScript(getWorkerSrc(), function () { callback(window.pdfjsDistBuildPdfWorker.WorkerMessageHandler); }); }; loader(fakeWorkerFilesLoadedCapability.resolve); } return fakeWorkerFilesLoadedCapability.promise; } function FakeWorkerPort(defer) { this._listeners = []; this._defer = defer; this._deferred = Promise.resolve(undefined); } FakeWorkerPort.prototype = { postMessage: function (obj, transfers) { function cloneValue(value) { // Trying to perform a structured clone close to the spec, including // transfers. if (typeof value !== 'object' || value === null) { return value; } if (cloned.has(value)) { // already cloned the object return cloned.get(value); } var result; var buffer; if ((buffer = value.buffer) && isArrayBuffer(buffer)) { // We found object with ArrayBuffer (typed array). var transferable = transfers && transfers.indexOf(buffer) >= 0; if (value === buffer) { // Special case when we are faking typed arrays in compatibility.js. result = value; } else if (transferable) { result = new value.constructor(buffer, value.byteOffset, value.byteLength); } else { result = new value.constructor(value); } cloned.set(value, result); return result; } result = isArray(value) ? [] : {}; cloned.set(value, result); // adding to cache now for cyclic references // Cloning all value and object properties, however ignoring properties // defined via getter. for (var i in value) { var desc, p = value; while (!(desc = Object.getOwnPropertyDescriptor(p, i))) { p = Object.getPrototypeOf(p); } if (typeof desc.value === 'undefined' || typeof desc.value === 'function') { continue; } result[i] = cloneValue(desc.value); } return result; } if (!this._defer) { this._listeners.forEach(function (listener) { listener.call(this, {data: obj}); }, this); return; } var cloned = new WeakMap(); var e = {data: cloneValue(obj)}; this._deferred.then(function () { this._listeners.forEach(function (listener) { listener.call(this, e); }, this); }.bind(this)); }, addEventListener: function (name, listener) { this._listeners.push(listener); }, removeEventListener: function (name, listener) { var i = this._listeners.indexOf(listener); this._listeners.splice(i, 1); }, terminate: function () { this._listeners = []; } }; function createCDNWrapper(url) { // We will rely on blob URL's property to specify origin. // We want this function to fail in case if createObjectURL or Blob do not // exist or fail for some reason -- our Worker creation will fail anyway. var wrapper = 'importScripts(\'' + url + '\');'; return URL.createObjectURL(new Blob([wrapper])); } function PDFWorker(name) { this.name = name; this.destroyed = false; this._readyCapability = createPromiseCapability(); this._port = null; this._webWorker = null; this._messageHandler = null; this._initialize(); } PDFWorker.prototype = /** @lends PDFWorker.prototype */ { get promise() { return this._readyCapability.promise; }, get port() { return this._port; }, get messageHandler() { return this._messageHandler; }, _initialize: function PDFWorker_initialize() { // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fulfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an // Uint8Array as it arrives on the worker. (Chrome added this with v.15.) if (!isWorkerDisabled && !getDefaultSetting('disableWorker') && typeof Worker !== 'undefined') { var workerSrc = getWorkerSrc(); try { // Wraps workerSrc path into blob URL, if the former does not belong // to the same origin. if (!isSameOrigin(window.location.href, workerSrc)) { workerSrc = createCDNWrapper( new URL(workerSrc, window.location).href); } // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', 'worker', worker); var terminateEarly = function() { worker.removeEventListener('error', onWorkerError); messageHandler.destroy(); worker.terminate(); if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); } else { // Fall back to fake worker if the termination is caused by an // error (e.g. NetworkError / SecurityError). this._setupFakeWorker(); } }.bind(this); var onWorkerError = function(event) { if (!this._webWorker) { // Worker failed to initialize due to an error. Clean up and fall // back to the fake worker. terminateEarly(); } }.bind(this); worker.addEventListener('error', onWorkerError); messageHandler.on('test', function PDFWorker_test(data) { worker.removeEventListener('error', onWorkerError); if (this.destroyed) { terminateEarly(); return; // worker was destroyed } var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this._messageHandler = messageHandler; this._port = worker; this._webWorker = worker; if (!data.supportTransfers) { isPostMessageTransfersDisabled = true; } this._readyCapability.resolve(); // Send global setting, e.g. verbosity level. messageHandler.send('configure', { verbosity: getVerbosityLevel() }); } else { this._setupFakeWorker(); messageHandler.destroy(); worker.terminate(); } }.bind(this)); messageHandler.on('console_log', function (data) { console.log.apply(console, data); }); messageHandler.on('console_error', function (data) { console.error.apply(console, data); }); messageHandler.on('ready', function (data) { worker.removeEventListener('error', onWorkerError); if (this.destroyed) { terminateEarly(); return; // worker was destroyed } try { sendTest(); } catch (e) { // We need fallback to a faked worker. this._setupFakeWorker(); } }.bind(this)); var sendTest = function () { var postMessageTransfers = getDefaultSetting('postMessageTransfers') && !isPostMessageTransfersDisabled; var testObj = new Uint8Array([postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } }; // It might take time for worker to initialize (especially when AMD // loader is used). We will try to send test immediately, and then // when 'ready' message will arrive. The worker shall process only // first received 'test'. sendTest(); return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. this._setupFakeWorker(); }, _setupFakeWorker: function PDFWorker_setupFakeWorker() { if (!isWorkerDisabled && !getDefaultSetting('disableWorker')) { warn('Setting up fake worker.'); isWorkerDisabled = true; } setupFakeWorkerGlobal().then(function (WorkerMessageHandler) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); return; } // We cannot turn on proper fake port simulation (this includes // structured cloning) when typed arrays are not supported. Relying // on a chance that messages will be sent in proper order. var isTypedArraysPresent = Uint8Array !== Float32Array; var port = new FakeWorkerPort(isTypedArraysPresent); this._port = port; // All fake workers use the same port, making id unique. var id = 'fake' + (nextFakeWorkerId++); // If the main thread is our worker, setup the handling for the // messages -- the main thread sends to it self. var workerHandler = new MessageHandler(id + '_worker', id, port); WorkerMessageHandler.setup(workerHandler, port); var messageHandler = new MessageHandler(id, id + '_worker', port); this._messageHandler = messageHandler; this._readyCapability.resolve(); }.bind(this)); }, /** * Destroys the worker instance. */ destroy: function PDFWorker_destroy() { this.destroyed = true; if (this._webWorker) { // We need to terminate only web worker created resource. this._webWorker.terminate(); this._webWorker = null; } this._port = null; if (this._messageHandler) { this._messageHandler.destroy(); this._messageHandler = null; } } }; return PDFWorker; })(); /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) { this.messageHandler = messageHandler; this.loadingTask = loadingTask; this.pdfDataRangeTransport = pdfDataRangeTransport; this.commonObjs = new PDFObjects(); this.fontLoader = new FontLoader(loadingTask.docId); this.destroyed = false; this.destroyCapability = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = createPromiseCapability(); this.setupMessageHandler(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { if (this.destroyCapability) { return this.destroyCapability.promise; } this.destroyed = true; this.destroyCapability = createPromiseCapability(); var waitOn = []; // We need to wait for all renderings to be completed, e.g. // timeout/rAF can take a long time. this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } }); this.pageCache = []; this.pagePromises = []; var self = this; // We also need to wait for the worker to finish its long running tasks. var terminated = this.messageHandler.sendWithPromise('Terminate', null); waitOn.push(terminated); Promise.all(waitOn).then(function () { self.fontLoader.clear(); if (self.pdfDataRangeTransport) { self.pdfDataRangeTransport.abort(); self.pdfDataRangeTransport = null; } if (self.messageHandler) { self.messageHandler.destroy(); self.messageHandler = null; } self.destroyCapability.resolve(); }, this.destroyCapability.reject); return this.destroyCapability.promise; }, setupMessageHandler: function WorkerTransport_setupMessageHandler() { var messageHandler = this.messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); pdfDataRangeTransport.addProgressiveReadListener(function(chunk) { messageHandler.send('OnDataRange', { chunk: chunk }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var loadingTask = this.loadingTask; var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask); this.pdfDocument = pdfDocument; loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportNeedPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject( new InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject( new MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject( new UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject( new UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) { if (this.pdfDataRangeTransport) { this.pdfDataRangeTransport.transportReady(); } }, this); messageHandler.on('StartRenderPage', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; if ('error' in exportedData) { var exportedError = exportedData.error; warn('Error during font loading: ' + exportedError); this.commonObjs.resolve(id, exportedError); break; } var fontRegistry = null; if (getDefaultSetting('pdfBug') && globalScope.FontInspector && globalScope['FontInspector'].enabled) { fontRegistry = { registerFont: function (font, url) { globalScope['FontInspector'].fontAdded(font, url); } }; } var font = new FontFaceObject(exportedData, { isEvalSuported: getDefaultSetting('isEvalSupported'), disableFontFace: getDefaultSetting('disableFontFace'), fontRegistry: fontRegistry }); this.fontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { error(data.error); } if (intentState.operatorList) { // Mark operator list as complete. intentState.operatorList.lastChunk = true; for (var i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } } }, this); messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var featureId = data.featureId; var loadingTask = this.loadingTask; if (loadingTask.onUnsupportedFeature) { loadingTask.onUnsupportedFeature(featureId); } _UnsupportedManager.notify(featureId); }, this); messageHandler.on('JpegDecode', function(data) { if (this.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject( new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height}); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }, this); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { if (!isInt(pageNumber) || pageNumber <= 0 || pageNumber > this.numPages) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { if (this.destroyed) { throw new Error('Transport destroyed'); } var page = new PDFPageProxy(pageIndex, pageInfo, this); this.pageCache[pageIndex] = page; return page; }.bind(this)); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref, }).catch(function (reason) { return Promise.reject(new Error(reason)); }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex, intent: intent, }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id }); }, getPageLabels: function WorkerTransport_getPageLabels() { return this.messageHandler.sendWithPromise('GetPageLabels', null); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null). then(function transportMetadata(results) { return { info: results[0], metadata: (results[1] ? new Metadata(results[1]) : null) }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.sendWithPromise('Cleanup', null). then(function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.cleanup(); } } this.commonObjs.clear(); this.fontLoader.clear(); }.bind(this)); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = Object.create(null); } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: createPromiseCapability(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = Object.create(null); } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class * @alias RenderTask */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ this.onContinue = null; } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Promise for rendering task completion. * @return {Promise} */ get promise() { return this._internalRenderTask.capability.promise; }, /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, /** * Registers callbacks to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.useRequestAnimationFrame = false; this.cancelled = false; this.capability = createPromiseCapability(); this.task = new RenderTask(this); // caching this-bound methods this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); } InternalRenderTask.prototype = { initializeGraphics: function InternalRenderTask_initializeGraphics(transparency) { if (this.cancelled) { return; } if (getDefaultSetting('pdfBug') && globalScope.StepperManager && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.transform, params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue.call(this.task, this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { if (this.useRequestAnimationFrame && typeof window !== 'undefined') { window.requestAnimationFrame(this._nextBound); } else { Promise.resolve(undefined).then(this._nextBound); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); /** * (Deprecated) Global observer of unsupported feature usages. Use * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance. */ var _UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead'); listeners.push(cb); }, notify: function (featureId) { for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); if (typeof pdfjsVersion !== 'undefined') { exports.version = pdfjsVersion; } if (typeof pdfjsBuild !== 'undefined') { exports.build = pdfjsBuild; } exports.getDocument = getDocument; exports.PDFDataRangeTransport = PDFDataRangeTransport; exports.PDFWorker = PDFWorker; exports.PDFDocumentProxy = PDFDocumentProxy; exports.PDFPageProxy = PDFPageProxy; exports._UnsupportedManager = _UnsupportedManager; })); (function (root, factory) { { factory((root.pdfjsDisplayGlobal = {}), root.pdfjsSharedUtil, root.pdfjsDisplayDOMUtils, root.pdfjsDisplayAPI, root.pdfjsDisplayAnnotationLayer, root.pdfjsDisplayTextLayer, root.pdfjsDisplayMetadata, root.pdfjsDisplaySVG); } }(this, function (exports, sharedUtil, displayDOMUtils, displayAPI, displayAnnotationLayer, displayTextLayer, displayMetadata, displaySVG) { var globalScope = sharedUtil.globalScope; var deprecated = sharedUtil.deprecated; var warn = sharedUtil.warn; var LinkTarget = displayDOMUtils.LinkTarget; var isWorker = (typeof window === 'undefined'); // The global PDFJS object is now deprecated and will not be supported in // the future. The members below are maintained for backward compatibility // and shall not be extended or modified. If the global.js is included as // a module, we will create a global PDFJS object instance or use existing. if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } var PDFJS = globalScope.PDFJS; if (typeof pdfjsVersion !== 'undefined') { PDFJS.version = pdfjsVersion; } if (typeof pdfjsBuild !== 'undefined') { PDFJS.build = pdfjsBuild; } PDFJS.pdfBug = false; if (PDFJS.verbosity !== undefined) { sharedUtil.setVerbosityLevel(PDFJS.verbosity); } delete PDFJS.verbosity; Object.defineProperty(PDFJS, 'verbosity', { get: function () { return sharedUtil.getVerbosityLevel(); }, set: function (level) { sharedUtil.setVerbosityLevel(level); }, enumerable: true, configurable: true }); PDFJS.VERBOSITY_LEVELS = sharedUtil.VERBOSITY_LEVELS; PDFJS.OPS = sharedUtil.OPS; PDFJS.UNSUPPORTED_FEATURES = sharedUtil.UNSUPPORTED_FEATURES; PDFJS.isValidUrl = sharedUtil.isValidUrl; PDFJS.shadow = sharedUtil.shadow; PDFJS.createBlob = sharedUtil.createBlob; PDFJS.createObjectURL = function PDFJS_createObjectURL(data, contentType) { return sharedUtil.createObjectURL(data, contentType, PDFJS.disableCreateObjectURL); }; Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { var value = sharedUtil.isLittleEndian(); return sharedUtil.shadow(PDFJS, 'isLittleEndian', value); } }); PDFJS.removeNullCharacters = sharedUtil.removeNullCharacters; PDFJS.PasswordResponses = sharedUtil.PasswordResponses; PDFJS.PasswordException = sharedUtil.PasswordException; PDFJS.UnknownErrorException = sharedUtil.UnknownErrorException; PDFJS.InvalidPDFException = sharedUtil.InvalidPDFException; PDFJS.MissingPDFException = sharedUtil.MissingPDFException; PDFJS.UnexpectedResponseException = sharedUtil.UnexpectedResponseException; PDFJS.Util = sharedUtil.Util; PDFJS.PageViewport = sharedUtil.PageViewport; PDFJS.createPromiseCapability = sharedUtil.createPromiseCapability; /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /** * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font * renderer that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will * happen automatically if the browser doesn't support workers or sending * typed arrays to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled * in development mode. If unspecified in the production build, the worker * will be loaded based on the location of the pdf.js file. It is recommended * that the workerSrc is set in a custom application to prevent issues caused * by third-party frameworks and libraries. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable streaming of PDF file data. By default PDF.js attempts to load PDF * in chunks. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableStream = (PDFJS.disableStream === undefined ? false : PDFJS.disableStream); /** * Disable pre-fetching of PDF file data. When range requests are enabled * PDF.js will automatically keep fetching more data even if it isn't needed * to display the current page. This default behavior can be disabled. * * NOTE: It is also necessary to disable streaming, see above, * in order for disabling of pre-fetching to work correctly. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Specifies the |target| attribute for external links. * The constants from PDFJS.LinkTarget should be used: * - NONE [default] * - SELF * - BLANK * - PARENT * - TOP * @var {number} */ PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ? LinkTarget.NONE : PDFJS.externalLinkTarget); /** * Specifies the |rel| attribute for external links. Defaults to stripping * the referrer. * @var {string} */ PDFJS.externalLinkRel = (PDFJS.externalLinkRel === undefined ? 'noreferrer' : PDFJS.externalLinkRel); /** * Determines if we can eval strings as JS. Primarily used to improve * performance for font rendering. * @var {boolean} */ PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported); var savedOpenExternalLinksInNewWindow = PDFJS.openExternalLinksInNewWindow; delete PDFJS.openExternalLinksInNewWindow; Object.defineProperty(PDFJS, 'openExternalLinksInNewWindow', { get: function () { return PDFJS.externalLinkTarget === LinkTarget.BLANK; }, set: function (value) { if (value) { deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'); } if (PDFJS.externalLinkTarget !== LinkTarget.NONE) { warn('PDFJS.externalLinkTarget is already initialized'); return; } PDFJS.externalLinkTarget = value ? LinkTarget.BLANK : LinkTarget.NONE; }, enumerable: true, configurable: true }); if (savedOpenExternalLinksInNewWindow) { /** * (Deprecated) Opens external links in a new window if enabled. * The default behavior opens external links in the PDF.js window. * * NOTE: This property has been deprecated, please use * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead. * @var {boolean} */ PDFJS.openExternalLinksInNewWindow = savedOpenExternalLinksInNewWindow; } PDFJS.getDocument = displayAPI.getDocument; PDFJS.PDFDataRangeTransport = displayAPI.PDFDataRangeTransport; PDFJS.PDFWorker = displayAPI.PDFWorker; Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { var value = displayDOMUtils.hasCanvasTypedArrays(); return sharedUtil.shadow(PDFJS, 'hasCanvasTypedArrays', value); } }); PDFJS.CustomStyle = displayDOMUtils.CustomStyle; PDFJS.LinkTarget = LinkTarget; PDFJS.addLinkAttributes = displayDOMUtils.addLinkAttributes; PDFJS.getFilenameFromUrl = displayDOMUtils.getFilenameFromUrl; PDFJS.isExternalLinkTargetSet = displayDOMUtils.isExternalLinkTargetSet; PDFJS.AnnotationLayer = displayAnnotationLayer.AnnotationLayer; PDFJS.renderTextLayer = displayTextLayer.renderTextLayer; PDFJS.Metadata = displayMetadata.Metadata; PDFJS.SVGGraphics = displaySVG.SVGGraphics; PDFJS.UnsupportedManager = displayAPI._UnsupportedManager; exports.globalScope = globalScope; exports.isWorker = isWorker; exports.PDFJS = globalScope.PDFJS; })); }).call(pdfjsLibs); exports.PDFJS = pdfjsLibs.pdfjsDisplayGlobal.PDFJS; exports.build = pdfjsLibs.pdfjsDisplayAPI.build; exports.version = pdfjsLibs.pdfjsDisplayAPI.version; exports.getDocument = pdfjsLibs.pdfjsDisplayAPI.getDocument; exports.PDFDataRangeTransport = pdfjsLibs.pdfjsDisplayAPI.PDFDataRangeTransport; exports.PDFWorker = pdfjsLibs.pdfjsDisplayAPI.PDFWorker; exports.renderTextLayer = pdfjsLibs.pdfjsDisplayTextLayer.renderTextLayer; exports.AnnotationLayer = pdfjsLibs.pdfjsDisplayAnnotationLayer.AnnotationLayer; exports.CustomStyle = pdfjsLibs.pdfjsDisplayDOMUtils.CustomStyle; exports.PasswordResponses = pdfjsLibs.pdfjsSharedUtil.PasswordResponses; exports.InvalidPDFException = pdfjsLibs.pdfjsSharedUtil.InvalidPDFException; exports.MissingPDFException = pdfjsLibs.pdfjsSharedUtil.MissingPDFException; exports.SVGGraphics = pdfjsLibs.pdfjsDisplaySVG.SVGGraphics; exports.UnexpectedResponseException = pdfjsLibs.pdfjsSharedUtil.UnexpectedResponseException; exports.OPS = pdfjsLibs.pdfjsSharedUtil.OPS; exports.UNSUPPORTED_FEATURES = pdfjsLibs.pdfjsSharedUtil.UNSUPPORTED_FEATURES; exports.isValidUrl = pdfjsLibs.pdfjsSharedUtil.isValidUrl; exports.createObjectURL = pdfjsLibs.pdfjsSharedUtil.createObjectURL; exports.removeNullCharacters = pdfjsLibs.pdfjsSharedUtil.removeNullCharacters; exports.shadow = pdfjsLibs.pdfjsSharedUtil.shadow; exports.createBlob = pdfjsLibs.pdfjsSharedUtil.createBlob; exports.getFilenameFromUrl = pdfjsLibs.pdfjsDisplayDOMUtils.getFilenameFromUrl; exports.addLinkAttributes = pdfjsLibs.pdfjsDisplayDOMUtils.addLinkAttributes; }));
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/worker-lua.js
3,632
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; if (!window.console) { window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; } window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); } } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, ['', '']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!(range instanceof Range)) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject(array[i]); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } if (Object.prototype.toString.call(obj) !== "[object Object]") return obj; copy = {}; for (var key in obj) copy[key] = deepCopy(obj[key]); return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/lua/luaparse",["require","exports","module"], function(require, exports, module) { (function (root, name, factory) { factory(exports) }(this, 'luaparse', function (exports) { 'use strict'; exports.version = '0.1.4'; var input, options, length; var defaultOptions = exports.defaultOptions = { wait: false , comments: true , scope: false , locations: false , ranges: false }; var EOF = 1, StringLiteral = 2, Keyword = 4, Identifier = 8 , NumericLiteral = 16, Punctuator = 32, BooleanLiteral = 64 , NilLiteral = 128, VarargLiteral = 256; exports.tokenTypes = { EOF: EOF, StringLiteral: StringLiteral , Keyword: Keyword, Identifier: Identifier, NumericLiteral: NumericLiteral , Punctuator: Punctuator, BooleanLiteral: BooleanLiteral , NilLiteral: NilLiteral, VarargLiteral: VarargLiteral }; var errors = exports.errors = { unexpected: 'Unexpected %1 \'%2\' near \'%3\'' , expected: '\'%1\' expected near \'%2\'' , expectedToken: '%1 expected near \'%2\'' , unfinishedString: 'unfinished string near \'%1\'' , malformedNumber: 'malformed number near \'%1\'' }; var ast = exports.ast = { labelStatement: function(label) { return { type: 'LabelStatement' , label: label }; } , breakStatement: function() { return { type: 'BreakStatement' }; } , gotoStatement: function(label) { return { type: 'GotoStatement' , label: label }; } , returnStatement: function(args) { return { type: 'ReturnStatement' , 'arguments': args }; } , ifStatement: function(clauses) { return { type: 'IfStatement' , clauses: clauses }; } , ifClause: function(condition, body) { return { type: 'IfClause' , condition: condition , body: body }; } , elseifClause: function(condition, body) { return { type: 'ElseifClause' , condition: condition , body: body }; } , elseClause: function(body) { return { type: 'ElseClause' , body: body }; } , whileStatement: function(condition, body) { return { type: 'WhileStatement' , condition: condition , body: body }; } , doStatement: function(body) { return { type: 'DoStatement' , body: body }; } , repeatStatement: function(condition, body) { return { type: 'RepeatStatement' , condition: condition , body: body }; } , localStatement: function(variables, init) { return { type: 'LocalStatement' , variables: variables , init: init }; } , assignmentStatement: function(variables, init) { return { type: 'AssignmentStatement' , variables: variables , init: init }; } , callStatement: function(expression) { return { type: 'CallStatement' , expression: expression }; } , functionStatement: function(identifier, parameters, isLocal, body) { return { type: 'FunctionDeclaration' , identifier: identifier , isLocal: isLocal , parameters: parameters , body: body }; } , forNumericStatement: function(variable, start, end, step, body) { return { type: 'ForNumericStatement' , variable: variable , start: start , end: end , step: step , body: body }; } , forGenericStatement: function(variables, iterators, body) { return { type: 'ForGenericStatement' , variables: variables , iterators: iterators , body: body }; } , chunk: function(body) { return { type: 'Chunk' , body: body }; } , identifier: function(name) { return { type: 'Identifier' , name: name }; } , literal: function(type, value, raw) { type = (type === StringLiteral) ? 'StringLiteral' : (type === NumericLiteral) ? 'NumericLiteral' : (type === BooleanLiteral) ? 'BooleanLiteral' : (type === NilLiteral) ? 'NilLiteral' : 'VarargLiteral'; return { type: type , value: value , raw: raw }; } , tableKey: function(key, value) { return { type: 'TableKey' , key: key , value: value }; } , tableKeyString: function(key, value) { return { type: 'TableKeyString' , key: key , value: value }; } , tableValue: function(value) { return { type: 'TableValue' , value: value }; } , tableConstructorExpression: function(fields) { return { type: 'TableConstructorExpression' , fields: fields }; } , binaryExpression: function(operator, left, right) { var type = ('and' === operator || 'or' === operator) ? 'LogicalExpression' : 'BinaryExpression'; return { type: type , operator: operator , left: left , right: right }; } , unaryExpression: function(operator, argument) { return { type: 'UnaryExpression' , operator: operator , argument: argument }; } , memberExpression: function(base, indexer, identifier) { return { type: 'MemberExpression' , indexer: indexer , identifier: identifier , base: base }; } , indexExpression: function(base, index) { return { type: 'IndexExpression' , base: base , index: index }; } , callExpression: function(base, args) { return { type: 'CallExpression' , base: base , 'arguments': args }; } , tableCallExpression: function(base, args) { return { type: 'TableCallExpression' , base: base , 'arguments': args }; } , stringCallExpression: function(base, argument) { return { type: 'StringCallExpression' , base: base , argument: argument }; } , comment: function(value, raw) { return { type: 'Comment' , value: value , raw: raw }; } }; function finishNode(node) { if (trackLocations) { var location = locations.pop(); location.complete(); if (options.locations) node.loc = location.loc; if (options.ranges) node.range = location.range; } return node; } var slice = Array.prototype.slice , toString = Object.prototype.toString , indexOf = function indexOf(array, element) { for (var i = 0, length = array.length; i < length; i++) { if (array[i] === element) return i; } return -1; }; function indexOfObject(array, property, element) { for (var i = 0, length = array.length; i < length; i++) { if (array[i][property] === element) return i; } return -1; } function sprintf(format) { var args = slice.call(arguments, 1); format = format.replace(/%(\d)/g, function (match, index) { return '' + args[index - 1] || ''; }); return format; } function extend() { var args = slice.call(arguments) , dest = {} , src, prop; for (var i = 0, length = args.length; i < length; i++) { src = args[i]; for (prop in src) if (src.hasOwnProperty(prop)) { dest[prop] = src[prop]; } } return dest; } function raise(token) { var message = sprintf.apply(null, slice.call(arguments, 1)) , error, col; if ('undefined' !== typeof token.line) { col = token.range[0] - token.lineStart; error = new SyntaxError(sprintf('[%1:%2] %3', token.line, col, message)); error.line = token.line; error.index = token.range[0]; error.column = col; } else { col = index - lineStart + 1; error = new SyntaxError(sprintf('[%1:%2] %3', line, col, message)); error.index = index; error.line = line; error.column = col; } throw error; } function raiseUnexpectedToken(type, token) { raise(token, errors.expectedToken, type, token.value); } function unexpected(found, near) { if ('undefined' === typeof near) near = lookahead.value; if ('undefined' !== typeof found.type) { var type; switch (found.type) { case StringLiteral: type = 'string'; break; case Keyword: type = 'keyword'; break; case Identifier: type = 'identifier'; break; case NumericLiteral: type = 'number'; break; case Punctuator: type = 'symbol'; break; case BooleanLiteral: type = 'boolean'; break; case NilLiteral: return raise(found, errors.unexpected, 'symbol', 'nil', near); } return raise(found, errors.unexpected, type, found.value, near); } return raise(found, errors.unexpected, 'symbol', found, near); } var index , token , previousToken , lookahead , comments , tokenStart , line , lineStart; exports.lex = lex; function lex() { skipWhiteSpace(); while (45 === input.charCodeAt(index) && 45 === input.charCodeAt(index + 1)) { scanComment(); skipWhiteSpace(); } if (index >= length) return { type : EOF , value: '<eof>' , line: line , lineStart: lineStart , range: [index, index] }; var charCode = input.charCodeAt(index) , next = input.charCodeAt(index + 1); tokenStart = index; if (isIdentifierStart(charCode)) return scanIdentifierOrKeyword(); switch (charCode) { case 39: case 34: // '" return scanStringLiteral(); case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return scanNumericLiteral(); case 46: // . if (isDecDigit(next)) return scanNumericLiteral(); if (46 === next) { if (46 === input.charCodeAt(index + 2)) return scanVarargLiteral(); return scanPunctuator('..'); } return scanPunctuator('.'); case 61: // = if (61 === next) return scanPunctuator('=='); return scanPunctuator('='); case 62: // > if (61 === next) return scanPunctuator('>='); return scanPunctuator('>'); case 60: // < if (61 === next) return scanPunctuator('<='); return scanPunctuator('<'); case 126: // ~ if (61 === next) return scanPunctuator('~='); return raise({}, errors.expected, '=', '~'); case 58: // : if (58 === next) return scanPunctuator('::'); return scanPunctuator(':'); case 91: // [ if (91 === next || 61 === next) return scanLongStringLiteral(); return scanPunctuator('['); case 42: case 47: case 94: case 37: case 44: case 123: case 125: case 93: case 40: case 41: case 59: case 35: case 45: case 43: return scanPunctuator(input.charAt(index)); } return unexpected(input.charAt(index)); } function skipWhiteSpace() { while (index < length) { var charCode = input.charCodeAt(index); if (isWhiteSpace(charCode)) { index++; } else if (isLineTerminator(charCode)) { line++; lineStart = ++index; } else { break; } } } function scanIdentifierOrKeyword() { var value, type; while (isIdentifierPart(input.charCodeAt(++index))); value = input.slice(tokenStart, index); if (isKeyword(value)) { type = Keyword; } else if ('true' === value || 'false' === value) { type = BooleanLiteral; value = ('true' === value); } else if ('nil' === value) { type = NilLiteral; value = null; } else { type = Identifier; } return { type: type , value: value , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanPunctuator(value) { index += value.length; return { type: Punctuator , value: value , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanVarargLiteral() { index += 3; return { type: VarargLiteral , value: '...' , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanStringLiteral() { var delimiter = input.charCodeAt(index++) , stringStart = index , string = '' , charCode; while (index < length) { charCode = input.charCodeAt(index++); if (delimiter === charCode) break; if (92 === charCode) { // \ string += input.slice(stringStart, index - 1) + readEscapeSequence(); stringStart = index; } else if (index >= length || isLineTerminator(charCode)) { string += input.slice(stringStart, index - 1); raise({}, errors.unfinishedString, string + String.fromCharCode(charCode)); } } string += input.slice(stringStart, index - 1); return { type: StringLiteral , value: string , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanLongStringLiteral() { var string = readLongString(); if (false === string) raise(token, errors.expected, '[', token.value); return { type: StringLiteral , value: string , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanNumericLiteral() { var character = input.charAt(index) , next = input.charAt(index + 1); var value = ('0' === character && 'xX'.indexOf(next || null) >= 0) ? readHexLiteral() : readDecLiteral(); return { type: NumericLiteral , value: value , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function readHexLiteral() { var fraction = 0 // defaults to 0 as it gets summed , binaryExponent = 1 // defaults to 1 as it gets multiplied , binarySign = 1 // positive , digit, fractionStart, exponentStart, digitStart; digitStart = index += 2; // Skip 0x part if (!isHexDigit(input.charCodeAt(index))) raise({}, errors.malformedNumber, input.slice(tokenStart, index)); while (isHexDigit(input.charCodeAt(index))) index++; digit = parseInt(input.slice(digitStart, index), 16); if ('.' === input.charAt(index)) { fractionStart = ++index; while (isHexDigit(input.charCodeAt(index))) index++; fraction = input.slice(fractionStart, index); fraction = (fractionStart === index) ? 0 : parseInt(fraction, 16) / Math.pow(16, index - fractionStart); } if ('pP'.indexOf(input.charAt(index) || null) >= 0) { index++; if ('+-'.indexOf(input.charAt(index) || null) >= 0) binarySign = ('+' === input.charAt(index++)) ? 1 : -1; exponentStart = index; if (!isDecDigit(input.charCodeAt(index))) raise({}, errors.malformedNumber, input.slice(tokenStart, index)); while (isDecDigit(input.charCodeAt(index))) index++; binaryExponent = input.slice(exponentStart, index); binaryExponent = Math.pow(2, binaryExponent * binarySign); } return (digit + fraction) * binaryExponent; } function readDecLiteral() { while (isDecDigit(input.charCodeAt(index))) index++; if ('.' === input.charAt(index)) { index++; while (isDecDigit(input.charCodeAt(index))) index++; } if ('eE'.indexOf(input.charAt(index) || null) >= 0) { index++; if ('+-'.indexOf(input.charAt(index) || null) >= 0) index++; if (!isDecDigit(input.charCodeAt(index))) raise({}, errors.malformedNumber, input.slice(tokenStart, index)); while (isDecDigit(input.charCodeAt(index))) index++; } return parseFloat(input.slice(tokenStart, index)); } function readEscapeSequence() { var sequenceStart = index; switch (input.charAt(index)) { case 'n': index++; return '\n'; case 'r': index++; return '\r'; case 't': index++; return '\t'; case 'v': index++; return '\x0B'; case 'b': index++; return '\b'; case 'f': index++; return '\f'; case 'z': index++; skipWhiteSpace(); return ''; case 'x': if (isHexDigit(input.charCodeAt(index + 1)) && isHexDigit(input.charCodeAt(index + 2))) { index += 3; return '\\' + input.slice(sequenceStart, index); } return '\\' + input.charAt(index++); default: if (isDecDigit(input.charCodeAt(index))) { while (isDecDigit(input.charCodeAt(++index))); return '\\' + input.slice(sequenceStart, index); } return input.charAt(index++); } } function scanComment() { tokenStart = index; index += 2; // -- var character = input.charAt(index) , content = '' , isLong = false , commentStart = index , lineStartComment = lineStart , lineComment = line; if ('[' === character) { content = readLongString(); if (false === content) content = character; else isLong = true; } if (!isLong) { while (index < length) { if (isLineTerminator(input.charCodeAt(index))) break; index++; } if (options.comments) content = input.slice(commentStart, index); } if (options.comments) { var node = ast.comment(content, input.slice(tokenStart, index)); if (options.locations) { node.loc = { start: { line: lineComment, column: tokenStart - lineStartComment } , end: { line: line, column: index - lineStart } }; } if (options.ranges) { node.range = [tokenStart, index]; } comments.push(node); } } function readLongString() { var level = 0 , content = '' , terminator = false , character, stringStart; index++; // [ while ('=' === input.charAt(index + level)) level++; if ('[' !== input.charAt(index + level)) return false; index += level + 1; if (isLineTerminator(input.charCodeAt(index))) { line++; lineStart = index++; } stringStart = index; while (index < length) { character = input.charAt(index++); if (isLineTerminator(character.charCodeAt(0))) { line++; lineStart = index; } if (']' === character) { terminator = true; for (var i = 0; i < level; i++) { if ('=' !== input.charAt(index + i)) terminator = false; } if (']' !== input.charAt(index + level)) terminator = false; } if (terminator) break; } content += input.slice(stringStart, index - 1); index += level + 1; return content; } function next() { previousToken = token; token = lookahead; lookahead = lex(); } function consume(value) { if (value === token.value) { next(); return true; } return false; } function expect(value) { if (value === token.value) next(); else raise(token, errors.expected, value, token.value); } function isWhiteSpace(charCode) { return 9 === charCode || 32 === charCode || 0xB === charCode || 0xC === charCode; } function isLineTerminator(charCode) { return 10 === charCode || 13 === charCode; } function isDecDigit(charCode) { return charCode >= 48 && charCode <= 57; } function isHexDigit(charCode) { return (charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 102) || (charCode >= 65 && charCode <= 70); } function isIdentifierStart(charCode) { return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode; } function isIdentifierPart(charCode) { return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode || (charCode >= 48 && charCode <= 57); } function isKeyword(id) { switch (id.length) { case 2: return 'do' === id || 'if' === id || 'in' === id || 'or' === id; case 3: return 'and' === id || 'end' === id || 'for' === id || 'not' === id; case 4: return 'else' === id || 'goto' === id || 'then' === id; case 5: return 'break' === id || 'local' === id || 'until' === id || 'while' === id; case 6: return 'elseif' === id || 'repeat' === id || 'return' === id; case 8: return 'function' === id; } return false; } function isUnary(token) { if (Punctuator === token.type) return '#-'.indexOf(token.value) >= 0; if (Keyword === token.type) return 'not' === token.value; return false; } function isCallExpression(expression) { switch (expression.type) { case 'CallExpression': case 'TableCallExpression': case 'StringCallExpression': return true; } return false; } function isBlockFollow(token) { if (EOF === token.type) return true; if (Keyword !== token.type) return false; switch (token.value) { case 'else': case 'elseif': case 'end': case 'until': return true; default: return false; } } var scopes , scopeDepth , globals; function createScope() { scopes.push(Array.apply(null, scopes[scopeDepth++])); } function exitScope() { scopes.pop(); scopeDepth--; } function scopeIdentifierName(name) { if (-1 !== indexOf(scopes[scopeDepth], name)) return; scopes[scopeDepth].push(name); } function scopeIdentifier(node) { scopeIdentifierName(node.name); attachScope(node, true); } function attachScope(node, isLocal) { if (!isLocal && -1 === indexOfObject(globals, 'name', node.name)) globals.push(node); node.isLocal = isLocal; } function scopeHasName(name) { return (-1 !== indexOf(scopes[scopeDepth], name)); } var locations = [] , trackLocations; function createLocationMarker() { return new Marker(token); } function Marker(token) { if (options.locations) { this.loc = { start: { line: token.line , column: token.range[0] - token.lineStart } , end: { line: 0 , column: 0 } }; } if (options.ranges) this.range = [token.range[0], 0]; } Marker.prototype.complete = function() { if (options.locations) { this.loc.end.line = previousToken.line; this.loc.end.column = previousToken.range[1] - previousToken.lineStart; } if (options.ranges) { this.range[1] = previousToken.range[1]; } }; function markLocation() { if (trackLocations) locations.push(createLocationMarker()); } function pushLocation(marker) { if (trackLocations) locations.push(marker); } function parseChunk() { next(); markLocation(); var body = parseBlock(); if (EOF !== token.type) unexpected(token); if (trackLocations && !body.length) previousToken = token; return finishNode(ast.chunk(body)); } function parseBlock(terminator) { var block = [] , statement; if (options.scope) createScope(); while (!isBlockFollow(token)) { if ('return' === token.value) { block.push(parseStatement()); break; } statement = parseStatement(); if (statement) block.push(statement); } if (options.scope) exitScope(); return block; } function parseStatement() { markLocation(); if (Keyword === token.type) { switch (token.value) { case 'local': next(); return parseLocalStatement(); case 'if': next(); return parseIfStatement(); case 'return': next(); return parseReturnStatement(); case 'function': next(); var name = parseFunctionName(); return parseFunctionDeclaration(name); case 'while': next(); return parseWhileStatement(); case 'for': next(); return parseForStatement(); case 'repeat': next(); return parseRepeatStatement(); case 'break': next(); return parseBreakStatement(); case 'do': next(); return parseDoStatement(); case 'goto': next(); return parseGotoStatement(); } } if (Punctuator === token.type) { if (consume('::')) return parseLabelStatement(); } if (trackLocations) locations.pop(); if (consume(';')) return; return parseAssignmentOrCallStatement(); } function parseLabelStatement() { var name = token.value , label = parseIdentifier(); if (options.scope) { scopeIdentifierName('::' + name + '::'); attachScope(label, true); } expect('::'); return finishNode(ast.labelStatement(label)); } function parseBreakStatement() { return finishNode(ast.breakStatement()); } function parseGotoStatement() { var name = token.value , label = parseIdentifier(); if (options.scope) label.isLabel = scopeHasName('::' + name + '::'); return finishNode(ast.gotoStatement(label)); } function parseDoStatement() { var body = parseBlock(); expect('end'); return finishNode(ast.doStatement(body)); } function parseWhileStatement() { var condition = parseExpectedExpression(); expect('do'); var body = parseBlock(); expect('end'); return finishNode(ast.whileStatement(condition, body)); } function parseRepeatStatement() { var body = parseBlock(); expect('until'); var condition = parseExpectedExpression(); return finishNode(ast.repeatStatement(condition, body)); } function parseReturnStatement() { var expressions = []; if ('end' !== token.value) { var expression = parseExpression(); if (null != expression) expressions.push(expression); while (consume(',')) { expression = parseExpectedExpression(); expressions.push(expression); } consume(';'); // grammar tells us ; is optional here. } return finishNode(ast.returnStatement(expressions)); } function parseIfStatement() { var clauses = [] , condition , body , marker; if (trackLocations) { marker = locations[locations.length - 1]; locations.push(marker); } condition = parseExpectedExpression(); expect('then'); body = parseBlock(); clauses.push(finishNode(ast.ifClause(condition, body))); if (trackLocations) marker = createLocationMarker(); while (consume('elseif')) { pushLocation(marker); condition = parseExpectedExpression(); expect('then'); body = parseBlock(); clauses.push(finishNode(ast.elseifClause(condition, body))); if (trackLocations) marker = createLocationMarker(); } if (consume('else')) { if (trackLocations) { marker = new Marker(previousToken); locations.push(marker); } body = parseBlock(); clauses.push(finishNode(ast.elseClause(body))); } expect('end'); return finishNode(ast.ifStatement(clauses)); } function parseForStatement() { var variable = parseIdentifier() , body; if (options.scope) scopeIdentifier(variable); if (consume('=')) { var start = parseExpectedExpression(); expect(','); var end = parseExpectedExpression(); var step = consume(',') ? parseExpectedExpression() : null; expect('do'); body = parseBlock(); expect('end'); return finishNode(ast.forNumericStatement(variable, start, end, step, body)); } else { var variables = [variable]; while (consume(',')) { variable = parseIdentifier(); if (options.scope) scopeIdentifier(variable); variables.push(variable); } expect('in'); var iterators = []; do { var expression = parseExpectedExpression(); iterators.push(expression); } while (consume(',')); expect('do'); body = parseBlock(); expect('end'); return finishNode(ast.forGenericStatement(variables, iterators, body)); } } function parseLocalStatement() { var name; if (Identifier === token.type) { var variables = [] , init = []; do { name = parseIdentifier(); variables.push(name); } while (consume(',')); if (consume('=')) { do { var expression = parseExpectedExpression(); init.push(expression); } while (consume(',')); } if (options.scope) { for (var i = 0, l = variables.length; i < l; i++) { scopeIdentifier(variables[i]); } } return finishNode(ast.localStatement(variables, init)); } if (consume('function')) { name = parseIdentifier(); if (options.scope) scopeIdentifier(name); return parseFunctionDeclaration(name, true); } else { raiseUnexpectedToken('<name>', token); } } function parseAssignmentOrCallStatement() { var previous = token , expression, marker; if (trackLocations) marker = createLocationMarker(); expression = parsePrefixExpression(); if (null == expression) return unexpected(token); if (',='.indexOf(token.value) >= 0) { var variables = [expression] , init = [] , exp; while (consume(',')) { exp = parsePrefixExpression(); if (null == exp) raiseUnexpectedToken('<expression>', token); variables.push(exp); } expect('='); do { exp = parseExpectedExpression(); init.push(exp); } while (consume(',')); pushLocation(marker); return finishNode(ast.assignmentStatement(variables, init)); } if (isCallExpression(expression)) { pushLocation(marker); return finishNode(ast.callStatement(expression)); } return unexpected(previous); } function parseIdentifier() { markLocation(); var identifier = token.value; if (Identifier !== token.type) raiseUnexpectedToken('<name>', token); next(); return finishNode(ast.identifier(identifier)); } function parseFunctionDeclaration(name, isLocal) { var parameters = []; expect('('); if (!consume(')')) { while (true) { if (Identifier === token.type) { var parameter = parseIdentifier(); if (options.scope) scopeIdentifier(parameter); parameters.push(parameter); if (consume(',')) continue; else if (consume(')')) break; } else if (VarargLiteral === token.type) { parameters.push(parsePrimaryExpression()); expect(')'); break; } else { raiseUnexpectedToken('<name> or \'...\'', token); } } } var body = parseBlock(); expect('end'); isLocal = isLocal || false; return finishNode(ast.functionStatement(name, parameters, isLocal, body)); } function parseFunctionName() { var base, name, marker; if (trackLocations) marker = createLocationMarker(); base = parseIdentifier(); if (options.scope) attachScope(base, false); while (consume('.')) { pushLocation(marker); name = parseIdentifier(); if (options.scope) attachScope(name, false); base = finishNode(ast.memberExpression(base, '.', name)); } if (consume(':')) { pushLocation(marker); name = parseIdentifier(); if (options.scope) attachScope(name, false); base = finishNode(ast.memberExpression(base, ':', name)); } return base; } function parseTableConstructor() { var fields = [] , key, value; while (true) { markLocation(); if (Punctuator === token.type && consume('[')) { key = parseExpectedExpression(); expect(']'); expect('='); value = parseExpectedExpression(); fields.push(finishNode(ast.tableKey(key, value))); } else if (Identifier === token.type) { key = parseExpectedExpression(); if (consume('=')) { value = parseExpectedExpression(); fields.push(finishNode(ast.tableKeyString(key, value))); } else { fields.push(finishNode(ast.tableValue(key))); } } else { if (null == (value = parseExpression())) { locations.pop(); break; } fields.push(finishNode(ast.tableValue(value))); } if (',;'.indexOf(token.value) >= 0) { next(); continue; } if ('}' === token.value) break; } expect('}'); return finishNode(ast.tableConstructorExpression(fields)); } function parseExpression() { var expression = parseSubExpression(0); return expression; } function parseExpectedExpression() { var expression = parseExpression(); if (null == expression) raiseUnexpectedToken('<expression>', token); else return expression; } function binaryPrecedence(operator) { var charCode = operator.charCodeAt(0) , length = operator.length; if (1 === length) { switch (charCode) { case 94: return 10; // ^ case 42: case 47: case 37: return 7; // * / % case 43: case 45: return 6; // + - case 60: case 62: return 3; // < > } } else if (2 === length) { switch (charCode) { case 46: return 5; // .. case 60: case 62: case 61: case 126: return 3; // <= >= == ~= case 111: return 1; // or } } else if (97 === charCode && 'and' === operator) return 2; return 0; } function parseSubExpression(minPrecedence) { var operator = token.value , expression, marker; if (trackLocations) marker = createLocationMarker(); if (isUnary(token)) { markLocation(); next(); var argument = parseSubExpression(8); if (argument == null) raiseUnexpectedToken('<expression>', token); expression = finishNode(ast.unaryExpression(operator, argument)); } if (null == expression) { expression = parsePrimaryExpression(); if (null == expression) { expression = parsePrefixExpression(); } } if (null == expression) return null; var precedence; while (true) { operator = token.value; precedence = (Punctuator === token.type || Keyword === token.type) ? binaryPrecedence(operator) : 0; if (precedence === 0 || precedence <= minPrecedence) break; if ('^' === operator || '..' === operator) precedence--; next(); var right = parseSubExpression(precedence); if (null == right) raiseUnexpectedToken('<expression>', token); if (trackLocations) locations.push(marker); expression = finishNode(ast.binaryExpression(operator, expression, right)); } return expression; } function parsePrefixExpression() { var base, name, marker , isLocal; if (trackLocations) marker = createLocationMarker(); if (Identifier === token.type) { name = token.value; base = parseIdentifier(); if (options.scope) attachScope(base, isLocal = scopeHasName(name)); } else if (consume('(')) { base = parseExpectedExpression(); expect(')'); if (options.scope) isLocal = base.isLocal; } else { return null; } var expression, identifier; while (true) { if (Punctuator === token.type) { switch (token.value) { case '[': pushLocation(marker); next(); expression = parseExpectedExpression(); base = finishNode(ast.indexExpression(base, expression)); expect(']'); break; case '.': pushLocation(marker); next(); identifier = parseIdentifier(); if (options.scope) attachScope(identifier, isLocal); base = finishNode(ast.memberExpression(base, '.', identifier)); break; case ':': pushLocation(marker); next(); identifier = parseIdentifier(); if (options.scope) attachScope(identifier, isLocal); base = finishNode(ast.memberExpression(base, ':', identifier)); pushLocation(marker); base = parseCallExpression(base); break; case '(': case '{': // args pushLocation(marker); base = parseCallExpression(base); break; default: return base; } } else if (StringLiteral === token.type) { pushLocation(marker); base = parseCallExpression(base); } else { break; } } return base; } function parseCallExpression(base) { if (Punctuator === token.type) { switch (token.value) { case '(': next(); var expressions = []; var expression = parseExpression(); if (null != expression) expressions.push(expression); while (consume(',')) { expression = parseExpectedExpression(); expressions.push(expression); } expect(')'); return finishNode(ast.callExpression(base, expressions)); case '{': markLocation(); next(); var table = parseTableConstructor(); return finishNode(ast.tableCallExpression(base, table)); } } else if (StringLiteral === token.type) { return finishNode(ast.stringCallExpression(base, parsePrimaryExpression())); } raiseUnexpectedToken('function arguments', token); } function parsePrimaryExpression() { var literals = StringLiteral | NumericLiteral | BooleanLiteral | NilLiteral | VarargLiteral , value = token.value , type = token.type , marker; if (trackLocations) marker = createLocationMarker(); if (type & literals) { pushLocation(marker); var raw = input.slice(token.range[0], token.range[1]); next(); return finishNode(ast.literal(type, value, raw)); } else if (Keyword === type && 'function' === value) { pushLocation(marker); next(); return parseFunctionDeclaration(null); } else if (consume('{')) { pushLocation(marker); return parseTableConstructor(); } } exports.parse = parse; function parse(_input, _options) { if ('undefined' === typeof _options && 'object' === typeof _input) { _options = _input; _input = undefined; } if (!_options) _options = {}; input = _input || ''; options = extend(defaultOptions, _options); index = 0; line = 1; lineStart = 0; length = input.length; scopes = [[]]; scopeDepth = 0; globals = []; locations = []; if (options.comments) comments = []; if (!options.wait) return end(); return exports; } exports.write = write; function write(_input) { input += String(_input); length = input.length; return exports; } exports.end = end; function end(_input) { if ('undefined' !== typeof _input) write(_input); length = input.length; trackLocations = options.locations || options.ranges; lookahead = lex(); var chunk = parseChunk(); if (options.comments) chunk.comments = comments; if (options.scope) chunk.globals = globals; if (locations.length > 0) throw new Error('Location tracking failed. This is most likely a bug in luaparse'); return chunk; } })); }); ace.define("ace/mode/lua_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/lua/luaparse"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var luaparse = require("../mode/lua/luaparse"); var Worker = exports.Worker = function(sender) { Mirror.call(this, sender); this.setTimeout(500); }; oop.inherits(Worker, Mirror); (function() { this.onUpdate = function() { var value = this.doc.getValue(); var errors = []; try { luaparse.parse(value); } catch(e) { if (e instanceof SyntaxError) { errors.push({ row: e.line - 1, column: e.column, text: e.message, type: "error" }); } } this.sender.emit("annotate", errors); }; }).call(Worker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace-1.2.5/mode-html_ruby.js
2,958
ace.define("ace/mode/css_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var supportType = exports.supportType = "align-content|align-items|align-self|all|animation|animation-delay|animation-direction|animation-duration|animation-fill-mode|animation-iteration-count|animation-name|animation-play-state|animation-timing-function|backface-visibility|background|background-attachment|background-blend-mode|background-clip|background-color|background-image|background-origin|background-position|background-repeat|background-size|border|border-bottom|border-bottom-color|border-bottom-left-radius|border-bottom-right-radius|border-bottom-style|border-bottom-width|border-collapse|border-color|border-image|border-image-outset|border-image-repeat|border-image-slice|border-image-source|border-image-width|border-left|border-left-color|border-left-style|border-left-width|border-radius|border-right|border-right-color|border-right-style|border-right-width|border-spacing|border-style|border-top|border-top-color|border-top-left-radius|border-top-right-radius|border-top-style|border-top-width|border-width|bottom|box-shadow|box-sizing|caption-side|clear|clip|color|column-count|column-fill|column-gap|column-rule|column-rule-color|column-rule-style|column-rule-width|column-span|column-width|columns|content|counter-increment|counter-reset|cursor|direction|display|empty-cells|filter|flex|flex-basis|flex-direction|flex-flow|flex-grow|flex-shrink|flex-wrap|float|font|font-family|font-size|font-size-adjust|font-stretch|font-style|font-variant|font-weight|hanging-punctuation|height|justify-content|left|letter-spacing|line-height|list-style|list-style-image|list-style-position|list-style-type|margin|margin-bottom|margin-left|margin-right|margin-top|max-height|max-width|min-height|min-width|nav-down|nav-index|nav-left|nav-right|nav-up|opacity|order|outline|outline-color|outline-offset|outline-style|outline-width|overflow|overflow-x|overflow-y|padding|padding-bottom|padding-left|padding-right|padding-top|page-break-after|page-break-before|page-break-inside|perspective|perspective-origin|position|quotes|resize|right|tab-size|table-layout|text-align|text-align-last|text-decoration|text-decoration-color|text-decoration-line|text-decoration-style|text-indent|text-justify|text-overflow|text-shadow|text-transform|top|transform|transform-origin|transform-style|transition|transition-delay|transition-duration|transition-property|transition-timing-function|unicode-bidi|vertical-align|visibility|white-space|width|word-break|word-spacing|word-wrap|z-index"; var supportFunction = exports.supportFunction = "rgb|rgba|url|attr|counter|counters"; var supportConstant = exports.supportConstant = "absolute|after-edge|after|all-scroll|all|alphabetic|always|antialiased|armenian|auto|avoid-column|avoid-page|avoid|balance|baseline|before-edge|before|below|bidi-override|block-line-height|block|bold|bolder|border-box|both|bottom|box|break-all|break-word|capitalize|caps-height|caption|center|central|char|circle|cjk-ideographic|clone|close-quote|col-resize|collapse|column|consider-shifts|contain|content-box|cover|crosshair|cubic-bezier|dashed|decimal-leading-zero|decimal|default|disabled|disc|disregard-shifts|distribute-all-lines|distribute-letter|distribute-space|distribute|dotted|double|e-resize|ease-in|ease-in-out|ease-out|ease|ellipsis|end|exclude-ruby|fill|fixed|georgian|glyphs|grid-height|groove|hand|hanging|hebrew|help|hidden|hiragana-iroha|hiragana|horizontal|icon|ideograph-alpha|ideograph-numeric|ideograph-parenthesis|ideograph-space|ideographic|inactive|include-ruby|inherit|initial|inline-block|inline-box|inline-line-height|inline-table|inline|inset|inside|inter-ideograph|inter-word|invert|italic|justify|katakana-iroha|katakana|keep-all|last|left|lighter|line-edge|line-through|line|linear|list-item|local|loose|lower-alpha|lower-greek|lower-latin|lower-roman|lowercase|lr-tb|ltr|mathematical|max-height|max-size|medium|menu|message-box|middle|move|n-resize|ne-resize|newspaper|no-change|no-close-quote|no-drop|no-open-quote|no-repeat|none|normal|not-allowed|nowrap|nw-resize|oblique|open-quote|outset|outside|overline|padding-box|page|pointer|pre-line|pre-wrap|pre|preserve-3d|progress|relative|repeat-x|repeat-y|repeat|replaced|reset-size|ridge|right|round|row-resize|rtl|s-resize|scroll|se-resize|separate|slice|small-caps|small-caption|solid|space|square|start|static|status-bar|step-end|step-start|steps|stretch|strict|sub|super|sw-resize|table-caption|table-cell|table-column-group|table-column|table-footer-group|table-header-group|table-row-group|table-row|table|tb-rl|text-after-edge|text-before-edge|text-bottom|text-size|text-top|text|thick|thin|transparent|underline|upper-alpha|upper-latin|upper-roman|uppercase|use-script|vertical-ideographic|vertical-text|visible|w-resize|wait|whitespace|z-index|zero"; var supportConstantColor = exports.supportConstantColor = "aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow"; var supportConstantFonts = exports.supportConstantFonts = "arial|century|comic|courier|cursive|fantasy|garamond|georgia|helvetica|impact|lucida|symbol|system|tahoma|times|trebuchet|utopia|verdana|webdings|sans-serif|serif|monospace"; var numRe = exports.numRe = "\\-?(?:(?:[0-9]+)|(?:[0-9]*\\.[0-9]+))"; var pseudoElements = exports.pseudoElements = "(\\:+)\\b(after|before|first-letter|first-line|moz-selection|selection)\\b"; var pseudoClasses = exports.pseudoClasses = "(:)\\b(active|checked|disabled|empty|enabled|first-child|first-of-type|focus|hover|indeterminate|invalid|last-child|last-of-type|link|not|nth-child|nth-last-child|nth-last-of-type|nth-of-type|only-child|only-of-type|required|root|target|valid|visited)\\b"; var CssHighlightRules = function() { var keywordMapper = this.createKeywordMapper({ "support.function": supportFunction, "support.constant": supportConstant, "support.type": supportType, "support.constant.color": supportConstantColor, "support.constant.fonts": supportConstantFonts }, "text", true); this.$rules = { "start" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "@.*?{", push: "media" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "media" : [{ token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token: "paren.lparen", regex: "\\{", push: "ruleset" }, { token: "string", regex: "\\}", next: "pop" }, { token: "keyword", regex: "#[a-z0-9-_]+" }, { token: "variable", regex: "\\.[a-z0-9-_]+" }, { token: "string", regex: ":[a-z0-9-_]+" }, { token: "constant", regex: "[a-z0-9-_]+" }, { caseInsensitive: true }], "comment" : [{ token : "comment", regex : "\\*\\/", next : "pop" }, { defaultToken : "comment" }], "ruleset" : [ { token : "paren.rparen", regex : "\\}", next: "pop" }, { token : "comment", // multi line comment regex : "\\/\\*", push : "comment" }, { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }, { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }, { token : ["constant.numeric", "keyword"], regex : "(" + numRe + ")(ch|cm|deg|em|ex|fr|gd|grad|Hz|in|kHz|mm|ms|pc|pt|px|rad|rem|s|turn|vh|vm|vw|%)" }, { token : "constant.numeric", regex : numRe }, { token : "constant.numeric", // hex6 color regex : "#[a-f0-9]{6}" }, { token : "constant.numeric", // hex3 color regex : "#[a-f0-9]{3}" }, { token : ["punctuation", "entity.other.attribute-name.pseudo-element.css"], regex : pseudoElements }, { token : ["punctuation", "entity.other.attribute-name.pseudo-class.css"], regex : pseudoClasses }, { token : ["support.function", "string", "support.function"], regex : "(url\\()(.*)(\\))" }, { token : keywordMapper, regex : "\\-?[a-zA-Z_][a-zA-Z0-9_\\-]*" }, { caseInsensitive: true }] }; this.normalizeRules(); }; oop.inherits(CssHighlightRules, TextHighlightRules); exports.CssHighlightRules = CssHighlightRules; }); ace.define("ace/mode/doc_comment_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var DocCommentHighlightRules = function() { this.$rules = { "start" : [ { token : "comment.doc.tag", regex : "@[\\w\\d_]+" // TODO: fix email addresses }, DocCommentHighlightRules.getTagRule(), { defaultToken : "comment.doc", caseInsensitive: true }] }; }; oop.inherits(DocCommentHighlightRules, TextHighlightRules); DocCommentHighlightRules.getTagRule = function(start) { return { token : "comment.doc.tag.storage.type", regex : "\\b(?:TODO|FIXME|XXX|HACK)\\b" }; } DocCommentHighlightRules.getStartRule = function(start) { return { token : "comment.doc", // doc comment regex : "\\/\\*(?=\\*)", next : start }; }; DocCommentHighlightRules.getEndRule = function (start) { return { token : "comment.doc", // closing comment regex : "\\*\\/", next : start }; }; exports.DocCommentHighlightRules = DocCommentHighlightRules; }); ace.define("ace/mode/javascript_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/doc_comment_highlight_rules","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var DocCommentHighlightRules = require("./doc_comment_highlight_rules").DocCommentHighlightRules; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var identifierRe = "[a-zA-Z\\$_\u00a1-\uffff][a-zA-Z\\d\\$_\u00a1-\uffff]*"; var JavaScriptHighlightRules = function(options) { var keywordMapper = this.createKeywordMapper({ "variable.language": "Array|Boolean|Date|Function|Iterator|Number|Object|RegExp|String|Proxy|" + // Constructors "Namespace|QName|XML|XMLList|" + // E4X "ArrayBuffer|Float32Array|Float64Array|Int16Array|Int32Array|Int8Array|" + "Uint16Array|Uint32Array|Uint8Array|Uint8ClampedArray|" + "Error|EvalError|InternalError|RangeError|ReferenceError|StopIteration|" + // Errors "SyntaxError|TypeError|URIError|" + "decodeURI|decodeURIComponent|encodeURI|encodeURIComponent|eval|isFinite|" + // Non-constructor functions "isNaN|parseFloat|parseInt|" + "JSON|Math|" + // Other "this|arguments|prototype|window|document" , // Pseudo "keyword": "const|yield|import|get|set|async|await|" + "break|case|catch|continue|default|delete|do|else|finally|for|function|" + "if|in|instanceof|new|return|switch|throw|try|typeof|let|var|while|with|debugger|" + "__parent__|__count__|escape|unescape|with|__proto__|" + "class|enum|extends|super|export|implements|private|public|interface|package|protected|static", "storage.type": "const|let|var|function", "constant.language": "null|Infinity|NaN|undefined", "support.function": "alert", "constant.language.boolean": "true|false" }, "identifier"); var kwBeforeRe = "case|do|else|finally|in|instanceof|return|throw|try|typeof|yield|void"; var escapedRe = "\\\\(?:x[0-9a-fA-F]{2}|" + // hex "u[0-9a-fA-F]{4}|" + // unicode "u{[0-9a-fA-F]{1,6}}|" + // es6 unicode "[0-2][0-7]{0,2}|" + // oct "3[0-7][0-7]?|" + // oct "[4-7][0-7]?|" + //oct ".)"; this.$rules = { "no_regex" : [ DocCommentHighlightRules.getStartRule("doc-start"), comments("no_regex"), { token : "string", regex : "'(?=.)", next : "qstring" }, { token : "string", regex : '"(?=.)', next : "qqstring" }, { token : "constant.numeric", // hex regex : /0(?:[xX][0-9a-fA-F]+|[bB][01]+)\b/ }, { token : "constant.numeric", // float regex : /[+-]?\d[\d_]*(?:(?:\.\d*)?(?:[eE][+-]?\d+)?)?\b/ }, { token : [ "storage.type", "punctuation.operator", "support.function", "punctuation.operator", "entity.name.function", "text","keyword.operator" ], regex : "(" + identifierRe + ")(\\.)(prototype)(\\.)(" + identifierRe +")(\\s*)(=)", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(\\s+)(\\w+)(\\s*)(\\()", next: "function_arguments" }, { token : [ "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(function)(\\s+)(" + identifierRe + ")(\\s*)(\\()", next: "function_arguments" }, { token : [ "entity.name.function", "text", "punctuation.operator", "text", "storage.type", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\s*)(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : [ "text", "text", "storage.type", "text", "paren.lparen" ], regex : "(:)(\\s*)(function)(\\s*)(\\()", next: "function_arguments" }, { token : "keyword", regex : "(?:" + kwBeforeRe + ")\\b", next : "start" }, { token : ["support.constant"], regex : /that\b/ }, { token : ["storage.type", "punctuation.operator", "support.function.firebug"], regex : /(console)(\.)(warn|info|log|error|time|trace|timeEnd|assert)\b/ }, { token : keywordMapper, regex : identifierRe }, { token : "punctuation.operator", regex : /[.](?![.])/, next : "property" }, { token : "keyword.operator", regex : /--|\+\+|\.{3}|===|==|=|!=|!==|<+=?|>+=?|!|&&|\|\||\?:|[!$%&*+\-~\/^]=?/, next : "start" }, { token : "punctuation.operator", regex : /[?:,;.]/, next : "start" }, { token : "paren.lparen", regex : /[\[({]/, next : "start" }, { token : "paren.rparen", regex : /[\])}]/ }, { token: "comment", regex: /^#!.*$/ } ], property: [{ token : "text", regex : "\\s+" }, { token : [ "storage.type", "punctuation.operator", "entity.name.function", "text", "keyword.operator", "text", "storage.type", "text", "entity.name.function", "text", "paren.lparen" ], regex : "(" + identifierRe + ")(\\.)(" + identifierRe +")(\\s*)(=)(\\s*)(function)(?:(\\s+)(\\w+))?(\\s*)(\\()", next: "function_arguments" }, { token : "punctuation.operator", regex : /[.](?![.])/ }, { token : "support.function", regex : /(s(?:h(?:ift|ow(?:Mod(?:elessDialog|alDialog)|Help))|croll(?:X|By(?:Pages|Lines)?|Y|To)?|t(?:op|rike)|i(?:n|zeToContent|debar|gnText)|ort|u(?:p|b(?:str(?:ing)?)?)|pli(?:ce|t)|e(?:nd|t(?:Re(?:sizable|questHeader)|M(?:i(?:nutes|lliseconds)|onth)|Seconds|Ho(?:tKeys|urs)|Year|Cursor|Time(?:out)?|Interval|ZOptions|Date|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Date|FullYear)|FullYear|Active)|arch)|qrt|lice|avePreferences|mall)|h(?:ome|andleEvent)|navigate|c(?:har(?:CodeAt|At)|o(?:s|n(?:cat|textual|firm)|mpile)|eil|lear(?:Timeout|Interval)?|a(?:ptureEvents|ll)|reate(?:StyleSheet|Popup|EventObject))|t(?:o(?:GMTString|S(?:tring|ource)|U(?:TCString|pperCase)|Lo(?:caleString|werCase))|est|a(?:n|int(?:Enabled)?))|i(?:s(?:NaN|Finite)|ndexOf|talics)|d(?:isableExternalCapture|ump|etachEvent)|u(?:n(?:shift|taint|escape|watch)|pdateCommands)|j(?:oin|avaEnabled)|p(?:o(?:p|w)|ush|lugins.refresh|a(?:ddings|rse(?:Int|Float)?)|r(?:int|ompt|eference))|e(?:scape|nableExternalCapture|val|lementFromPoint|x(?:p|ec(?:Script|Command)?))|valueOf|UTC|queryCommand(?:State|Indeterm|Enabled|Value)|f(?:i(?:nd|le(?:ModifiedDate|Size|CreatedDate|UpdatedDate)|xed)|o(?:nt(?:size|color)|rward)|loor|romCharCode)|watch|l(?:ink|o(?:ad|g)|astIndexOf)|a(?:sin|nchor|cos|t(?:tachEvent|ob|an(?:2)?)|pply|lert|b(?:s|ort))|r(?:ou(?:nd|teEvents)|e(?:size(?:By|To)|calc|turnValue|place|verse|l(?:oad|ease(?:Capture|Events)))|andom)|g(?:o|et(?:ResponseHeader|M(?:i(?:nutes|lliseconds)|onth)|Se(?:conds|lection)|Hours|Year|Time(?:zoneOffset)?|Da(?:y|te)|UTC(?:M(?:i(?:nutes|lliseconds)|onth)|Seconds|Hours|Da(?:y|te)|FullYear)|FullYear|A(?:ttention|llResponseHeaders)))|m(?:in|ove(?:B(?:y|elow)|To(?:Absolute)?|Above)|ergeAttributes|a(?:tch|rgins|x))|b(?:toa|ig|o(?:ld|rderWidths)|link|ack))\b(?=\()/ }, { token : "support.function.dom", regex : /(s(?:ub(?:stringData|mit)|plitText|e(?:t(?:NamedItem|Attribute(?:Node)?)|lect))|has(?:ChildNodes|Feature)|namedItem|c(?:l(?:ick|o(?:se|neNode))|reate(?:C(?:omment|DATASection|aption)|T(?:Head|extNode|Foot)|DocumentFragment|ProcessingInstruction|E(?:ntityReference|lement)|Attribute))|tabIndex|i(?:nsert(?:Row|Before|Cell|Data)|tem)|open|delete(?:Row|C(?:ell|aption)|T(?:Head|Foot)|Data)|focus|write(?:ln)?|a(?:dd|ppend(?:Child|Data))|re(?:set|place(?:Child|Data)|move(?:NamedItem|Child|Attribute(?:Node)?)?)|get(?:NamedItem|Element(?:sBy(?:Name|TagName|ClassName)|ById)|Attribute(?:Node)?)|blur)\b(?=\()/ }, { token : "support.constant", regex : /(s(?:ystemLanguage|cr(?:ipts|ollbars|een(?:X|Y|Top|Left))|t(?:yle(?:Sheets)?|atus(?:Text|bar)?)|ibling(?:Below|Above)|ource|uffixes|e(?:curity(?:Policy)?|l(?:ection|f)))|h(?:istory|ost(?:name)?|as(?:h|Focus))|y|X(?:MLDocument|SLDocument)|n(?:ext|ame(?:space(?:s|URI)|Prop))|M(?:IN_VALUE|AX_VALUE)|c(?:haracterSet|o(?:n(?:structor|trollers)|okieEnabled|lorDepth|mp(?:onents|lete))|urrent|puClass|l(?:i(?:p(?:boardData)?|entInformation)|osed|asses)|alle(?:e|r)|rypto)|t(?:o(?:olbar|p)|ext(?:Transform|Indent|Decoration|Align)|ags)|SQRT(?:1_2|2)|i(?:n(?:ner(?:Height|Width)|put)|ds|gnoreCase)|zIndex|o(?:scpu|n(?:readystatechange|Line)|uter(?:Height|Width)|p(?:sProfile|ener)|ffscreenBuffering)|NEGATIVE_INFINITY|d(?:i(?:splay|alog(?:Height|Top|Width|Left|Arguments)|rectories)|e(?:scription|fault(?:Status|Ch(?:ecked|arset)|View)))|u(?:ser(?:Profile|Language|Agent)|n(?:iqueID|defined)|pdateInterval)|_content|p(?:ixelDepth|ort|ersonalbar|kcs11|l(?:ugins|atform)|a(?:thname|dding(?:Right|Bottom|Top|Left)|rent(?:Window|Layer)?|ge(?:X(?:Offset)?|Y(?:Offset)?))|r(?:o(?:to(?:col|type)|duct(?:Sub)?|mpter)|e(?:vious|fix)))|e(?:n(?:coding|abledPlugin)|x(?:ternal|pando)|mbeds)|v(?:isibility|endor(?:Sub)?|Linkcolor)|URLUnencoded|P(?:I|OSITIVE_INFINITY)|f(?:ilename|o(?:nt(?:Size|Family|Weight)|rmName)|rame(?:s|Element)|gColor)|E|whiteSpace|l(?:i(?:stStyleType|n(?:eHeight|kColor))|o(?:ca(?:tion(?:bar)?|lName)|wsrc)|e(?:ngth|ft(?:Context)?)|a(?:st(?:M(?:odified|atch)|Index|Paren)|yer(?:s|X)|nguage))|a(?:pp(?:MinorVersion|Name|Co(?:deName|re)|Version)|vail(?:Height|Top|Width|Left)|ll|r(?:ity|guments)|Linkcolor|bove)|r(?:ight(?:Context)?|e(?:sponse(?:XML|Text)|adyState))|global|x|m(?:imeTypes|ultiline|enubar|argin(?:Right|Bottom|Top|Left))|L(?:N(?:10|2)|OG(?:10E|2E))|b(?:o(?:ttom|rder(?:Width|RightWidth|BottomWidth|Style|Color|TopWidth|LeftWidth))|ufferDepth|elow|ackground(?:Color|Image)))\b/ }, { token : "identifier", regex : identifierRe }, { regex: "", token: "empty", next: "no_regex" } ], "start": [ DocCommentHighlightRules.getStartRule("doc-start"), comments("start"), { token: "string.regexp", regex: "\\/", next: "regex" }, { token : "text", regex : "\\s+|^$", next : "start" }, { token: "empty", regex: "", next: "no_regex" } ], "regex": [ { token: "regexp.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "string.regexp", regex: "/[sxngimy]*", next: "no_regex" }, { token : "invalid", regex: /\{\d+\b,?\d*\}[+*]|[+*$^?][+*]|[$^][?]|\?{3,}/ }, { token : "constant.language.escape", regex: /\(\?[:=!]|\)|\{\d+\b,?\d*\}|[+*]\?|[()$^+*?.]/ }, { token : "constant.language.delimiter", regex: /\|/ }, { token: "constant.language.escape", regex: /\[\^?/, next: "regex_character_class" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp" } ], "regex_character_class": [ { token: "regexp.charclass.keyword.operator", regex: "\\\\(?:u[\\da-fA-F]{4}|x[\\da-fA-F]{2}|.)" }, { token: "constant.language.escape", regex: "]", next: "regex" }, { token: "constant.language.escape", regex: "-" }, { token: "empty", regex: "$", next: "no_regex" }, { defaultToken: "string.regexp.charachterclass" } ], "function_arguments": [ { token: "variable.parameter", regex: identifierRe }, { token: "punctuation.operator", regex: "[, ]+" }, { token: "punctuation.operator", regex: "$" }, { token: "empty", regex: "", next: "no_regex" } ], "qqstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qqstring" }, { token : "string", regex : '"|$', next : "no_regex" }, { defaultToken: "string" } ], "qstring" : [ { token : "constant.language.escape", regex : escapedRe }, { token : "string", regex : "\\\\$", next : "qstring" }, { token : "string", regex : "'|$", next : "no_regex" }, { defaultToken: "string" } ] }; if (!options || !options.noES6) { this.$rules.no_regex.unshift({ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); } else if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1 || this.next.indexOf("jsx") != -1) return "paren.quasi.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.quasi.start", regex : /`/, push : [{ token : "constant.language.escape", regex : escapedRe }, { token : "paren.quasi.start", regex : /\${/, push : "start" }, { token : "string.quasi.end", regex : /`/, next : "pop" }, { defaultToken: "string.quasi" }] }); if (!options || options.jsx != false) JSX.call(this); } this.embedRules(DocCommentHighlightRules, "doc-", [ DocCommentHighlightRules.getEndRule("no_regex") ]); this.normalizeRules(); }; oop.inherits(JavaScriptHighlightRules, TextHighlightRules); function JSX() { var tagRegex = identifierRe.replace("\\d", "\\d\\-"); var jsxTag = { onMatch : function(val, state, stack) { var offset = val.charAt(1) == "/" ? 2 : 1; if (offset == 1) { if (state != this.nextState) stack.unshift(this.next, this.nextState, 0); else stack.unshift(this.next); stack[2]++; } else if (offset == 2) { if (state == this.nextState) { stack[1]--; if (!stack[1] || stack[1] < 0) { stack.shift(); stack.shift(); } } } return [{ type: "meta.tag.punctuation." + (offset == 1 ? "" : "end-") + "tag-open.xml", value: val.slice(0, offset) }, { type: "meta.tag.tag-name.xml", value: val.substr(offset) }]; }, regex : "</?" + tagRegex + "", next: "jsxAttributes", nextState: "jsx" }; this.$rules.start.unshift(jsxTag); var jsxJsRule = { regex: "{", token: "paren.quasi.start", push: "start" }; this.$rules.jsx = [ jsxJsRule, jsxTag, {include : "reference"}, {defaultToken: "string"} ]; this.$rules.jsxAttributes = [{ token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", onMatch : function(value, currentState, stack) { if (currentState == stack[0]) stack.shift(); if (value.length == 2) { if (stack[0] == this.nextState) stack[1]--; if (!stack[1] || stack[1] < 0) { stack.splice(0, 2); } } this.next = stack[0] || "start"; return [{type: this.token, value: value}]; }, nextState: "jsx" }, jsxJsRule, comments("jsxAttributes"), { token : "entity.other.attribute-name.xml", regex : tagRegex }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { token : "text.tag-whitespace.xml", regex : "\\s+" }, { token : "string.attribute-value.xml", regex : "'", stateName : "jsx_attr_q", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', stateName : "jsx_attr_qq", push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "reference"}, {defaultToken : "string.attribute-value.xml"} ] }, jsxTag ]; this.$rules.reference = [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }]; } function comments(next) { return [ { token : "comment", // multi line comment regex : /\/\*/, next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "\\*\\/", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] }, { token : "comment", regex : "\\/\\/", next: [ DocCommentHighlightRules.getTagRule(), {token : "comment", regex : "$|^", next : next || "pop"}, {defaultToken : "comment", caseInsensitive: true} ] } ]; } exports.JavaScriptHighlightRules = JavaScriptHighlightRules; }); ace.define("ace/mode/xml_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var XmlHighlightRules = function(normalize) { var tagRegex = "[_:a-zA-Z\xc0-\uffff][-_:.a-zA-Z0-9\xc0-\uffff]*"; this.$rules = { start : [ {token : "string.cdata.xml", regex : "<\\!\\[CDATA\\[", next : "cdata"}, { token : ["punctuation.xml-decl.xml", "keyword.xml-decl.xml"], regex : "(<\\?)(xml)(?=[\\s])", next : "xml_decl", caseInsensitive: true }, { token : ["punctuation.instruction.xml", "keyword.instruction.xml"], regex : "(<\\?)(" + tagRegex + ")", next : "processing_instruction" }, {token : "comment.xml", regex : "<\\!--", next : "comment"}, { token : ["xml-pe.doctype.xml", "xml-pe.doctype.xml"], regex : "(<\\!)(DOCTYPE)(?=[\\s])", next : "doctype", caseInsensitive: true }, {include : "tag"}, {token : "text.end-tag-open.xml", regex: "</"}, {token : "text.tag-open.xml", regex: "<"}, {include : "reference"}, {defaultToken : "text.xml"} ], xml_decl : [{ token : "entity.other.attribute-name.decl-attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.decl-attribute-equals.xml", regex : "=" }, { include: "whitespace" }, { include: "string" }, { token : "punctuation.xml-decl.xml", regex : "\\?>", next : "start" }], processing_instruction : [ {token : "punctuation.instruction.xml", regex : "\\?>", next : "start"}, {defaultToken : "instruction.xml"} ], doctype : [ {include : "whitespace"}, {include : "string"}, {token : "xml-pe.doctype.xml", regex : ">", next : "start"}, {token : "xml-pe.xml", regex : "[-_a-zA-Z0-9:]+"}, {token : "punctuation.int-subset", regex : "\\[", push : "int_subset"} ], int_subset : [{ token : "text.xml", regex : "\\s+" }, { token: "punctuation.int-subset.xml", regex: "]", next: "pop" }, { token : ["punctuation.markup-decl.xml", "keyword.markup-decl.xml"], regex : "(<\\!)(" + tagRegex + ")", push : [{ token : "text", regex : "\\s+" }, { token : "punctuation.markup-decl.xml", regex : ">", next : "pop" }, {include : "string"}] }], cdata : [ {token : "string.cdata.xml", regex : "\\]\\]>", next : "start"}, {token : "text.xml", regex : "\\s+"}, {token : "text.xml", regex : "(?:[^\\]]|\\](?!\\]>))+"} ], comment : [ {token : "comment.xml", regex : "-->", next : "start"}, {defaultToken : "comment.xml"} ], reference : [{ token : "constant.language.escape.reference.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], attr_reference : [{ token : "constant.language.escape.reference.attribute-value.xml", regex : "(?:&#[0-9]+;)|(?:&#x[0-9a-fA-F]+;)|(?:&[a-zA-Z0-9_:\\.-]+;)" }], tag : [{ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag.punctuation.end-tag-open.xml", "meta.tag.tag-name.xml"], regex : "(?:(<)|(</))((?:" + tagRegex + ":)?" + tagRegex + ")", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }], tag_whitespace : [ {token : "text.tag-whitespace.xml", regex : "\\s+"} ], whitespace : [ {token : "text.whitespace.xml", regex : "\\s+"} ], string: [{ token : "string.xml", regex : "'", push : [ {token : "string.xml", regex: "'", next: "pop"}, {defaultToken : "string.xml"} ] }, { token : "string.xml", regex : '"', push : [ {token : "string.xml", regex: '"', next: "pop"}, {defaultToken : "string.xml"} ] }], attributes: [{ token : "entity.other.attribute-name.xml", regex : "(?:" + tagRegex + ":)?" + tagRegex + "" }, { token : "keyword.operator.attribute-equals.xml", regex : "=" }, { include: "tag_whitespace" }, { include: "attribute_value" }], attribute_value: [{ token : "string.attribute-value.xml", regex : "'", push : [ {token : "string.attribute-value.xml", regex: "'", next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }, { token : "string.attribute-value.xml", regex : '"', push : [ {token : "string.attribute-value.xml", regex: '"', next: "pop"}, {include : "attr_reference"}, {defaultToken : "string.attribute-value.xml"} ] }] }; if (this.constructor === XmlHighlightRules) this.normalizeRules(); }; (function() { this.embedTagRules = function(HighlightRules, prefix, tag){ this.$rules.tag.unshift({ token : ["meta.tag.punctuation.tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(<)(" + tag + "(?=\\s|>|$))", next: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : prefix + "start"} ] }); this.$rules[tag + "-end"] = [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next: "start", onMatch : function(value, currentState, stack) { stack.splice(0); return this.token; }} ] this.embedRules(HighlightRules, prefix, [{ token: ["meta.tag.punctuation.end-tag-open.xml", "meta.tag." + tag + ".tag-name.xml"], regex : "(</)(" + tag + "(?=\\s|>|$))", next: tag + "-end" }, { token: "string.cdata.xml", regex : "<\\!\\[CDATA\\[" }, { token: "string.cdata.xml", regex : "\\]\\]>" }]); }; }).call(TextHighlightRules.prototype); oop.inherits(XmlHighlightRules, TextHighlightRules); exports.XmlHighlightRules = XmlHighlightRules; }); ace.define("ace/mode/html_highlight_rules",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/css_highlight_rules","ace/mode/javascript_highlight_rules","ace/mode/xml_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var XmlHighlightRules = require("./xml_highlight_rules").XmlHighlightRules; var tagMap = lang.createMap({ a : 'anchor', button : 'form', form : 'form', img : 'image', input : 'form', label : 'form', option : 'form', script : 'script', select : 'form', textarea : 'form', style : 'style', table : 'table', tbody : 'table', td : 'table', tfoot : 'table', th : 'table', tr : 'table' }); var HtmlHighlightRules = function() { XmlHighlightRules.call(this); this.addRules({ attributes: [{ include : "tag_whitespace" }, { token : "entity.other.attribute-name.xml", regex : "[-_a-zA-Z0-9:.]+" }, { token : "keyword.operator.attribute-equals.xml", regex : "=", push : [{ include: "tag_whitespace" }, { token : "string.unquoted.attribute-value.html", regex : "[^<>='\"`\\s]+", next : "pop" }, { token : "empty", regex : "", next : "pop" }] }, { include : "attribute_value" }], tag: [{ token : function(start, tag) { var group = tagMap[tag]; return ["meta.tag.punctuation." + (start == "<" ? "" : "end-") + "tag-open.xml", "meta.tag" + (group ? "." + group : "") + ".tag-name.xml"]; }, regex : "(</?)([-_a-zA-Z0-9:.]+)", next: "tag_stuff" }], tag_stuff: [ {include : "attributes"}, {token : "meta.tag.punctuation.tag-close.xml", regex : "/?>", next : "start"} ] }); this.embedTagRules(CssHighlightRules, "css-", "style"); this.embedTagRules(new JavaScriptHighlightRules({jsx: false}).getRules(), "js-", "script"); if (this.constructor === HtmlHighlightRules) this.normalizeRules(); }; oop.inherits(HtmlHighlightRules, XmlHighlightRules); exports.HtmlHighlightRules = HtmlHighlightRules; }); ace.define("ace/mode/ruby_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/text_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var constantOtherSymbol = exports.constantOtherSymbol = { token : "constant.other.symbol.ruby", // symbol regex : "[:](?:[A-Za-z_]|[@$](?=[a-zA-Z0-9_]))[a-zA-Z0-9_]*[!=?]?" }; var qString = exports.qString = { token : "string", // single line regex : "['](?:(?:\\\\.)|(?:[^'\\\\]))*?[']" }; var qqString = exports.qqString = { token : "string", // single line regex : '["](?:(?:\\\\.)|(?:[^"\\\\]))*?["]' }; var tString = exports.tString = { token : "string", // backtick string regex : "[`](?:(?:\\\\.)|(?:[^'\\\\]))*?[`]" }; var constantNumericHex = exports.constantNumericHex = { token : "constant.numeric", // hex regex : "0[xX][0-9a-fA-F](?:[0-9a-fA-F]|_(?=[0-9a-fA-F]))*\\b" }; var constantNumericFloat = exports.constantNumericFloat = { token : "constant.numeric", // float regex : "[+-]?\\d(?:\\d|_(?=\\d))*(?:(?:\\.\\d(?:\\d|_(?=\\d))*)?(?:[eE][+-]?\\d+)?)?\\b" }; var RubyHighlightRules = function() { var builtinFunctions = ( "abort|Array|assert|assert_equal|assert_not_equal|assert_same|assert_not_same|" + "assert_nil|assert_not_nil|assert_match|assert_no_match|assert_in_delta|assert_throws|" + "assert_raise|assert_nothing_raised|assert_instance_of|assert_kind_of|assert_respond_to|" + "assert_operator|assert_send|assert_difference|assert_no_difference|assert_recognizes|" + "assert_generates|assert_response|assert_redirected_to|assert_template|assert_select|" + "assert_select_email|assert_select_rjs|assert_select_encoded|css_select|at_exit|" + "attr|attr_writer|attr_reader|attr_accessor|attr_accessible|autoload|binding|block_given?|callcc|" + "caller|catch|chomp|chomp!|chop|chop!|defined?|delete_via_redirect|eval|exec|exit|" + "exit!|fail|Float|flunk|follow_redirect!|fork|form_for|form_tag|format|gets|global_variables|gsub|" + "gsub!|get_via_redirect|host!|https?|https!|include|Integer|lambda|link_to|" + "link_to_unless_current|link_to_function|link_to_remote|load|local_variables|loop|open|open_session|" + "p|print|printf|proc|putc|puts|post_via_redirect|put_via_redirect|raise|rand|" + "raw|readline|readlines|redirect?|request_via_redirect|require|scan|select|" + "set_trace_func|sleep|split|sprintf|srand|String|stylesheet_link_tag|syscall|system|sub|sub!|test|" + "throw|trace_var|trap|untrace_var|atan2|cos|exp|frexp|ldexp|log|log10|sin|sqrt|tan|" + "render|javascript_include_tag|csrf_meta_tag|label_tag|text_field_tag|submit_tag|check_box_tag|" + "content_tag|radio_button_tag|text_area_tag|password_field_tag|hidden_field_tag|" + "fields_for|select_tag|options_for_select|options_from_collection_for_select|collection_select|" + "time_zone_select|select_date|select_time|select_datetime|date_select|time_select|datetime_select|" + "select_year|select_month|select_day|select_hour|select_minute|select_second|file_field_tag|" + "file_field|respond_to|skip_before_filter|around_filter|after_filter|verify|" + "protect_from_forgery|rescue_from|helper_method|redirect_to|before_filter|" + "send_data|send_file|validates_presence_of|validates_uniqueness_of|validates_length_of|" + "validates_format_of|validates_acceptance_of|validates_associated|validates_exclusion_of|" + "validates_inclusion_of|validates_numericality_of|validates_with|validates_each|" + "authenticate_or_request_with_http_basic|authenticate_or_request_with_http_digest|" + "filter_parameter_logging|match|get|post|resources|redirect|scope|assert_routing|" + "translate|localize|extract_locale_from_tld|caches_page|expire_page|caches_action|expire_action|" + "cache|expire_fragment|expire_cache_for|observe|cache_sweeper|" + "has_many|has_one|belongs_to|has_and_belongs_to_many" ); var keywords = ( "alias|and|BEGIN|begin|break|case|class|def|defined|do|else|elsif|END|end|ensure|" + "__FILE__|finally|for|gem|if|in|__LINE__|module|next|not|or|private|protected|public|" + "redo|rescue|retry|return|super|then|undef|unless|until|when|while|yield" ); var buildinConstants = ( "true|TRUE|false|FALSE|nil|NIL|ARGF|ARGV|DATA|ENV|RUBY_PLATFORM|RUBY_RELEASE_DATE|" + "RUBY_VERSION|STDERR|STDIN|STDOUT|TOPLEVEL_BINDING" ); var builtinVariables = ( "$DEBUG|$defout|$FILENAME|$LOAD_PATH|$SAFE|$stdin|$stdout|$stderr|$VERBOSE|" + "$!|root_url|flash|session|cookies|params|request|response|logger|self" ); var keywordMapper = this.$keywords = this.createKeywordMapper({ "keyword": keywords, "constant.language": buildinConstants, "variable.language": builtinVariables, "support.function": builtinFunctions, "invalid.deprecated": "debugger" // TODO is this a remnant from js mode? }, "identifier"); this.$rules = { "start" : [ { token : "comment", regex : "#.*$" }, { token : "comment", // multi line comment regex : "^=begin(?:$|\\s.*$)", next : "comment" }, { token : "string.regexp", regex : "[/](?:(?:\\[(?:\\\\]|[^\\]])+\\])|(?:\\\\/|[^\\]/]))*[/]\\w*\\s*(?=[).,;]|$)" }, [{ regex: "[{}]", onMatch: function(val, state, stack) { this.next = val == "{" ? this.nextState : ""; if (val == "{" && stack.length) { stack.unshift("start", state); return "paren.lparen"; } if (val == "}" && stack.length) { stack.shift(); this.next = stack.shift(); if (this.next.indexOf("string") != -1) return "paren.end"; } return val == "{" ? "paren.lparen" : "paren.rparen"; }, nextState: "start" }, { token : "string.start", regex : /"/, push : [{ token : "constant.language.escape", regex : /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/ }, { token : "paren.start", regex : /#{/, push : "start" }, { token : "string.end", regex : /"/, next : "pop" }, { defaultToken: "string" }] }, { token : "string.start", regex : /`/, push : [{ token : "constant.language.escape", regex : /\\(?:[nsrtvfbae'"\\]|c.|C-.|M-.(?:\\C-.)?|[0-7]{3}|x[\da-fA-F]{2}|u[\da-fA-F]{4})/ }, { token : "paren.start", regex : /#{/, push : "start" }, { token : "string.end", regex : /`/, next : "pop" }, { defaultToken: "string" }] }, { token : "string.start", regex : /'/, push : [{ token : "constant.language.escape", regex : /\\['\\]/ }, { token : "string.end", regex : /'/, next : "pop" }, { defaultToken: "string" }] }], { token : "text", // namespaces aren't symbols regex : "::" }, { token : "variable.instance", // instance variable regex : "@{1,2}[a-zA-Z_\\d]+" }, { token : "support.class", // class name regex : "[A-Z][a-zA-Z_\\d]+" }, constantOtherSymbol, constantNumericHex, constantNumericFloat, { token : "constant.language.boolean", regex : "(?:true|false)\\b" }, { token : keywordMapper, regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b" }, { token : "punctuation.separator.key-value", regex : "=>" }, { stateName: "heredoc", onMatch : function(value, currentState, stack) { var next = value[2] == '-' ? "indentedHeredoc" : "heredoc"; var tokens = value.split(this.splitRegex); stack.push(next, tokens[3]); return [ {type:"constant", value: tokens[1]}, {type:"string", value: tokens[2]}, {type:"support.class", value: tokens[3]}, {type:"string", value: tokens[4]} ]; }, regex : "(<<-?)(['\"`]?)([\\w]+)(['\"`]?)", rules: { heredoc: [{ onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }], indentedHeredoc: [{ token: "string", regex: "^ +" }, { onMatch: function(value, currentState, stack) { if (value === stack[1]) { stack.shift(); stack.shift(); this.next = stack[0] || "start"; return "support.class"; } this.next = ""; return "string"; }, regex: ".*$", next: "start" }] } }, { regex : "$", token : "empty", next : function(currentState, stack) { if (stack[0] === "heredoc" || stack[0] === "indentedHeredoc") return stack[0]; return currentState; } }, { token : "string.character", regex : "\\B\\?." }, { token : "keyword.operator", regex : "!|\\$|%|&|\\*|\\-\\-|\\-|\\+\\+|\\+|~|===|==|=|!=|!==|<=|>=|<<=|>>=|>>>=|<>|<|>|!|&&|\\|\\||\\?\\:|\\*=|%=|\\+=|\\-=|&=|\\^=|\\b(?:in|instanceof|new|delete|typeof|void)" }, { token : "paren.lparen", regex : "[[({]" }, { token : "paren.rparen", regex : "[\\])}]" }, { token : "text", regex : "\\s+" } ], "comment" : [ { token : "comment", // closing comment regex : "^=end(?:$|\\s.*$)", next : "start" }, { token : "comment", // comment spanning whole line regex : ".+" } ] }; this.normalizeRules(); }; oop.inherits(RubyHighlightRules, TextHighlightRules); exports.RubyHighlightRules = RubyHighlightRules; }); ace.define("ace/mode/html_ruby_highlight_rules",["require","exports","module","ace/lib/oop","ace/mode/html_highlight_rules","ace/mode/ruby_highlight_rules"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules; var HtmlRubyHighlightRules = function() { HtmlHighlightRules.call(this); var startRules = [ { regex: "<%%|%%>", token: "constant.language.escape" }, { token : "comment.start.erb", regex : "<%#", push : [{ token : "comment.end.erb", regex: "%>", next: "pop", defaultToken:"comment" }] }, { token : "support.ruby_tag", regex : "<%+(?!>)[-=]?", push : "ruby-start" } ]; var endRules = [ { token : "support.ruby_tag", regex : "%>", next : "pop" }, { token: "comment", regex: "#(?:[^%]|%[^>])*" } ]; for (var key in this.$rules) this.$rules[key].unshift.apply(this.$rules[key], startRules); this.embedRules(RubyHighlightRules, "ruby-", endRules, ["start"]); this.normalizeRules(); }; oop.inherits(HtmlRubyHighlightRules, HtmlHighlightRules); exports.HtmlRubyHighlightRules = HtmlRubyHighlightRules; }); ace.define("ace/mode/matching_brace_outdent",["require","exports","module","ace/range"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var MatchingBraceOutdent = function() {}; (function() { this.checkOutdent = function(line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*\}/.test(input); }; this.autoOutdent = function(doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*\})/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.$getIndent = function(line) { return line.match(/^\s*/)[0]; }; }).call(MatchingBraceOutdent.prototype); exports.MatchingBraceOutdent = MatchingBraceOutdent; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/javascript",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/javascript_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/worker/worker_client","ace/mode/behaviour/cstyle","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var JavaScriptHighlightRules = require("./javascript_highlight_rules").JavaScriptHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var WorkerClient = require("../worker/worker_client").WorkerClient; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = JavaScriptHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "//"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; var endState = tokenizedLine.state; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start" || state == "no_regex") { var match = line.match(/^.*(?:\bcase\b.*:|[\{\(\[])\s*$/); if (match) { indent += tab; } } else if (state == "doc-start") { if (endState == "start" || endState == "no_regex") { return ""; } var match = line.match(/^\s*(\/?)\*/); if (match) { if (match[1]) { indent += " "; } indent += "* "; } } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/javascript_worker", "JavaScriptWorker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(results) { session.setAnnotations(results.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/javascript"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/css_completions",["require","exports","module"], function(require, exports, module) { "use strict"; var propertyMap = { "background": {"#$0": 1}, "background-color": {"#$0": 1, "transparent": 1, "fixed": 1}, "background-image": {"url('/$0')": 1}, "background-repeat": {"repeat": 1, "repeat-x": 1, "repeat-y": 1, "no-repeat": 1, "inherit": 1}, "background-position": {"bottom":2, "center":2, "left":2, "right":2, "top":2, "inherit":2}, "background-attachment": {"scroll": 1, "fixed": 1}, "background-size": {"cover": 1, "contain": 1}, "background-clip": {"border-box": 1, "padding-box": 1, "content-box": 1}, "background-origin": {"border-box": 1, "padding-box": 1, "content-box": 1}, "border": {"solid $0": 1, "dashed $0": 1, "dotted $0": 1, "#$0": 1}, "border-color": {"#$0": 1}, "border-style": {"solid":2, "dashed":2, "dotted":2, "double":2, "groove":2, "hidden":2, "inherit":2, "inset":2, "none":2, "outset":2, "ridged":2}, "border-collapse": {"collapse": 1, "separate": 1}, "bottom": {"px": 1, "em": 1, "%": 1}, "clear": {"left": 1, "right": 1, "both": 1, "none": 1}, "color": {"#$0": 1, "rgb(#$00,0,0)": 1}, "cursor": {"default": 1, "pointer": 1, "move": 1, "text": 1, "wait": 1, "help": 1, "progress": 1, "n-resize": 1, "ne-resize": 1, "e-resize": 1, "se-resize": 1, "s-resize": 1, "sw-resize": 1, "w-resize": 1, "nw-resize": 1}, "display": {"none": 1, "block": 1, "inline": 1, "inline-block": 1, "table-cell": 1}, "empty-cells": {"show": 1, "hide": 1}, "float": {"left": 1, "right": 1, "none": 1}, "font-family": {"Arial":2,"Comic Sans MS":2,"Consolas":2,"Courier New":2,"Courier":2,"Georgia":2,"Monospace":2,"Sans-Serif":2, "Segoe UI":2,"Tahoma":2,"Times New Roman":2,"Trebuchet MS":2,"Verdana": 1}, "font-size": {"px": 1, "em": 1, "%": 1}, "font-weight": {"bold": 1, "normal": 1}, "font-style": {"italic": 1, "normal": 1}, "font-variant": {"normal": 1, "small-caps": 1}, "height": {"px": 1, "em": 1, "%": 1}, "left": {"px": 1, "em": 1, "%": 1}, "letter-spacing": {"normal": 1}, "line-height": {"normal": 1}, "list-style-type": {"none": 1, "disc": 1, "circle": 1, "square": 1, "decimal": 1, "decimal-leading-zero": 1, "lower-roman": 1, "upper-roman": 1, "lower-greek": 1, "lower-latin": 1, "upper-latin": 1, "georgian": 1, "lower-alpha": 1, "upper-alpha": 1}, "margin": {"px": 1, "em": 1, "%": 1}, "margin-right": {"px": 1, "em": 1, "%": 1}, "margin-left": {"px": 1, "em": 1, "%": 1}, "margin-top": {"px": 1, "em": 1, "%": 1}, "margin-bottom": {"px": 1, "em": 1, "%": 1}, "max-height": {"px": 1, "em": 1, "%": 1}, "max-width": {"px": 1, "em": 1, "%": 1}, "min-height": {"px": 1, "em": 1, "%": 1}, "min-width": {"px": 1, "em": 1, "%": 1}, "overflow": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-x": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "overflow-y": {"hidden": 1, "visible": 1, "auto": 1, "scroll": 1}, "padding": {"px": 1, "em": 1, "%": 1}, "padding-top": {"px": 1, "em": 1, "%": 1}, "padding-right": {"px": 1, "em": 1, "%": 1}, "padding-bottom": {"px": 1, "em": 1, "%": 1}, "padding-left": {"px": 1, "em": 1, "%": 1}, "page-break-after": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "page-break-before": {"auto": 1, "always": 1, "avoid": 1, "left": 1, "right": 1}, "position": {"absolute": 1, "relative": 1, "fixed": 1, "static": 1}, "right": {"px": 1, "em": 1, "%": 1}, "table-layout": {"fixed": 1, "auto": 1}, "text-decoration": {"none": 1, "underline": 1, "line-through": 1, "blink": 1}, "text-align": {"left": 1, "right": 1, "center": 1, "justify": 1}, "text-transform": {"capitalize": 1, "uppercase": 1, "lowercase": 1, "none": 1}, "top": {"px": 1, "em": 1, "%": 1}, "vertical-align": {"top": 1, "bottom": 1}, "visibility": {"hidden": 1, "visible": 1}, "white-space": {"nowrap": 1, "normal": 1, "pre": 1, "pre-line": 1, "pre-wrap": 1}, "width": {"px": 1, "em": 1, "%": 1}, "word-spacing": {"normal": 1}, "filter": {"alpha(opacity=$0100)": 1}, "text-shadow": {"$02px 2px 2px #777": 1}, "text-overflow": {"ellipsis-word": 1, "clip": 1, "ellipsis": 1}, "-moz-border-radius": 1, "-moz-border-radius-topright": 1, "-moz-border-radius-bottomright": 1, "-moz-border-radius-topleft": 1, "-moz-border-radius-bottomleft": 1, "-webkit-border-radius": 1, "-webkit-border-top-right-radius": 1, "-webkit-border-top-left-radius": 1, "-webkit-border-bottom-right-radius": 1, "-webkit-border-bottom-left-radius": 1, "-moz-box-shadow": 1, "-webkit-box-shadow": 1, "transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-moz-transform": {"rotate($00deg)": 1, "skew($00deg)": 1}, "-webkit-transform": {"rotate($00deg)": 1, "skew($00deg)": 1 } }; var CssCompletions = function() { }; (function() { this.completionsDefined = false; this.defineCompletions = function() { if (document) { var style = document.createElement('c').style; for (var i in style) { if (typeof style[i] !== 'string') continue; var name = i.replace(/[A-Z]/g, function(x) { return '-' + x.toLowerCase(); }); if (!propertyMap.hasOwnProperty(name)) propertyMap[name] = 1; } } this.completionsDefined = true; } this.getCompletions = function(state, session, pos, prefix) { if (!this.completionsDefined) { this.defineCompletions(); } var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (state==='ruleset'){ var line = session.getLine(pos.row).substr(0, pos.column); if (/:[^;]+$/.test(line)) { /([\w\-]+):[^:]*$/.test(line); return this.getPropertyValueCompletions(state, session, pos, prefix); } else { return this.getPropertyCompletions(state, session, pos, prefix); } } return []; }; this.getPropertyCompletions = function(state, session, pos, prefix) { var properties = Object.keys(propertyMap); return properties.map(function(property){ return { caption: property, snippet: property + ': $0', meta: "property", score: Number.MAX_VALUE }; }); }; this.getPropertyValueCompletions = function(state, session, pos, prefix) { var line = session.getLine(pos.row).substr(0, pos.column); var property = (/([\w\-]+):[^:]*$/.exec(line) || {})[1]; if (!property) return []; var values = []; if (property in propertyMap && typeof propertyMap[property] === "object") { values = Object.keys(propertyMap[property]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "property value", score: Number.MAX_VALUE }; }); }; }).call(CssCompletions.prototype); exports.CssCompletions = CssCompletions; }); ace.define("ace/mode/behaviour/css",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var CstyleBehaviour = require("./cstyle").CstyleBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var CssBehaviour = function () { this.inherit(CstyleBehaviour); this.add("colon", "insertion", function (state, action, editor, session, text) { if (text === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ':') { return { text: '', selection: [1, 1] } } if (!line.substring(cursor.column).match(/^\s*;/)) { return { text: ':;', selection: [1, 1] } } } } }); this.add("colon", "deletion", function (state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected === ':') { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.value.match(/\s+/)) { token = iterator.stepBackward(); } if (token && token.type === 'support.type') { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar === ';') { range.end.column ++; return range; } } } }); this.add("semicolon", "insertion", function (state, action, editor, session, text) { if (text === ';') { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === ';') { return { text: '', selection: [1, 1] } } } }); } oop.inherits(CssBehaviour, CstyleBehaviour); exports.CssBehaviour = CssBehaviour; }); ace.define("ace/mode/css",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/css_highlight_rules","ace/mode/matching_brace_outdent","ace/worker/worker_client","ace/mode/css_completions","ace/mode/behaviour/css","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var CssHighlightRules = require("./css_highlight_rules").CssHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var WorkerClient = require("../worker/worker_client").WorkerClient; var CssCompletions = require("./css_completions").CssCompletions; var CssBehaviour = require("./behaviour/css").CssBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Mode = function() { this.HighlightRules = CssHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CssBehaviour(); this.$completer = new CssCompletions(); this.foldingRules = new CStyleFoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.foldingRules = "cStyle"; this.blockComment = {start: "/*", end: "*/"}; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokens = this.getTokenizer().getLineTokens(line, state).tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } var match = line.match(/^.*\{\s*$/); if (match) { indent += tab; } return indent; }; this.checkOutdent = function(state, line, input) { return this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, doc, row) { this.$outdent.autoOutdent(doc, row); }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/css_worker", "Worker"); worker.attachToDocument(session.getDocument()); worker.on("annotate", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/css"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getSelectionRange().start; var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); if (token.value == "<") { token = iterator.stepForward(); break; } } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/folding/mixed",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(defaultMode, subModes) { this.defaultMode = defaultMode; this.subModes = subModes; }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.$getMode = function(state) { if (typeof state != "string") state = state[0]; for (var key in this.subModes) { if (state.indexOf(key) === 0) return this.subModes[key]; } return null; }; this.$tryMode = function(state, session, foldStyle, row) { var mode = this.$getMode(state); return (mode ? mode.getFoldWidget(session, foldStyle, row) : ""); }; this.getFoldWidget = function(session, foldStyle, row) { return ( this.$tryMode(session.getState(row-1), session, foldStyle, row) || this.$tryMode(session.getState(row), session, foldStyle, row) || this.defaultMode.getFoldWidget(session, foldStyle, row) ); }; this.getFoldWidgetRange = function(session, foldStyle, row) { var mode = this.$getMode(session.getState(row-1)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.$getMode(session.getState(row)); if (!mode || !mode.getFoldWidget(session, foldStyle, row)) mode = this.defaultMode; return mode.getFoldWidgetRange(session, foldStyle, row); }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/xml",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/range","ace/mode/folding/fold_mode","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var lang = require("../../lib/lang"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var TokenIterator = require("../../token_iterator").TokenIterator; var FoldMode = exports.FoldMode = function(voidElements, optionalEndTags) { BaseFoldMode.call(this); this.voidElements = voidElements || {}; this.optionalEndTags = oop.mixin({}, this.voidElements); if (optionalEndTags) oop.mixin(this.optionalEndTags, optionalEndTags); }; oop.inherits(FoldMode, BaseFoldMode); var Tag = function() { this.tagName = ""; this.closing = false; this.selfClosing = false; this.start = {row: 0, column: 0}; this.end = {row: 0, column: 0}; }; function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } (function() { this.getFoldWidget = function(session, foldStyle, row) { var tag = this._getFirstTagInLine(session, row); if (!tag) return ""; if (tag.closing || (!tag.tagName && tag.selfClosing)) return foldStyle == "markbeginend" ? "end" : ""; if (!tag.tagName || tag.selfClosing || this.voidElements.hasOwnProperty(tag.tagName.toLowerCase())) return ""; if (this._findEndTagInLine(session, row, tag.tagName, tag.end.column)) return ""; return "start"; }; this._getFirstTagInLine = function(session, row) { var tokens = session.getTokens(row); var tag = new Tag(); for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; if (is(token, "tag-open")) { tag.end.column = tag.start.column + token.value.length; tag.closing = is(token, "end-tag-open"); token = tokens[++i]; if (!token) return null; tag.tagName = token.value; tag.end.column += token.value.length; for (i++; i < tokens.length; i++) { token = tokens[i]; tag.end.column += token.value.length; if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; break; } } return tag; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == '/>'; return tag; } tag.start.column += token.value.length; } return null; }; this._findEndTagInLine = function(session, row, tagName, startColumn) { var tokens = session.getTokens(row); var column = 0; for (var i = 0; i < tokens.length; i++) { var token = tokens[i]; column += token.value.length; if (column < startColumn) continue; if (is(token, "end-tag-open")) { token = tokens[i + 1]; if (token && token.value == tagName) return true; } } return false; }; this._readTagForward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; iterator.stepForward(); return tag; } } while(token = iterator.stepForward()); return null; }; this._readTagBackward = function(iterator) { var token = iterator.getCurrentToken(); if (!token) return null; var tag = new Tag(); do { if (is(token, "tag-open")) { tag.closing = is(token, "end-tag-open"); tag.start.row = iterator.getCurrentTokenRow(); tag.start.column = iterator.getCurrentTokenColumn(); iterator.stepBackward(); return tag; } else if (is(token, "tag-name")) { tag.tagName = token.value; } else if (is(token, "tag-close")) { tag.selfClosing = token.value == "/>"; tag.end.row = iterator.getCurrentTokenRow(); tag.end.column = iterator.getCurrentTokenColumn() + token.value.length; } } while(token = iterator.stepBackward()); return null; }; this._pop = function(stack, tag) { while (stack.length) { var top = stack[stack.length-1]; if (!tag || top.tagName == tag.tagName) { return stack.pop(); } else if (this.optionalEndTags.hasOwnProperty(top.tagName)) { stack.pop(); continue; } else { return null; } } }; this.getFoldWidgetRange = function(session, foldStyle, row) { var firstTag = this._getFirstTagInLine(session, row); if (!firstTag) return null; var isBackward = firstTag.closing || firstTag.selfClosing; var stack = []; var tag; if (!isBackward) { var iterator = new TokenIterator(session, row, firstTag.start.column); var start = { row: row, column: firstTag.start.column + firstTag.tagName.length + 2 }; if (firstTag.start.row == firstTag.end.row) start.column = firstTag.end.column; while (tag = this._readTagForward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (tag.closing) { this._pop(stack, tag); if (stack.length == 0) return Range.fromPoints(start, tag.start); } else { stack.push(tag); } } } else { var iterator = new TokenIterator(session, row, firstTag.end.column); var end = { row: row, column: firstTag.start.column }; while (tag = this._readTagBackward(iterator)) { if (tag.selfClosing) { if (!stack.length) { tag.start.column += tag.tagName.length + 2; tag.end.column -= 2; return Range.fromPoints(tag.start, tag.end); } else continue; } if (!tag.closing) { this._pop(stack, tag); if (stack.length == 0) { tag.start.column += tag.tagName.length + 2; if (tag.start.row == tag.end.row && tag.start.column < tag.end.column) tag.start.column = tag.end.column; return Range.fromPoints(tag.start, end); } } else { stack.push(tag); } } } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/folding/html",["require","exports","module","ace/lib/oop","ace/mode/folding/mixed","ace/mode/folding/xml","ace/mode/folding/cstyle"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var MixedFoldMode = require("./mixed").FoldMode; var XmlFoldMode = require("./xml").FoldMode; var CStyleFoldMode = require("./cstyle").FoldMode; var FoldMode = exports.FoldMode = function(voidElements, optionalTags) { MixedFoldMode.call(this, new XmlFoldMode(voidElements, optionalTags), { "js-": new CStyleFoldMode(), "css-": new CStyleFoldMode() }); }; oop.inherits(FoldMode, MixedFoldMode); }); ace.define("ace/mode/html_completions",["require","exports","module","ace/token_iterator"], function(require, exports, module) { "use strict"; var TokenIterator = require("../token_iterator").TokenIterator; var commonAttributes = [ "accesskey", "class", "contenteditable", "contextmenu", "dir", "draggable", "dropzone", "hidden", "id", "inert", "itemid", "itemprop", "itemref", "itemscope", "itemtype", "lang", "spellcheck", "style", "tabindex", "title", "translate" ]; var eventAttributes = [ "onabort", "onblur", "oncancel", "oncanplay", "oncanplaythrough", "onchange", "onclick", "onclose", "oncontextmenu", "oncuechange", "ondblclick", "ondrag", "ondragend", "ondragenter", "ondragleave", "ondragover", "ondragstart", "ondrop", "ondurationchange", "onemptied", "onended", "onerror", "onfocus", "oninput", "oninvalid", "onkeydown", "onkeypress", "onkeyup", "onload", "onloadeddata", "onloadedmetadata", "onloadstart", "onmousedown", "onmousemove", "onmouseout", "onmouseover", "onmouseup", "onmousewheel", "onpause", "onplay", "onplaying", "onprogress", "onratechange", "onreset", "onscroll", "onseeked", "onseeking", "onselect", "onshow", "onstalled", "onsubmit", "onsuspend", "ontimeupdate", "onvolumechange", "onwaiting" ]; var globalAttributes = commonAttributes.concat(eventAttributes); var attributeMap = { "html": {"manifest": 1}, "head": {}, "title": {}, "base": {"href": 1, "target": 1}, "link": {"href": 1, "hreflang": 1, "rel": {"stylesheet": 1, "icon": 1}, "media": {"all": 1, "screen": 1, "print": 1}, "type": {"text/css": 1, "image/png": 1, "image/jpeg": 1, "image/gif": 1}, "sizes": 1}, "meta": {"http-equiv": {"content-type": 1}, "name": {"description": 1, "keywords": 1}, "content": {"text/html; charset=UTF-8": 1}, "charset": 1}, "style": {"type": 1, "media": {"all": 1, "screen": 1, "print": 1}, "scoped": 1}, "script": {"charset": 1, "type": {"text/javascript": 1}, "src": 1, "defer": 1, "async": 1}, "noscript": {"href": 1}, "body": {"onafterprint": 1, "onbeforeprint": 1, "onbeforeunload": 1, "onhashchange": 1, "onmessage": 1, "onoffline": 1, "onpopstate": 1, "onredo": 1, "onresize": 1, "onstorage": 1, "onundo": 1, "onunload": 1}, "section": {}, "nav": {}, "article": {"pubdate": 1}, "aside": {}, "h1": {}, "h2": {}, "h3": {}, "h4": {}, "h5": {}, "h6": {}, "header": {}, "footer": {}, "address": {}, "main": {}, "p": {}, "hr": {}, "pre": {}, "blockquote": {"cite": 1}, "ol": {"start": 1, "reversed": 1}, "ul": {}, "li": {"value": 1}, "dl": {}, "dt": {}, "dd": {}, "figure": {}, "figcaption": {}, "div": {}, "a": {"href": 1, "target": {"_blank": 1, "top": 1}, "ping": 1, "rel": {"nofollow": 1, "alternate": 1, "author": 1, "bookmark": 1, "help": 1, "license": 1, "next": 1, "noreferrer": 1, "prefetch": 1, "prev": 1, "search": 1, "tag": 1}, "media": 1, "hreflang": 1, "type": 1}, "em": {}, "strong": {}, "small": {}, "s": {}, "cite": {}, "q": {"cite": 1}, "dfn": {}, "abbr": {}, "data": {}, "time": {"datetime": 1}, "code": {}, "var": {}, "samp": {}, "kbd": {}, "sub": {}, "sup": {}, "i": {}, "b": {}, "u": {}, "mark": {}, "ruby": {}, "rt": {}, "rp": {}, "bdi": {}, "bdo": {}, "span": {}, "br": {}, "wbr": {}, "ins": {"cite": 1, "datetime": 1}, "del": {"cite": 1, "datetime": 1}, "img": {"alt": 1, "src": 1, "height": 1, "width": 1, "usemap": 1, "ismap": 1}, "iframe": {"name": 1, "src": 1, "height": 1, "width": 1, "sandbox": {"allow-same-origin": 1, "allow-top-navigation": 1, "allow-forms": 1, "allow-scripts": 1}, "seamless": {"seamless": 1}}, "embed": {"src": 1, "height": 1, "width": 1, "type": 1}, "object": {"param": 1, "data": 1, "type": 1, "height" : 1, "width": 1, "usemap": 1, "name": 1, "form": 1, "classid": 1}, "param": {"name": 1, "value": 1}, "video": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "width": 1, "height": 1, "poster": 1, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1}}, "audio": {"src": 1, "autobuffer": 1, "autoplay": {"autoplay": 1}, "loop": {"loop": 1}, "controls": {"controls": 1}, "muted": {"muted": 1}, "preload": {"auto": 1, "metadata": 1, "none": 1 }}, "source": {"src": 1, "type": 1, "media": 1}, "track": {"kind": 1, "src": 1, "srclang": 1, "label": 1, "default": 1}, "canvas": {"width": 1, "height": 1}, "map": {"name": 1}, "area": {"shape": 1, "coords": 1, "href": 1, "hreflang": 1, "alt": 1, "target": 1, "media": 1, "rel": 1, "ping": 1, "type": 1}, "svg": {}, "math": {}, "table": {"summary": 1}, "caption": {}, "colgroup": {"span": 1}, "col": {"span": 1}, "tbody": {}, "thead": {}, "tfoot": {}, "tr": {}, "td": {"headers": 1, "rowspan": 1, "colspan": 1}, "th": {"headers": 1, "rowspan": 1, "colspan": 1, "scope": 1}, "form": {"accept-charset": 1, "action": 1, "autocomplete": 1, "enctype": {"multipart/form-data": 1, "application/x-www-form-urlencoded": 1}, "method": {"get": 1, "post": 1}, "name": 1, "novalidate": 1, "target": {"_blank": 1, "top": 1}}, "fieldset": {"disabled": 1, "form": 1, "name": 1}, "legend": {}, "label": {"form": 1, "for": 1}, "input": { "type": {"text": 1, "password": 1, "hidden": 1, "checkbox": 1, "submit": 1, "radio": 1, "file": 1, "button": 1, "reset": 1, "image": 31, "color": 1, "date": 1, "datetime": 1, "datetime-local": 1, "email": 1, "month": 1, "number": 1, "range": 1, "search": 1, "tel": 1, "time": 1, "url": 1, "week": 1}, "accept": 1, "alt": 1, "autocomplete": {"on": 1, "off": 1}, "autofocus": {"autofocus": 1}, "checked": {"checked": 1}, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": {"application/x-www-form-urlencoded": 1, "multipart/form-data": 1, "text/plain": 1}, "formmethod": {"get": 1, "post": 1}, "formnovalidate": {"formnovalidate": 1}, "formtarget": {"_blank": 1, "_self": 1, "_parent": 1, "_top": 1}, "height": 1, "list": 1, "max": 1, "maxlength": 1, "min": 1, "multiple": {"multiple": 1}, "name": 1, "pattern": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "size": 1, "src": 1, "step": 1, "width": 1, "files": 1, "value": 1}, "button": {"autofocus": 1, "disabled": {"disabled": 1}, "form": 1, "formaction": 1, "formenctype": 1, "formmethod": 1, "formnovalidate": 1, "formtarget": 1, "name": 1, "value": 1, "type": {"button": 1, "submit": 1}}, "select": {"autofocus": 1, "disabled": 1, "form": 1, "multiple": {"multiple": 1}, "name": 1, "size": 1, "readonly":{"readonly": 1}}, "datalist": {}, "optgroup": {"disabled": 1, "label": 1}, "option": {"disabled": 1, "selected": 1, "label": 1, "value": 1}, "textarea": {"autofocus": {"autofocus": 1}, "disabled": {"disabled": 1}, "form": 1, "maxlength": 1, "name": 1, "placeholder": 1, "readonly": {"readonly": 1}, "required": {"required": 1}, "rows": 1, "cols": 1, "wrap": {"on": 1, "off": 1, "hard": 1, "soft": 1}}, "keygen": {"autofocus": 1, "challenge": {"challenge": 1}, "disabled": {"disabled": 1}, "form": 1, "keytype": {"rsa": 1, "dsa": 1, "ec": 1}, "name": 1}, "output": {"for": 1, "form": 1, "name": 1}, "progress": {"value": 1, "max": 1}, "meter": {"value": 1, "min": 1, "max": 1, "low": 1, "high": 1, "optimum": 1}, "details": {"open": 1}, "summary": {}, "command": {"type": 1, "label": 1, "icon": 1, "disabled": 1, "checked": 1, "radiogroup": 1, "command": 1}, "menu": {"type": 1, "label": 1}, "dialog": {"open": 1} }; var elements = Object.keys(attributeMap); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } function findTagName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "tag-name")){ token = iterator.stepBackward(); } if (token) return token.value; } function findAttributeName(session, pos) { var iterator = new TokenIterator(session, pos.row, pos.column); var token = iterator.getCurrentToken(); while (token && !is(token, "attribute-name")){ token = iterator.stepBackward(); } if (token) return token.value; } var HtmlCompletions = function() { }; (function() { this.getCompletions = function(state, session, pos, prefix) { var token = session.getTokenAt(pos.row, pos.column); if (!token) return []; if (is(token, "tag-name") || is(token, "tag-open") || is(token, "end-tag-open")) return this.getTagCompletions(state, session, pos, prefix); if (is(token, "tag-whitespace") || is(token, "attribute-name")) return this.getAttributeCompletions(state, session, pos, prefix); if (is(token, "attribute-value")) return this.getAttributeValueCompletions(state, session, pos, prefix); var line = session.getLine(pos.row).substr(0, pos.column); if (/&[A-z]*$/i.test(line)) return this.getHTMLEntityCompletions(state, session, pos, prefix); return []; }; this.getTagCompletions = function(state, session, pos, prefix) { return elements.map(function(element){ return { value: element, meta: "tag", score: Number.MAX_VALUE }; }); }; this.getAttributeCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); if (!tagName) return []; var attributes = globalAttributes; if (tagName in attributeMap) { attributes = attributes.concat(Object.keys(attributeMap[tagName])); } return attributes.map(function(attribute){ return { caption: attribute, snippet: attribute + '="$0"', meta: "attribute", score: Number.MAX_VALUE }; }); }; this.getAttributeValueCompletions = function(state, session, pos, prefix) { var tagName = findTagName(session, pos); var attributeName = findAttributeName(session, pos); if (!tagName) return []; var values = []; if (tagName in attributeMap && attributeName in attributeMap[tagName] && typeof attributeMap[tagName][attributeName] === "object") { values = Object.keys(attributeMap[tagName][attributeName]); } return values.map(function(value){ return { caption: value, snippet: value, meta: "attribute value", score: Number.MAX_VALUE }; }); }; this.getHTMLEntityCompletions = function(state, session, pos, prefix) { var values = ['Aacute;', 'aacute;', 'Acirc;', 'acirc;', 'acute;', 'AElig;', 'aelig;', 'Agrave;', 'agrave;', 'alefsym;', 'Alpha;', 'alpha;', 'amp;', 'and;', 'ang;', 'Aring;', 'aring;', 'asymp;', 'Atilde;', 'atilde;', 'Auml;', 'auml;', 'bdquo;', 'Beta;', 'beta;', 'brvbar;', 'bull;', 'cap;', 'Ccedil;', 'ccedil;', 'cedil;', 'cent;', 'Chi;', 'chi;', 'circ;', 'clubs;', 'cong;', 'copy;', 'crarr;', 'cup;', 'curren;', 'Dagger;', 'dagger;', 'dArr;', 'darr;', 'deg;', 'Delta;', 'delta;', 'diams;', 'divide;', 'Eacute;', 'eacute;', 'Ecirc;', 'ecirc;', 'Egrave;', 'egrave;', 'empty;', 'emsp;', 'ensp;', 'Epsilon;', 'epsilon;', 'equiv;', 'Eta;', 'eta;', 'ETH;', 'eth;', 'Euml;', 'euml;', 'euro;', 'exist;', 'fnof;', 'forall;', 'frac12;', 'frac14;', 'frac34;', 'frasl;', 'Gamma;', 'gamma;', 'ge;', 'gt;', 'hArr;', 'harr;', 'hearts;', 'hellip;', 'Iacute;', 'iacute;', 'Icirc;', 'icirc;', 'iexcl;', 'Igrave;', 'igrave;', 'image;', 'infin;', 'int;', 'Iota;', 'iota;', 'iquest;', 'isin;', 'Iuml;', 'iuml;', 'Kappa;', 'kappa;', 'Lambda;', 'lambda;', 'lang;', 'laquo;', 'lArr;', 'larr;', 'lceil;', 'ldquo;', 'le;', 'lfloor;', 'lowast;', 'loz;', 'lrm;', 'lsaquo;', 'lsquo;', 'lt;', 'macr;', 'mdash;', 'micro;', 'middot;', 'minus;', 'Mu;', 'mu;', 'nabla;', 'nbsp;', 'ndash;', 'ne;', 'ni;', 'not;', 'notin;', 'nsub;', 'Ntilde;', 'ntilde;', 'Nu;', 'nu;', 'Oacute;', 'oacute;', 'Ocirc;', 'ocirc;', 'OElig;', 'oelig;', 'Ograve;', 'ograve;', 'oline;', 'Omega;', 'omega;', 'Omicron;', 'omicron;', 'oplus;', 'or;', 'ordf;', 'ordm;', 'Oslash;', 'oslash;', 'Otilde;', 'otilde;', 'otimes;', 'Ouml;', 'ouml;', 'para;', 'part;', 'permil;', 'perp;', 'Phi;', 'phi;', 'Pi;', 'pi;', 'piv;', 'plusmn;', 'pound;', 'Prime;', 'prime;', 'prod;', 'prop;', 'Psi;', 'psi;', 'quot;', 'radic;', 'rang;', 'raquo;', 'rArr;', 'rarr;', 'rceil;', 'rdquo;', 'real;', 'reg;', 'rfloor;', 'Rho;', 'rho;', 'rlm;', 'rsaquo;', 'rsquo;', 'sbquo;', 'Scaron;', 'scaron;', 'sdot;', 'sect;', 'shy;', 'Sigma;', 'sigma;', 'sigmaf;', 'sim;', 'spades;', 'sub;', 'sube;', 'sum;', 'sup;', 'sup1;', 'sup2;', 'sup3;', 'supe;', 'szlig;', 'Tau;', 'tau;', 'there4;', 'Theta;', 'theta;', 'thetasym;', 'thinsp;', 'THORN;', 'thorn;', 'tilde;', 'times;', 'trade;', 'Uacute;', 'uacute;', 'uArr;', 'uarr;', 'Ucirc;', 'ucirc;', 'Ugrave;', 'ugrave;', 'uml;', 'upsih;', 'Upsilon;', 'upsilon;', 'Uuml;', 'uuml;', 'weierp;', 'Xi;', 'xi;', 'Yacute;', 'yacute;', 'yen;', 'Yuml;', 'yuml;', 'Zeta;', 'zeta;', 'zwj;', 'zwnj;']; return values.map(function(value){ return { caption: value, snippet: value, meta: "html entity", score: Number.MAX_VALUE }; }); }; }).call(HtmlCompletions.prototype); exports.HtmlCompletions = HtmlCompletions; }); ace.define("ace/mode/html",["require","exports","module","ace/lib/oop","ace/lib/lang","ace/mode/text","ace/mode/javascript","ace/mode/css","ace/mode/html_highlight_rules","ace/mode/behaviour/xml","ace/mode/folding/html","ace/mode/html_completions","ace/worker/worker_client"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var lang = require("../lib/lang"); var TextMode = require("./text").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var HtmlHighlightRules = require("./html_highlight_rules").HtmlHighlightRules; var XmlBehaviour = require("./behaviour/xml").XmlBehaviour; var HtmlFoldMode = require("./folding/html").FoldMode; var HtmlCompletions = require("./html_completions").HtmlCompletions; var WorkerClient = require("../worker/worker_client").WorkerClient; var voidElements = ["area", "base", "br", "col", "embed", "hr", "img", "input", "keygen", "link", "meta", "menuitem", "param", "source", "track", "wbr"]; var optionalEndTags = ["li", "dt", "dd", "p", "rt", "rp", "optgroup", "option", "colgroup", "td", "th"]; var Mode = function(options) { this.fragmentContext = options && options.fragmentContext; this.HighlightRules = HtmlHighlightRules; this.$behaviour = new XmlBehaviour(); this.$completer = new HtmlCompletions(); this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode }); this.foldingRules = new HtmlFoldMode(this.voidElements, lang.arrayToMap(optionalEndTags)); }; oop.inherits(Mode, TextMode); (function() { this.blockComment = {start: "<!--", end: "-->"}; this.voidElements = lang.arrayToMap(voidElements); this.getNextLineIndent = function(state, line, tab) { return this.$getIndent(line); }; this.checkOutdent = function(state, line, input) { return false; }; this.getCompletions = function(state, session, pos, prefix) { return this.$completer.getCompletions(state, session, pos, prefix); }; this.createWorker = function(session) { if (this.constructor != Mode) return; var worker = new WorkerClient(["ace"], "ace/mode/html_worker", "Worker"); worker.attachToDocument(session.getDocument()); if (this.fragmentContext) worker.call("setOptions", [{context: this.fragmentContext}]); worker.on("error", function(e) { session.setAnnotations(e.data); }); worker.on("terminate", function() { session.clearAnnotations(); }); return worker; }; this.$id = "ace/mode/html"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/folding/coffee",["require","exports","module","ace/lib/oop","ace/mode/folding/fold_mode","ace/range"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var BaseFoldMode = require("./fold_mode").FoldMode; var Range = require("../../range").Range; var FoldMode = exports.FoldMode = function() {}; oop.inherits(FoldMode, BaseFoldMode); (function() { this.getFoldWidgetRange = function(session, foldStyle, row) { var range = this.indentationBlock(session, row); if (range) return range; var re = /\S/; var line = session.getLine(row); var startLevel = line.search(re); if (startLevel == -1 || line[startLevel] != "#") return; var startColumn = line.length; var maxRow = session.getLength(); var startRow = row; var endRow = row; while (++row < maxRow) { line = session.getLine(row); var level = line.search(re); if (level == -1) continue; if (line[level] != "#") break; endRow = row; } if (endRow > startRow) { var endColumn = session.getLine(endRow).length; return new Range(startRow, startColumn, endRow, endColumn); } }; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); var indent = line.search(/\S/); var next = session.getLine(row + 1); var prev = session.getLine(row - 1); var prevIndent = prev.search(/\S/); var nextIndent = next.search(/\S/); if (indent == -1) { session.foldWidgets[row - 1] = prevIndent!= -1 && prevIndent < nextIndent ? "start" : ""; return ""; } if (prevIndent == -1) { if (indent == nextIndent && line[indent] == "#" && next[indent] == "#") { session.foldWidgets[row - 1] = ""; session.foldWidgets[row + 1] = ""; return "start"; } } else if (prevIndent == indent && line[indent] == "#" && prev[indent] == "#") { if (session.getLine(row - 2).search(/\S/) == -1) { session.foldWidgets[row - 1] = "start"; session.foldWidgets[row + 1] = ""; return ""; } } if (prevIndent!= -1 && prevIndent < indent) session.foldWidgets[row - 1] = "start"; else session.foldWidgets[row - 1] = ""; if (indent < nextIndent) return "start"; else return ""; }; }).call(FoldMode.prototype); }); ace.define("ace/mode/ruby",["require","exports","module","ace/lib/oop","ace/mode/text","ace/mode/ruby_highlight_rules","ace/mode/matching_brace_outdent","ace/range","ace/mode/behaviour/cstyle","ace/mode/folding/coffee"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var RubyHighlightRules = require("./ruby_highlight_rules").RubyHighlightRules; var MatchingBraceOutdent = require("./matching_brace_outdent").MatchingBraceOutdent; var Range = require("../range").Range; var CstyleBehaviour = require("./behaviour/cstyle").CstyleBehaviour; var FoldMode = require("./folding/coffee").FoldMode; var Mode = function() { this.HighlightRules = RubyHighlightRules; this.$outdent = new MatchingBraceOutdent(); this.$behaviour = new CstyleBehaviour(); this.foldingRules = new FoldMode(); }; oop.inherits(Mode, TextMode); (function() { this.lineCommentStart = "#"; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var tokenizedLine = this.getTokenizer().getLineTokens(line, state); var tokens = tokenizedLine.tokens; if (tokens.length && tokens[tokens.length-1].type == "comment") { return indent; } if (state == "start") { var match = line.match(/^.*[\{\(\[]\s*$/); var startingClassOrMethod = line.match(/^\s*(class|def|module)\s.*$/); var startingDoBlock = line.match(/.*do(\s*|\s+\|.*\|\s*)$/); var startingConditional = line.match(/^\s*(if|else|when)\s*/) if (match || startingClassOrMethod || startingDoBlock || startingConditional) { indent += tab; } } return indent; }; this.checkOutdent = function(state, line, input) { return /^\s+(end|else)$/.test(line + input) || this.$outdent.checkOutdent(line, input); }; this.autoOutdent = function(state, session, row) { var line = session.getLine(row); if (/}/.test(line)) return this.$outdent.autoOutdent(session, row); var indent = this.$getIndent(line); var prevLine = session.getLine(row - 1); var prevIndent = this.$getIndent(prevLine); var tab = session.getTabString(); if (prevIndent.length <= indent.length) { if (indent.slice(-tab.length) == tab) session.remove(new Range(row, indent.length-tab.length, row, indent.length)); } }; this.$id = "ace/mode/ruby"; }).call(Mode.prototype); exports.Mode = Mode; }); ace.define("ace/mode/html_ruby",["require","exports","module","ace/lib/oop","ace/mode/html_ruby_highlight_rules","ace/mode/html","ace/mode/javascript","ace/mode/css","ace/mode/ruby"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var HtmlRubyHighlightRules = require("./html_ruby_highlight_rules").HtmlRubyHighlightRules; var HtmlMode = require("./html").Mode; var JavaScriptMode = require("./javascript").Mode; var CssMode = require("./css").Mode; var RubyMode = require("./ruby").Mode; var Mode = function() { HtmlMode.call(this); this.HighlightRules = HtmlRubyHighlightRules; this.createModeDelegates({ "js-": JavaScriptMode, "css-": CssMode, "ruby-": RubyMode }); }; oop.inherits(Mode, HtmlMode); (function() { this.$id = "ace/mode/html_ruby"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace/mode-jsoniq.js
2,956
ace.define("ace/mode/xquery/jsoniq_lexer",["require","exports","module"], function(require, exports, module) { module.exports = (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({ 1:[function(_dereq_,module,exports){ var JSONiqTokenizer = exports.JSONiqTokenizer = function JSONiqTokenizer(string, parsingEventHandler) { init(string, parsingEventHandler); var self = this; this.ParseException = function(b, e, s, o, x) { var begin = b, end = e, state = s, offending = o, expected = x; this.getBegin = function() {return begin;}; this.getEnd = function() {return end;}; this.getState = function() {return state;}; this.getExpected = function() {return expected;}; this.getOffending = function() {return offending;}; this.getMessage = function() { return offending < 0 ? "lexical analysis failed" : "syntax error"; }; }; function init(string, parsingEventHandler) { eventHandler = parsingEventHandler; input = string; size = string.length; reset(0, 0, 0); } this.getInput = function() { return input; }; function reset(l, b, e) { b0 = b; e0 = b; l1 = l; b1 = b; e1 = e; end = e; eventHandler.reset(input); } this.getOffendingToken = function(e) { var o = e.getOffending(); return o >= 0 ? JSONiqTokenizer.TOKEN[o] : null; }; this.getExpectedTokenSet = function(e) { var expected; if (e.getExpected() < 0) { expected = JSONiqTokenizer.getTokenSet(- e.getState()); } else { expected = [JSONiqTokenizer.TOKEN[e.getExpected()]]; } return expected; }; this.getErrorMessage = function(e) { var tokenSet = this.getExpectedTokenSet(e); var found = this.getOffendingToken(e); var prefix = input.substring(0, e.getBegin()); var lines = prefix.split("\n"); var line = lines.length; var column = lines[line - 1].length + 1; var size = e.getEnd() - e.getBegin(); return e.getMessage() + (found == null ? "" : ", found " + found) + "\nwhile expecting " + (tokenSet.length == 1 ? tokenSet[0] : ("[" + tokenSet.join(", ") + "]")) + "\n" + (size == 0 || found != null ? "" : "after successfully scanning " + size + " characters beginning ") + "at line " + line + ", column " + column + ":\n..." + input.substring(e.getBegin(), Math.min(input.length, e.getBegin() + 64)) + "..."; }; this.parse_start = function() { eventHandler.startNonterminal("start", e0); lookahead1W(14); // ModuleDecl | Annotation | OptionDecl | Operator | Variable | Tag | AttrTest | switch (l1) { case 58: // '<![CDATA[' shift(58); // '<![CDATA[' break; case 57: // '<!--' shift(57); // '<!--' break; case 59: // '<?' shift(59); // '<?' break; case 43: // '(#' shift(43); // '(#' break; case 45: // '(:~' shift(45); // '(:~' break; case 44: // '(:' shift(44); // '(:' break; case 37: // '"' shift(37); // '"' break; case 41: // "'" shift(41); // "'" break; case 277: // '}' shift(277); // '}' break; case 274: // '{' shift(274); // '{' break; case 42: // '(' shift(42); // '(' break; case 46: // ')' shift(46); // ')' break; case 52: // '/' shift(52); // '/' break; case 65: // '[' shift(65); // '[' break; case 66: // ']' shift(66); // ']' break; case 49: // ',' shift(49); // ',' break; case 51: // '.' shift(51); // '.' break; case 56: // ';' shift(56); // ';' break; case 54: // ':' shift(54); // ':' break; case 36: // '!' shift(36); // '!' break; case 276: // '|' shift(276); // '|' break; case 40: // '$$' shift(40); // '$$' break; case 5: // Annotation shift(5); // Annotation break; case 4: // ModuleDecl shift(4); // ModuleDecl break; case 6: // OptionDecl shift(6); // OptionDecl break; case 15: // AttrTest shift(15); // AttrTest break; case 16: // Wildcard shift(16); // Wildcard break; case 18: // IntegerLiteral shift(18); // IntegerLiteral break; case 19: // DecimalLiteral shift(19); // DecimalLiteral break; case 20: // DoubleLiteral shift(20); // DoubleLiteral break; case 8: // Variable shift(8); // Variable break; case 9: // Tag shift(9); // Tag break; case 7: // Operator shift(7); // Operator break; case 35: // EOF shift(35); // EOF break; default: parse_EQName(); } eventHandler.endNonterminal("start", e0); }; this.parse_StartTag = function() { eventHandler.startNonterminal("StartTag", e0); lookahead1W(8); // QName | S^WS | EOF | '"' | "'" | '/>' | '=' | '>' switch (l1) { case 61: // '>' shift(61); // '>' break; case 53: // '/>' shift(53); // '/>' break; case 29: // QName shift(29); // QName break; case 60: // '=' shift(60); // '=' break; case 37: // '"' shift(37); // '"' break; case 41: // "'" shift(41); // "'" break; default: shift(35); // EOF } eventHandler.endNonterminal("StartTag", e0); }; this.parse_TagContent = function() { eventHandler.startNonterminal("TagContent", e0); lookahead1(11); // Tag | EndTag | PredefinedEntityRef | ElementContentChar | CharRef | EOF | switch (l1) { case 25: // ElementContentChar shift(25); // ElementContentChar break; case 9: // Tag shift(9); // Tag break; case 10: // EndTag shift(10); // EndTag break; case 58: // '<![CDATA[' shift(58); // '<![CDATA[' break; case 57: // '<!--' shift(57); // '<!--' break; case 21: // PredefinedEntityRef shift(21); // PredefinedEntityRef break; case 31: // CharRef shift(31); // CharRef break; case 275: // '{{' shift(275); // '{{' break; case 278: // '}}' shift(278); // '}}' break; case 274: // '{' shift(274); // '{' break; default: shift(35); // EOF } eventHandler.endNonterminal("TagContent", e0); }; this.parse_AposAttr = function() { eventHandler.startNonterminal("AposAttr", e0); lookahead1(10); // PredefinedEntityRef | EscapeApos | AposAttrContentChar | CharRef | EOF | "'" | switch (l1) { case 23: // EscapeApos shift(23); // EscapeApos break; case 27: // AposAttrContentChar shift(27); // AposAttrContentChar break; case 21: // PredefinedEntityRef shift(21); // PredefinedEntityRef break; case 31: // CharRef shift(31); // CharRef break; case 275: // '{{' shift(275); // '{{' break; case 278: // '}}' shift(278); // '}}' break; case 274: // '{' shift(274); // '{' break; case 41: // "'" shift(41); // "'" break; default: shift(35); // EOF } eventHandler.endNonterminal("AposAttr", e0); }; this.parse_QuotAttr = function() { eventHandler.startNonterminal("QuotAttr", e0); lookahead1(9); // PredefinedEntityRef | EscapeQuot | QuotAttrContentChar | CharRef | EOF | '"' | switch (l1) { case 22: // EscapeQuot shift(22); // EscapeQuot break; case 26: // QuotAttrContentChar shift(26); // QuotAttrContentChar break; case 21: // PredefinedEntityRef shift(21); // PredefinedEntityRef break; case 31: // CharRef shift(31); // CharRef break; case 275: // '{{' shift(275); // '{{' break; case 278: // '}}' shift(278); // '}}' break; case 274: // '{' shift(274); // '{' break; case 37: // '"' shift(37); // '"' break; default: shift(35); // EOF } eventHandler.endNonterminal("QuotAttr", e0); }; this.parse_CData = function() { eventHandler.startNonterminal("CData", e0); lookahead1(1); // CDataSectionContents | EOF | ']]>' switch (l1) { case 14: // CDataSectionContents shift(14); // CDataSectionContents break; case 67: // ']]>' shift(67); // ']]>' break; default: shift(35); // EOF } eventHandler.endNonterminal("CData", e0); }; this.parse_XMLComment = function() { eventHandler.startNonterminal("XMLComment", e0); lookahead1(0); // DirCommentContents | EOF | '-->' switch (l1) { case 12: // DirCommentContents shift(12); // DirCommentContents break; case 50: // '-->' shift(50); // '-->' break; default: shift(35); // EOF } eventHandler.endNonterminal("XMLComment", e0); }; this.parse_PI = function() { eventHandler.startNonterminal("PI", e0); lookahead1(3); // DirPIContents | EOF | '?' | '?>' switch (l1) { case 13: // DirPIContents shift(13); // DirPIContents break; case 62: // '?' shift(62); // '?' break; case 63: // '?>' shift(63); // '?>' break; default: shift(35); // EOF } eventHandler.endNonterminal("PI", e0); }; this.parse_Pragma = function() { eventHandler.startNonterminal("Pragma", e0); lookahead1(2); // PragmaContents | EOF | '#' | '#)' switch (l1) { case 11: // PragmaContents shift(11); // PragmaContents break; case 38: // '#' shift(38); // '#' break; case 39: // '#)' shift(39); // '#)' break; default: shift(35); // EOF } eventHandler.endNonterminal("Pragma", e0); }; this.parse_Comment = function() { eventHandler.startNonterminal("Comment", e0); lookahead1(4); // CommentContents | EOF | '(:' | ':)' switch (l1) { case 55: // ':)' shift(55); // ':)' break; case 44: // '(:' shift(44); // '(:' break; case 32: // CommentContents shift(32); // CommentContents break; default: shift(35); // EOF } eventHandler.endNonterminal("Comment", e0); }; this.parse_CommentDoc = function() { eventHandler.startNonterminal("CommentDoc", e0); lookahead1(6); // DocTag | DocCommentContents | EOF | '(:' | ':)' switch (l1) { case 33: // DocTag shift(33); // DocTag break; case 34: // DocCommentContents shift(34); // DocCommentContents break; case 55: // ':)' shift(55); // ':)' break; case 44: // '(:' shift(44); // '(:' break; default: shift(35); // EOF } eventHandler.endNonterminal("CommentDoc", e0); }; this.parse_QuotString = function() { eventHandler.startNonterminal("QuotString", e0); lookahead1(5); // JSONChar | JSONCharRef | JSONPredefinedCharRef | EOF | '"' switch (l1) { case 3: // JSONPredefinedCharRef shift(3); // JSONPredefinedCharRef break; case 2: // JSONCharRef shift(2); // JSONCharRef break; case 1: // JSONChar shift(1); // JSONChar break; case 37: // '"' shift(37); // '"' break; default: shift(35); // EOF } eventHandler.endNonterminal("QuotString", e0); }; this.parse_AposString = function() { eventHandler.startNonterminal("AposString", e0); lookahead1(7); // PredefinedEntityRef | EscapeApos | AposChar | CharRef | EOF | "'" switch (l1) { case 21: // PredefinedEntityRef shift(21); // PredefinedEntityRef break; case 31: // CharRef shift(31); // CharRef break; case 23: // EscapeApos shift(23); // EscapeApos break; case 24: // AposChar shift(24); // AposChar break; case 41: // "'" shift(41); // "'" break; default: shift(35); // EOF } eventHandler.endNonterminal("AposString", e0); }; this.parse_Prefix = function() { eventHandler.startNonterminal("Prefix", e0); lookahead1W(13); // NCName^Token | S^WS | 'after' | 'allowing' | 'ancestor' | 'ancestor-or-self' | whitespace(); parse_NCName(); eventHandler.endNonterminal("Prefix", e0); }; this.parse__EQName = function() { eventHandler.startNonterminal("_EQName", e0); lookahead1W(12); // EQName^Token | S^WS | 'after' | 'allowing' | 'ancestor' | 'ancestor-or-self' | whitespace(); parse_EQName(); eventHandler.endNonterminal("_EQName", e0); }; function parse_EQName() { eventHandler.startNonterminal("EQName", e0); switch (l1) { case 80: // 'attribute' shift(80); // 'attribute' break; case 94: // 'comment' shift(94); // 'comment' break; case 118: // 'document-node' shift(118); // 'document-node' break; case 119: // 'element' shift(119); // 'element' break; case 122: // 'empty-sequence' shift(122); // 'empty-sequence' break; case 143: // 'function' shift(143); // 'function' break; case 150: // 'if' shift(150); // 'if' break; case 163: // 'item' shift(163); // 'item' break; case 183: // 'namespace-node' shift(183); // 'namespace-node' break; case 189: // 'node' shift(189); // 'node' break; case 214: // 'processing-instruction' shift(214); // 'processing-instruction' break; case 224: // 'schema-attribute' shift(224); // 'schema-attribute' break; case 225: // 'schema-element' shift(225); // 'schema-element' break; case 241: // 'switch' shift(241); // 'switch' break; case 242: // 'text' shift(242); // 'text' break; case 251: // 'typeswitch' shift(251); // 'typeswitch' break; default: parse_FunctionName(); } eventHandler.endNonterminal("EQName", e0); } function parse_FunctionName() { eventHandler.startNonterminal("FunctionName", e0); switch (l1) { case 17: // EQName^Token shift(17); // EQName^Token break; case 68: // 'after' shift(68); // 'after' break; case 71: // 'ancestor' shift(71); // 'ancestor' break; case 72: // 'ancestor-or-self' shift(72); // 'ancestor-or-self' break; case 73: // 'and' shift(73); // 'and' break; case 77: // 'as' shift(77); // 'as' break; case 78: // 'ascending' shift(78); // 'ascending' break; case 82: // 'before' shift(82); // 'before' break; case 86: // 'case' shift(86); // 'case' break; case 87: // 'cast' shift(87); // 'cast' break; case 88: // 'castable' shift(88); // 'castable' break; case 91: // 'child' shift(91); // 'child' break; case 92: // 'collation' shift(92); // 'collation' break; case 101: // 'copy' shift(101); // 'copy' break; case 103: // 'count' shift(103); // 'count' break; case 106: // 'declare' shift(106); // 'declare' break; case 107: // 'default' shift(107); // 'default' break; case 108: // 'delete' shift(108); // 'delete' break; case 109: // 'descendant' shift(109); // 'descendant' break; case 110: // 'descendant-or-self' shift(110); // 'descendant-or-self' break; case 111: // 'descending' shift(111); // 'descending' break; case 116: // 'div' shift(116); // 'div' break; case 117: // 'document' shift(117); // 'document' break; case 120: // 'else' shift(120); // 'else' break; case 121: // 'empty' shift(121); // 'empty' break; case 124: // 'end' shift(124); // 'end' break; case 126: // 'eq' shift(126); // 'eq' break; case 127: // 'every' shift(127); // 'every' break; case 129: // 'except' shift(129); // 'except' break; case 132: // 'first' shift(132); // 'first' break; case 133: // 'following' shift(133); // 'following' break; case 134: // 'following-sibling' shift(134); // 'following-sibling' break; case 135: // 'for' shift(135); // 'for' break; case 144: // 'ge' shift(144); // 'ge' break; case 146: // 'group' shift(146); // 'group' break; case 148: // 'gt' shift(148); // 'gt' break; case 149: // 'idiv' shift(149); // 'idiv' break; case 151: // 'import' shift(151); // 'import' break; case 157: // 'insert' shift(157); // 'insert' break; case 158: // 'instance' shift(158); // 'instance' break; case 160: // 'intersect' shift(160); // 'intersect' break; case 161: // 'into' shift(161); // 'into' break; case 162: // 'is' shift(162); // 'is' break; case 168: // 'last' shift(168); // 'last' break; case 170: // 'le' shift(170); // 'le' break; case 172: // 'let' shift(172); // 'let' break; case 176: // 'lt' shift(176); // 'lt' break; case 178: // 'mod' shift(178); // 'mod' break; case 179: // 'modify' shift(179); // 'modify' break; case 180: // 'module' shift(180); // 'module' break; case 182: // 'namespace' shift(182); // 'namespace' break; case 184: // 'ne' shift(184); // 'ne' break; case 196: // 'only' shift(196); // 'only' break; case 198: // 'or' shift(198); // 'or' break; case 199: // 'order' shift(199); // 'order' break; case 200: // 'ordered' shift(200); // 'ordered' break; case 204: // 'parent' shift(204); // 'parent' break; case 210: // 'preceding' shift(210); // 'preceding' break; case 211: // 'preceding-sibling' shift(211); // 'preceding-sibling' break; case 216: // 'rename' shift(216); // 'rename' break; case 217: // 'replace' shift(217); // 'replace' break; case 218: // 'return' shift(218); // 'return' break; case 222: // 'satisfies' shift(222); // 'satisfies' break; case 227: // 'self' shift(227); // 'self' break; case 233: // 'some' shift(233); // 'some' break; case 234: // 'stable' shift(234); // 'stable' break; case 235: // 'start' shift(235); // 'start' break; case 246: // 'to' shift(246); // 'to' break; case 247: // 'treat' shift(247); // 'treat' break; case 248: // 'try' shift(248); // 'try' break; case 252: // 'union' shift(252); // 'union' break; case 254: // 'unordered' shift(254); // 'unordered' break; case 258: // 'validate' shift(258); // 'validate' break; case 264: // 'where' shift(264); // 'where' break; case 268: // 'with' shift(268); // 'with' break; case 272: // 'xquery' shift(272); // 'xquery' break; case 70: // 'allowing' shift(70); // 'allowing' break; case 79: // 'at' shift(79); // 'at' break; case 81: // 'base-uri' shift(81); // 'base-uri' break; case 83: // 'boundary-space' shift(83); // 'boundary-space' break; case 84: // 'break' shift(84); // 'break' break; case 89: // 'catch' shift(89); // 'catch' break; case 96: // 'construction' shift(96); // 'construction' break; case 99: // 'context' shift(99); // 'context' break; case 100: // 'continue' shift(100); // 'continue' break; case 102: // 'copy-namespaces' shift(102); // 'copy-namespaces' break; case 104: // 'decimal-format' shift(104); // 'decimal-format' break; case 123: // 'encoding' shift(123); // 'encoding' break; case 130: // 'exit' shift(130); // 'exit' break; case 131: // 'external' shift(131); // 'external' break; case 139: // 'ft-option' shift(139); // 'ft-option' break; case 152: // 'in' shift(152); // 'in' break; case 153: // 'index' shift(153); // 'index' break; case 159: // 'integrity' shift(159); // 'integrity' break; case 169: // 'lax' shift(169); // 'lax' break; case 190: // 'nodes' shift(190); // 'nodes' break; case 197: // 'option' shift(197); // 'option' break; case 201: // 'ordering' shift(201); // 'ordering' break; case 220: // 'revalidation' shift(220); // 'revalidation' break; case 223: // 'schema' shift(223); // 'schema' break; case 226: // 'score' shift(226); // 'score' break; case 232: // 'sliding' shift(232); // 'sliding' break; case 238: // 'strict' shift(238); // 'strict' break; case 249: // 'tumbling' shift(249); // 'tumbling' break; case 250: // 'type' shift(250); // 'type' break; case 255: // 'updating' shift(255); // 'updating' break; case 259: // 'value' shift(259); // 'value' break; case 260: // 'variable' shift(260); // 'variable' break; case 261: // 'version' shift(261); // 'version' break; case 265: // 'while' shift(265); // 'while' break; case 95: // 'constraint' shift(95); // 'constraint' break; case 174: // 'loop' shift(174); // 'loop' break; default: shift(219); // 'returning' } eventHandler.endNonterminal("FunctionName", e0); } function parse_NCName() { eventHandler.startNonterminal("NCName", e0); switch (l1) { case 28: // NCName^Token shift(28); // NCName^Token break; case 68: // 'after' shift(68); // 'after' break; case 73: // 'and' shift(73); // 'and' break; case 77: // 'as' shift(77); // 'as' break; case 78: // 'ascending' shift(78); // 'ascending' break; case 82: // 'before' shift(82); // 'before' break; case 86: // 'case' shift(86); // 'case' break; case 87: // 'cast' shift(87); // 'cast' break; case 88: // 'castable' shift(88); // 'castable' break; case 92: // 'collation' shift(92); // 'collation' break; case 103: // 'count' shift(103); // 'count' break; case 107: // 'default' shift(107); // 'default' break; case 111: // 'descending' shift(111); // 'descending' break; case 116: // 'div' shift(116); // 'div' break; case 120: // 'else' shift(120); // 'else' break; case 121: // 'empty' shift(121); // 'empty' break; case 124: // 'end' shift(124); // 'end' break; case 126: // 'eq' shift(126); // 'eq' break; case 129: // 'except' shift(129); // 'except' break; case 135: // 'for' shift(135); // 'for' break; case 144: // 'ge' shift(144); // 'ge' break; case 146: // 'group' shift(146); // 'group' break; case 148: // 'gt' shift(148); // 'gt' break; case 149: // 'idiv' shift(149); // 'idiv' break; case 158: // 'instance' shift(158); // 'instance' break; case 160: // 'intersect' shift(160); // 'intersect' break; case 161: // 'into' shift(161); // 'into' break; case 162: // 'is' shift(162); // 'is' break; case 170: // 'le' shift(170); // 'le' break; case 172: // 'let' shift(172); // 'let' break; case 176: // 'lt' shift(176); // 'lt' break; case 178: // 'mod' shift(178); // 'mod' break; case 179: // 'modify' shift(179); // 'modify' break; case 184: // 'ne' shift(184); // 'ne' break; case 196: // 'only' shift(196); // 'only' break; case 198: // 'or' shift(198); // 'or' break; case 199: // 'order' shift(199); // 'order' break; case 218: // 'return' shift(218); // 'return' break; case 222: // 'satisfies' shift(222); // 'satisfies' break; case 234: // 'stable' shift(234); // 'stable' break; case 235: // 'start' shift(235); // 'start' break; case 246: // 'to' shift(246); // 'to' break; case 247: // 'treat' shift(247); // 'treat' break; case 252: // 'union' shift(252); // 'union' break; case 264: // 'where' shift(264); // 'where' break; case 268: // 'with' shift(268); // 'with' break; case 71: // 'ancestor' shift(71); // 'ancestor' break; case 72: // 'ancestor-or-self' shift(72); // 'ancestor-or-self' break; case 80: // 'attribute' shift(80); // 'attribute' break; case 91: // 'child' shift(91); // 'child' break; case 94: // 'comment' shift(94); // 'comment' break; case 101: // 'copy' shift(101); // 'copy' break; case 106: // 'declare' shift(106); // 'declare' break; case 108: // 'delete' shift(108); // 'delete' break; case 109: // 'descendant' shift(109); // 'descendant' break; case 110: // 'descendant-or-self' shift(110); // 'descendant-or-self' break; case 117: // 'document' shift(117); // 'document' break; case 118: // 'document-node' shift(118); // 'document-node' break; case 119: // 'element' shift(119); // 'element' break; case 122: // 'empty-sequence' shift(122); // 'empty-sequence' break; case 127: // 'every' shift(127); // 'every' break; case 132: // 'first' shift(132); // 'first' break; case 133: // 'following' shift(133); // 'following' break; case 134: // 'following-sibling' shift(134); // 'following-sibling' break; case 143: // 'function' shift(143); // 'function' break; case 150: // 'if' shift(150); // 'if' break; case 151: // 'import' shift(151); // 'import' break; case 157: // 'insert' shift(157); // 'insert' break; case 163: // 'item' shift(163); // 'item' break; case 168: // 'last' shift(168); // 'last' break; case 180: // 'module' shift(180); // 'module' break; case 182: // 'namespace' shift(182); // 'namespace' break; case 183: // 'namespace-node' shift(183); // 'namespace-node' break; case 189: // 'node' shift(189); // 'node' break; case 200: // 'ordered' shift(200); // 'ordered' break; case 204: // 'parent' shift(204); // 'parent' break; case 210: // 'preceding' shift(210); // 'preceding' break; case 211: // 'preceding-sibling' shift(211); // 'preceding-sibling' break; case 214: // 'processing-instruction' shift(214); // 'processing-instruction' break; case 216: // 'rename' shift(216); // 'rename' break; case 217: // 'replace' shift(217); // 'replace' break; case 224: // 'schema-attribute' shift(224); // 'schema-attribute' break; case 225: // 'schema-element' shift(225); // 'schema-element' break; case 227: // 'self' shift(227); // 'self' break; case 233: // 'some' shift(233); // 'some' break; case 241: // 'switch' shift(241); // 'switch' break; case 242: // 'text' shift(242); // 'text' break; case 248: // 'try' shift(248); // 'try' break; case 251: // 'typeswitch' shift(251); // 'typeswitch' break; case 254: // 'unordered' shift(254); // 'unordered' break; case 258: // 'validate' shift(258); // 'validate' break; case 260: // 'variable' shift(260); // 'variable' break; case 272: // 'xquery' shift(272); // 'xquery' break; case 70: // 'allowing' shift(70); // 'allowing' break; case 79: // 'at' shift(79); // 'at' break; case 81: // 'base-uri' shift(81); // 'base-uri' break; case 83: // 'boundary-space' shift(83); // 'boundary-space' break; case 84: // 'break' shift(84); // 'break' break; case 89: // 'catch' shift(89); // 'catch' break; case 96: // 'construction' shift(96); // 'construction' break; case 99: // 'context' shift(99); // 'context' break; case 100: // 'continue' shift(100); // 'continue' break; case 102: // 'copy-namespaces' shift(102); // 'copy-namespaces' break; case 104: // 'decimal-format' shift(104); // 'decimal-format' break; case 123: // 'encoding' shift(123); // 'encoding' break; case 130: // 'exit' shift(130); // 'exit' break; case 131: // 'external' shift(131); // 'external' break; case 139: // 'ft-option' shift(139); // 'ft-option' break; case 152: // 'in' shift(152); // 'in' break; case 153: // 'index' shift(153); // 'index' break; case 159: // 'integrity' shift(159); // 'integrity' break; case 169: // 'lax' shift(169); // 'lax' break; case 190: // 'nodes' shift(190); // 'nodes' break; case 197: // 'option' shift(197); // 'option' break; case 201: // 'ordering' shift(201); // 'ordering' break; case 220: // 'revalidation' shift(220); // 'revalidation' break; case 223: // 'schema' shift(223); // 'schema' break; case 226: // 'score' shift(226); // 'score' break; case 232: // 'sliding' shift(232); // 'sliding' break; case 238: // 'strict' shift(238); // 'strict' break; case 249: // 'tumbling' shift(249); // 'tumbling' break; case 250: // 'type' shift(250); // 'type' break; case 255: // 'updating' shift(255); // 'updating' break; case 259: // 'value' shift(259); // 'value' break; case 261: // 'version' shift(261); // 'version' break; case 265: // 'while' shift(265); // 'while' break; case 95: // 'constraint' shift(95); // 'constraint' break; case 174: // 'loop' shift(174); // 'loop' break; default: shift(219); // 'returning' } eventHandler.endNonterminal("NCName", e0); } function shift(t) { if (l1 == t) { whitespace(); eventHandler.terminal(JSONiqTokenizer.TOKEN[l1], b1, e1 > size ? size : e1); b0 = b1; e0 = e1; l1 = 0; } else { error(b1, e1, 0, l1, t); } } function whitespace() { if (e0 != b1) { b0 = e0; e0 = b1; eventHandler.whitespace(b0, e0); } } function matchW(set) { var code; for (;;) { code = match(set); if (code != 30) // S^WS { break; } } return code; } function lookahead1W(set) { if (l1 == 0) { l1 = matchW(set); b1 = begin; e1 = end; } } function lookahead1(set) { if (l1 == 0) { l1 = match(set); b1 = begin; e1 = end; } } function error(b, e, s, l, t) { throw new self.ParseException(b, e, s, l, t); } var lk, b0, e0; var l1, b1, e1; var eventHandler; var input; var size; var begin; var end; function match(tokenSetId) { var nonbmp = false; begin = end; var current = end; var result = JSONiqTokenizer.INITIAL[tokenSetId]; var state = 0; for (var code = result & 4095; code != 0; ) { var charclass; var c0 = current < size ? input.charCodeAt(current) : 0; ++current; if (c0 < 0x80) { charclass = JSONiqTokenizer.MAP0[c0]; } else if (c0 < 0xd800) { var c1 = c0 >> 4; charclass = JSONiqTokenizer.MAP1[(c0 & 15) + JSONiqTokenizer.MAP1[(c1 & 31) + JSONiqTokenizer.MAP1[c1 >> 5]]]; } else { if (c0 < 0xdc00) { var c1 = current < size ? input.charCodeAt(current) : 0; if (c1 >= 0xdc00 && c1 < 0xe000) { ++current; c0 = ((c0 & 0x3ff) << 10) + (c1 & 0x3ff) + 0x10000; nonbmp = true; } } var lo = 0, hi = 5; for (var m = 3; ; m = (hi + lo) >> 1) { if (JSONiqTokenizer.MAP2[m] > c0) hi = m - 1; else if (JSONiqTokenizer.MAP2[6 + m] < c0) lo = m + 1; else {charclass = JSONiqTokenizer.MAP2[12 + m]; break;} if (lo > hi) {charclass = 0; break;} } } state = code; var i0 = (charclass << 12) + code - 1; code = JSONiqTokenizer.TRANSITION[(i0 & 15) + JSONiqTokenizer.TRANSITION[i0 >> 4]]; if (code > 4095) { result = code; code &= 4095; end = current; } } result >>= 12; if (result == 0) { end = current - 1; var c1 = end < size ? input.charCodeAt(end) : 0; if (c1 >= 0xdc00 && c1 < 0xe000) --end; return error(begin, end, state, -1, -1); } if (nonbmp) { for (var i = result >> 9; i > 0; --i) { --end; var c1 = end < size ? input.charCodeAt(end) : 0; if (c1 >= 0xdc00 && c1 < 0xe000) --end; } } else { end -= result >> 9; } return (result & 511) - 1; } } JSONiqTokenizer.getTokenSet = function(tokenSetId) { var set = []; var s = tokenSetId < 0 ? - tokenSetId : INITIAL[tokenSetId] & 4095; for (var i = 0; i < 279; i += 32) { var j = i; var i0 = (i >> 5) * 2066 + s - 1; var i1 = i0 >> 2; var i2 = i1 >> 2; var f = JSONiqTokenizer.EXPECTED[(i0 & 3) + JSONiqTokenizer.EXPECTED[(i1 & 3) + JSONiqTokenizer.EXPECTED[(i2 & 3) + JSONiqTokenizer.EXPECTED[i2 >> 2]]]]; for ( ; f != 0; f >>>= 1, ++j) { if ((f & 1) != 0) { set.push(JSONiqTokenizer.TOKEN[j]); } } } return set; }; JSONiqTokenizer.MAP0 = [ 67, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 27, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 31, 31, 33, 31, 31, 31, 31, 31, 31, 34, 35, 36, 37, 31, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 31, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 31, 62, 63, 64, 65, 37 ]; JSONiqTokenizer.MAP1 = [ 108, 124, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 156, 181, 181, 181, 181, 181, 214, 215, 213, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 214, 247, 261, 277, 293, 309, 347, 363, 379, 416, 416, 416, 408, 331, 323, 331, 323, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 433, 433, 433, 433, 433, 433, 433, 316, 331, 331, 331, 331, 331, 331, 331, 331, 394, 416, 416, 417, 415, 416, 416, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 416, 330, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 331, 416, 67, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 18, 18, 18, 18, 18, 18, 18, 18, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 27, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 37, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 31, 32, 31, 31, 33, 31, 31, 31, 31, 31, 31, 34, 35, 36, 37, 31, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 31, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 31, 62, 63, 64, 65, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 31, 31, 37, 37, 37, 37, 37, 37, 37, 66, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 37, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66, 66 ]; JSONiqTokenizer.MAP2 = [ 57344, 63744, 64976, 65008, 65536, 983040, 63743, 64975, 65007, 65533, 983039, 1114111, 37, 31, 37, 31, 31, 37 ]; JSONiqTokenizer.INITIAL = [ 1, 2, 49155, 57348, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 ]; JSONiqTokenizer.TRANSITION = [ 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 17408, 19288, 17439, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 22126, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17672, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 19469, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 36919, 18234, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18419, 18432, 18304, 18448, 18485, 18523, 18553, 18583, 18599, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 18825, 18841, 18871, 18906, 18944, 18960, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19074, 36169, 17439, 36866, 17466, 36890, 36866, 22314, 19105, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 22126, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17672, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 19469, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 36919, 18234, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18419, 18432, 18304, 18448, 18485, 18523, 18553, 18583, 18599, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 18825, 18841, 18871, 18906, 18944, 18960, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22182, 19288, 19121, 36866, 17466, 18345, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19273, 19552, 19304, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19332, 17423, 19363, 36866, 17466, 17537, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 18614, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 19391, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 19427, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36154, 19288, 19457, 36866, 17466, 17740, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22780, 19288, 19457, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22375, 22197, 18469, 36866, 17466, 36890, 36866, 21991, 24018, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 21331, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 19485, 19501, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19537, 22390, 19568, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19596, 19611, 19457, 36866, 17466, 36890, 36866, 18246, 19627, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22242, 20553, 19457, 36866, 17466, 36890, 36866, 18648, 30477, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36472, 19288, 19457, 36866, 17466, 17809, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 21770, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 19643, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 19672, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 20538, 19288, 19457, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 17975, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22345, 19288, 19457, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19726, 19742, 21529, 24035, 23112, 26225, 23511, 27749, 27397, 24035, 34360, 24035, 24036, 23114, 35166, 23114, 23114, 19758, 23511, 35247, 23511, 23511, 28447, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 24254, 19821, 23511, 23511, 23511, 23511, 23512, 19441, 36539, 24035, 24035, 24035, 24035, 19846, 19869, 23114, 23114, 23114, 28618, 32187, 19892, 23511, 23511, 23511, 34585, 20402, 36647, 24035, 24035, 24036, 23114, 33757, 23114, 23114, 23029, 20271, 23511, 27070, 23511, 23511, 30562, 24035, 24035, 29274, 26576, 23114, 23114, 31118, 23036, 29695, 23511, 23511, 32431, 23634, 30821, 24035, 23110, 19913, 23114, 23467, 31261, 23261, 34299, 19932, 24035, 32609, 19965, 35389, 19984, 27689, 19830, 29391, 29337, 20041, 22643, 35619, 33728, 20062, 20121, 20166, 35100, 26145, 20211, 23008, 19876, 20208, 20227, 25670, 20132, 26578, 27685, 20141, 20243, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36094, 19288, 19457, 36866, 17466, 21724, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22735, 19552, 20287, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22750, 19288, 21529, 24035, 23112, 28056, 23511, 29483, 28756, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 20327, 23511, 23511, 23511, 23511, 31156, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 24254, 20371, 23511, 23511, 23511, 23511, 27443, 20395, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 29457, 29700, 23511, 23511, 23511, 23511, 33444, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 28350, 20421, 23511, 23511, 23511, 23511, 25645, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 20447, 20475, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 20523, 22257, 20569, 20783, 21715, 17603, 20699, 20837, 20614, 20630, 21149, 20670, 21405, 17486, 17509, 17525, 18373, 19179, 20695, 20716, 20732, 20755, 19194, 18042, 21641, 20592, 20779, 20598, 21412, 17470, 17591, 20896, 17468, 17619, 20799, 20700, 21031, 20744, 20699, 20828, 18075, 21259, 20581, 20853, 18048, 20868, 20884, 17756, 17784, 17800, 17825, 17854, 21171, 21200, 20931, 20947, 21378, 20955, 20971, 18086, 20645, 21002, 20986, 18178, 17960, 18012, 18381, 18064, 29176, 21044, 21438, 21018, 21122, 21393, 21060, 21844, 21094, 20654, 17493, 18150, 18166, 18214, 25967, 20763, 21799, 21110, 21830, 21138, 21246, 21301, 18336, 18361, 21165, 21187, 20812, 21216, 21232, 21287, 21317, 18553, 21347, 21363, 21428, 21454, 21271, 21483, 21499, 21515, 21575, 21467, 18712, 21591, 21633, 21078, 18189, 18198, 20679, 21657, 21701, 21074, 21687, 21740, 21756, 21786, 21815, 21860, 21876, 21892, 21946, 21962, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36457, 19288, 19457, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 36813, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 21981, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 22151, 22007, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 27898, 17884, 18890, 17906, 17928, 22042, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 22070, 22112, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 22142, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36109, 19288, 18469, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22167, 19288, 19457, 36866, 17466, 17768, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22227, 36487, 22273, 36866, 17466, 36890, 36866, 19316, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18749, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 22304, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 19580, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22330, 19089, 19457, 36866, 17466, 18721, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22765, 19347, 19457, 36866, 17466, 36890, 36866, 18114, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 24035, 23112, 32618, 23511, 29483, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 29116, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 27443, 22493, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34541, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 22839, 23511, 23511, 23511, 23511, 25645, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 32683, 22516, 23511, 23511, 23511, 22540, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 24035, 23112, 32618, 23511, 29483, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 29116, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 27443, 22493, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34564, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 22839, 23511, 23511, 23511, 23511, 25645, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 32683, 22516, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 24035, 23112, 32618, 23511, 29483, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 29908, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 27443, 22493, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34564, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 22839, 23511, 23511, 23511, 23511, 25645, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 32683, 22516, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 24035, 23112, 32618, 23511, 29483, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 29116, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 27443, 22561, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34564, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 22839, 23511, 23511, 23511, 23511, 25645, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 32683, 22516, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 24035, 23112, 23837, 23511, 29483, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22584, 23511, 23511, 23511, 23511, 29116, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 27443, 22493, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34564, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 22839, 23511, 23511, 23511, 23511, 25645, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 32683, 22516, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 24035, 23112, 32618, 23511, 31507, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 28306, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 23512, 24694, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 20271, 23511, 23511, 23511, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36442, 19288, 21605, 24035, 23112, 28137, 23511, 31507, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 28306, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 23512, 24694, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 20271, 23511, 23511, 23511, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 24035, 23112, 32618, 23511, 31507, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 28306, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 23512, 24694, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 20271, 23511, 23511, 23511, 23511, 31568, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22690, 19288, 19457, 36866, 17466, 36890, 36866, 21991, 27584, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 22659, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22360, 19552, 19457, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22675, 22811, 19457, 36866, 17466, 36890, 36866, 19133, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 22827, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36139, 19288, 19457, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36064, 19288, 22865, 22881, 32031, 22897, 22913, 22956, 29939, 24035, 24035, 24035, 23003, 23114, 23114, 23114, 23024, 22420, 23511, 23511, 23511, 23052, 29116, 23073, 29268, 24035, 25563, 26915, 23106, 23131, 23114, 23114, 23159, 23181, 23197, 23248, 23511, 23511, 23282, 23305, 22493, 32364, 24035, 33472, 30138, 26325, 31770, 33508, 27345, 33667, 23114, 23321, 23473, 23351, 35793, 36576, 23511, 23375, 22500, 24145, 24035, 29197, 20192, 24533, 23440, 23114, 19017, 23459, 22839, 23489, 23510, 23511, 33563, 23528, 32076, 25389, 24035, 26576, 23561, 23583, 23114, 32683, 22516, 23622, 23655, 23511, 23634, 35456, 37144, 23110, 23683, 34153, 20499, 32513, 25824, 23705, 24035, 24035, 23111, 23114, 19874, 27078, 33263, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 20507, 32241, 20150, 31862, 27464, 35108, 23727, 23007, 35895, 34953, 26578, 27685, 20141, 24569, 31691, 19787, 33967, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36427, 19552, 21605, 24035, 23112, 32618, 23511, 29483, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 29116, 19803, 24035, 24035, 24035, 27027, 26576, 23114, 23114, 23114, 31471, 23756, 22468, 23511, 23511, 23511, 34687, 23772, 22493, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34564, 23788, 24035, 24035, 24035, 21559, 23828, 23114, 23114, 23114, 25086, 22839, 23853, 23511, 23511, 23511, 23876, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 32683, 22516, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 31761, 23909, 23953, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36049, 19288, 21605, 30825, 23112, 23987, 23511, 24003, 31001, 27617, 24034, 24035, 24036, 24052, 24089, 23114, 23114, 22420, 24109, 24168, 23511, 23511, 29116, 24188, 27609, 20017, 29516, 24035, 26576, 24222, 19968, 23114, 24252, 33811, 22468, 24270, 33587, 23511, 24320, 27443, 22493, 24035, 24035, 24035, 24035, 24339, 23113, 23114, 23114, 23114, 28128, 28618, 29700, 23511, 23511, 23511, 28276, 34564, 20402, 24035, 24035, 32929, 24036, 23114, 23114, 23114, 24357, 23029, 22839, 23511, 23511, 23511, 24377, 25645, 24035, 34112, 24035, 26576, 23114, 26643, 23114, 32683, 22516, 23511, 25638, 23511, 23711, 24035, 24395, 27809, 23114, 24414, 20499, 24432, 30917, 23628, 24035, 30680, 23111, 23114, 30233, 27078, 25748, 24452, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 24475, 19829, 26577, 26597, 26154, 24519, 24556, 24596, 23007, 20046, 20132, 26578, 24634, 20141, 24569, 31691, 24679, 24727, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36412, 19288, 21605, 19943, 34861, 32618, 26027, 29483, 32016, 32050, 36233, 24776, 35574, 24801, 24819, 32671, 31289, 22420, 24868, 24886, 20087, 26849, 29116, 19803, 24035, 24035, 24035, 36228, 26576, 23114, 23114, 23114, 24981, 33811, 22468, 23511, 23511, 23511, 29028, 27443, 22493, 24923, 27965, 24035, 24035, 32797, 24946, 23443, 23114, 23114, 29636, 24997, 22849, 28252, 23511, 23511, 23511, 25042, 25110, 24035, 24035, 34085, 24036, 25133, 23114, 23114, 25152, 23029, 22839, 25169, 23511, 36764, 23511, 25645, 30403, 24035, 25186, 26576, 31806, 24093, 25212, 32683, 22516, 32713, 26245, 34293, 23634, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 24035, 32406, 23111, 23114, 28676, 30944, 27689, 25234, 24035, 23112, 19872, 37063, 23266, 24036, 23114, 30243, 20379, 26100, 29218, 20211, 30105, 25257, 25284, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 24834, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36034, 19288, 21671, 25314, 25072, 25330, 25346, 25362, 29939, 29951, 35288, 29984, 23812, 27216, 25405, 25424, 30456, 22584, 26292, 25461, 25480, 31592, 29116, 25516, 34963, 25545, 27007, 25579, 33937, 25614, 25661, 25686, 34872, 25702, 25718, 25734, 25769, 25795, 25811, 25840, 22493, 26533, 25856, 24035, 25876, 30763, 27481, 25909, 23114, 28987, 25936, 25954, 29700, 25983, 23511, 31412, 26043, 26063, 22568, 29241, 29592, 26116, 31216, 35383, 26170, 34783, 26194, 26221, 22839, 26241, 26261, 22477, 26283, 26308, 27306, 31035, 24655, 26576, 29854, 33386, 26341, 32683, 22516, 32153, 30926, 26361, 19996, 26381, 35463, 26397, 26424, 34646, 26478, 35605, 31386, 26494, 35567, 31964, 22940, 23689, 25218, 30309, 32289, 19830, 33605, 23112, 32109, 27733, 27084, 24496, 35886, 35221, 26525, 36602, 26549, 26558, 26574, 26594, 26613, 26629, 26666, 26700, 26578, 27685, 23740, 24285, 31691, 26733, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36397, 19552, 18991, 25887, 28117, 32618, 26776, 29483, 29939, 26802, 24035, 24035, 24036, 28664, 23114, 23114, 23114, 22420, 30297, 23511, 23511, 23511, 29116, 19803, 24035, 24035, 24035, 25559, 26576, 23114, 23114, 23114, 30525, 33811, 22468, 23511, 23511, 23511, 28725, 27443, 22493, 24035, 24035, 27249, 24035, 24035, 23113, 23114, 23114, 26827, 23114, 28618, 29700, 23511, 23511, 26845, 23511, 34564, 20402, 24035, 24035, 26979, 24036, 23114, 23114, 23114, 24974, 23029, 22839, 23511, 23511, 23511, 26865, 25645, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 32683, 22516, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 20499, 23511, 23261, 23628, 33305, 24035, 25598, 23114, 19874, 34253, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 26886, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 26931, 24569, 26439, 26947, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36019, 19288, 26995, 24035, 23112, 32618, 23511, 31507, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 28306, 27043, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 27061, 23511, 23511, 23511, 23511, 23512, 24694, 24035, 24035, 29978, 24035, 24035, 23113, 23114, 33114, 23114, 23114, 30010, 29700, 23511, 35913, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 20271, 23511, 23511, 23511, 23511, 30562, 24035, 24035, 27155, 26576, 23114, 23114, 30447, 23036, 29695, 23511, 23511, 30935, 20099, 24152, 25529, 27100, 34461, 27121, 22625, 29156, 26009, 27137, 30422, 31903, 31655, 28870, 27171, 32439, 31731, 19830, 27232, 22612, 27265, 26786, 25494, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 20342, 27288, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 27322, 27339, 28020, 27361, 27382, 29939, 24035, 24035, 32581, 24036, 23114, 23114, 23114, 27425, 22420, 23511, 23511, 23511, 27442, 28306, 19803, 24035, 24035, 24035, 24035, 26710, 23114, 23114, 23114, 23114, 32261, 22468, 23511, 23511, 23511, 23511, 35719, 24694, 29510, 24035, 24035, 24035, 24035, 26717, 23114, 23114, 23114, 23114, 28618, 32217, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 27459, 23114, 23114, 23114, 36252, 23029, 20271, 23511, 23511, 23511, 28840, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 27480, 34483, 28401, 29761, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36382, 19288, 21605, 27497, 27517, 28504, 28898, 27569, 29939, 29401, 27600, 27323, 27633, 19025, 27662, 23114, 27705, 22420, 20483, 27721, 23511, 27765, 28306, 19803, 23540, 24035, 24610, 27781, 27805, 26650, 23114, 28573, 32990, 25920, 22468, 26870, 23511, 26684, 34262, 34737, 25057, 34622, 24035, 24035, 23971, 24206, 27825, 27847, 23114, 23114, 27865, 27885, 35766, 27914, 23511, 23511, 32766, 32844, 27934, 28795, 26909, 27955, 26092, 27988, 25445, 28005, 28036, 28052, 21965, 23511, 32196, 19897, 28072, 28102, 36534, 21541, 23801, 28153, 28180, 28197, 28221, 23036, 32695, 28251, 28268, 28292, 23667, 34825, 23930, 24580, 28322, 28344, 31627, 28366, 25996, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 35625, 33477, 33359, 27674, 28393, 33992, 24036, 23114, 30243, 19829, 28417, 28433, 28463, 23008, 19876, 20208, 23007, 20046, 20132, 28489, 28520, 20141, 24569, 31691, 19787, 28550, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 24035, 23112, 32618, 23511, 31507, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 28306, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 23512, 24694, 28589, 24035, 24035, 24035, 24035, 28608, 23114, 23114, 23114, 23114, 28618, 20431, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 20271, 23511, 23511, 23511, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36004, 19288, 28634, 31951, 28565, 28702, 28718, 28741, 32544, 20175, 28792, 32086, 20105, 28811, 29059, 29862, 28856, 22420, 28886, 30354, 23359, 28922, 28306, 28952, 23888, 26320, 36506, 24035, 29331, 28968, 36609, 23114, 29003, 31661, 27061, 30649, 27366, 23511, 29023, 27918, 24694, 24035, 24035, 23893, 33094, 30867, 23113, 23114, 23114, 29044, 34184, 30010, 29700, 23511, 23511, 29081, 29102, 34585, 20402, 27789, 24035, 24035, 24036, 23114, 29132, 23114, 23114, 23029, 20271, 23511, 29153, 23511, 23511, 30562, 30174, 24035, 24035, 27409, 25438, 23114, 23114, 29172, 36668, 31332, 23511, 23511, 29192, 30144, 24035, 23110, 30203, 23114, 23467, 31544, 23261, 23628, 24035, 22545, 23111, 23114, 29213, 27078, 27689, 29234, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 29257, 23008, 19876, 20208, 28768, 29290, 29320, 34776, 29353, 20141, 22435, 29378, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36367, 19288, 21605, 34616, 19006, 32618, 31497, 31507, 36216, 20184, 24035, 34393, 29424, 34668, 23114, 34900, 29447, 22420, 30360, 23511, 37089, 29473, 28306, 19803, 29499, 24398, 24035, 24035, 26576, 31799, 29532, 29550, 23114, 33811, 22468, 32298, 29571, 31184, 23511, 23512, 37127, 36628, 29589, 24035, 24135, 24035, 23113, 29608, 23114, 27831, 29634, 28618, 29652, 30037, 23511, 24172, 29671, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 29555, 29690, 23511, 23511, 23511, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 29719, 24035, 23110, 29738, 23114, 23467, 34035, 29756, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 29777, 34364, 28181, 30243, 29799, 31920, 27272, 27185, 23008, 31126, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29828, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 35989, 19552, 19687, 35139, 28649, 29878, 29894, 29924, 29939, 23224, 23085, 31969, 24036, 35173, 24752, 24803, 23114, 22420, 31190, 30318, 24870, 23511, 28306, 29967, 23967, 24035, 24035, 24035, 26576, 30000, 23114, 23114, 23114, 33811, 22468, 30026, 23511, 23511, 23511, 23512, 26078, 24035, 24035, 24035, 30053, 37137, 30071, 23114, 23114, 33368, 25136, 28618, 30723, 23511, 23511, 37096, 31356, 34585, 20402, 30092, 30127, 30160, 24036, 35740, 30219, 24960, 30259, 23029, 20271, 34042, 30285, 30342, 30376, 23289, 30055, 30400, 30419, 30438, 32640, 33532, 33514, 30472, 18792, 26267, 24323, 23057, 30493, 23639, 20008, 30196, 33188, 30517, 20075, 23511, 30541, 23628, 30578, 33928, 28776, 30594, 19874, 30610, 30637, 19830, 30677, 27646, 19872, 25779, 23266, 23232, 35016, 30243, 30696, 29812, 30712, 30746, 27206, 30779, 30807, 23007, 33395, 20132, 26578, 27685, 31703, 22928, 31691, 19787, 31079, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36352, 19288, 23335, 30841, 26131, 30888, 30904, 30986, 29939, 24035, 24704, 31017, 20025, 23114, 26178, 31051, 31095, 22420, 23511, 22524, 31142, 31172, 28534, 31206, 35497, 25196, 24035, 28592, 24503, 23114, 31239, 31285, 23114, 31305, 31321, 31355, 31372, 31407, 23511, 30556, 24694, 24035, 27501, 19805, 24035, 24035, 23113, 23114, 31428, 24066, 23114, 28618, 29700, 23511, 31837, 18809, 23511, 34585, 31448, 24035, 24035, 24035, 23090, 23114, 23114, 23114, 23114, 31619, 35038, 23511, 23511, 23511, 23511, 33714, 24035, 33085, 24035, 29431, 23114, 31467, 23114, 23143, 31487, 23511, 31523, 23511, 35195, 36783, 24035, 30111, 23567, 23114, 23467, 31543, 31560, 23628, 24035, 24035, 23111, 23114, 19874, 30953, 31584, 34508, 24035, 31608, 26345, 37055, 23266, 31643, 31677, 31719, 31747, 31786, 31822, 26898, 23008, 19876, 31859, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 31878, 31936, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 35974, 19288, 21605, 27972, 35663, 31985, 29655, 32001, 36715, 24785, 25893, 23545, 31912, 19853, 19916, 25938, 24540, 22420, 31843, 29674, 29573, 32735, 28936, 19803, 24035, 24035, 32047, 24035, 26576, 23114, 23114, 27544, 23114, 33811, 22468, 23511, 23511, 32161, 23511, 23512, 32066, 24035, 33313, 24035, 24035, 24035, 23113, 27426, 32102, 23114, 23114, 28618, 32125, 23511, 32144, 23511, 23511, 33569, 20402, 24035, 27045, 24035, 24036, 23114, 23114, 28328, 23114, 30076, 32177, 23511, 23511, 30384, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23595, 32212, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 22635, 25753, 32233, 32257, 32277, 19829, 26577, 26597, 20211, 23008, 19876, 32322, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 32352, 35285, 32380, 34196, 33016, 30661, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 28306, 32404, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 32422, 23511, 23511, 23511, 23511, 23512, 24694, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 30269, 29700, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 20271, 23511, 23511, 23511, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 19949, 24035, 23111, 32455, 19874, 31269, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36337, 19552, 19209, 21617, 26509, 32475, 32491, 32529, 29939, 24035, 32578, 25241, 32597, 23114, 32634, 29007, 32656, 22420, 23511, 32729, 26365, 32751, 28306, 32788, 32882, 24035, 24035, 32813, 36727, 23114, 33182, 23114, 27553, 33235, 32829, 23511, 32706, 23511, 28906, 28377, 26962, 32881, 32904, 32898, 32920, 24035, 32953, 23114, 32977, 26408, 23114, 28164, 33006, 23511, 33039, 35774, 23511, 32306, 20402, 33076, 30872, 24035, 24036, 25408, 33110, 28979, 23114, 23029, 20271, 35835, 33130, 33054, 23511, 30562, 33148, 24035, 24035, 33167, 23114, 23114, 33775, 23036, 20459, 23511, 23511, 25464, 24646, 24035, 24035, 22446, 23114, 23114, 25627, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 31391, 33204, 33220, 33251, 33287, 26577, 26597, 20211, 33329, 19876, 33345, 23007, 20046, 20132, 26578, 27685, 28473, 22599, 31691, 33411, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 35959, 19288, 21907, 27243, 29843, 32618, 33427, 31507, 29939, 33460, 34090, 24035, 24036, 33493, 24416, 33530, 23114, 22420, 33548, 24379, 33585, 23511, 28306, 19803, 33603, 24202, 24035, 24035, 25593, 33749, 28205, 23114, 23114, 32388, 22468, 33853, 33060, 23511, 23511, 31339, 33621, 24035, 24035, 34397, 24618, 30757, 33663, 23114, 23114, 33683, 35684, 28618, 26678, 23511, 23511, 32506, 33699, 34585, 20402, 24035, 32562, 26973, 24036, 23114, 23114, 33377, 33773, 23029, 20271, 23511, 23511, 30621, 23511, 23860, 24035, 33791, 21553, 26576, 36558, 23114, 33809, 23036, 32857, 26047, 23511, 33827, 23634, 24035, 24035, 23110, 23114, 23114, 31252, 23511, 33845, 23628, 24035, 24459, 23111, 23114, 33869, 27078, 30791, 29783, 24035, 24742, 19872, 33895, 23266, 26462, 19710, 33879, 33919, 26577, 26597, 24123, 24930, 21930, 20208, 30501, 33953, 25268, 20252, 33983, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36322, 19552, 23390, 33634, 35154, 34008, 34024, 34058, 35544, 34106, 34128, 26811, 33151, 34144, 34169, 34212, 23114, 34228, 34244, 34278, 34315, 23511, 34331, 34347, 34380, 34413, 24035, 24663, 26576, 34429, 34453, 34477, 29534, 33811, 22468, 34499, 34524, 34557, 25170, 34580, 35436, 23937, 34601, 24035, 24341, 26453, 23113, 34638, 34662, 23114, 24236, 28618, 34684, 34703, 34729, 23511, 35352, 34753, 34799, 24035, 34815, 32558, 34848, 34888, 35814, 34923, 23165, 29137, 23606, 30326, 30730, 34939, 33023, 30562, 36848, 34979, 24035, 24847, 34996, 23114, 23114, 35032, 29695, 35054, 23511, 23511, 35091, 33296, 35124, 24296, 28235, 24361, 36276, 32772, 35067, 35189, 27301, 30855, 24852, 22452, 35211, 35237, 35316, 25500, 35270, 23405, 24304, 35304, 29362, 24036, 23114, 35332, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 35368, 28823, 23920, 32336, 35405, 20141, 24569, 31691, 35421, 35479, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 35944, 22795, 21605, 33647, 35877, 35513, 30962, 35529, 34073, 35557, 24035, 24035, 20405, 31107, 23114, 23114, 23114, 35590, 34713, 23511, 23511, 23511, 35641, 19803, 29408, 32937, 25298, 24035, 35657, 23115, 27849, 24760, 35679, 26205, 22468, 23511, 35700, 24907, 24901, 35075, 31893, 34980, 24035, 24035, 24035, 24035, 23113, 35009, 23114, 23114, 23114, 28618, 35716, 30970, 23511, 23511, 23511, 34585, 23215, 24035, 24035, 24035, 24036, 35735, 23114, 23114, 23114, 27105, 35756, 35790, 23511, 23511, 23511, 35254, 35446, 24035, 24035, 31223, 35809, 23114, 23114, 23036, 36825, 35830, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 31031, 20355, 19872, 33903, 23266, 24036, 23114, 28686, 19829, 26577, 26597, 20211, 23008, 23424, 20208, 24711, 31065, 24486, 26578, 27685, 20141, 19773, 35851, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36307, 19288, 21605, 35494, 19702, 32618, 33437, 31507, 29939, 25117, 24035, 27939, 24036, 27869, 23114, 26829, 23114, 22420, 23494, 23511, 33132, 23511, 28306, 19803, 24035, 34832, 24035, 24035, 26576, 23114, 25153, 23114, 23114, 33811, 22468, 23511, 23511, 35911, 23511, 23512, 24694, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 20271, 23511, 23511, 23511, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 35929, 19288, 21605, 25860, 23112, 36185, 23511, 36201, 29939, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 22420, 23511, 23511, 23511, 23511, 28306, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 23512, 26748, 24035, 24035, 24035, 24035, 24035, 36249, 23114, 23114, 23114, 23114, 28618, 28835, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 27151, 24035, 26760, 23114, 27989, 23114, 23114, 36268, 20271, 23511, 24436, 23511, 29703, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36292, 19288, 21605, 36503, 21922, 32618, 34534, 31507, 36522, 24035, 33793, 24035, 35864, 23114, 23114, 36555, 23417, 22420, 23511, 23511, 36574, 26020, 28306, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 33811, 22468, 23511, 23511, 23511, 23511, 23512, 36592, 24035, 24035, 36625, 24035, 24035, 23113, 23114, 32961, 23114, 23114, 29618, 29700, 23511, 29086, 23511, 23511, 34585, 20402, 36644, 24035, 24035, 24036, 29740, 23114, 23114, 23114, 29065, 36663, 31527, 23511, 23511, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36079, 19288, 21605, 31451, 23112, 36684, 23511, 36700, 29939, 24035, 24035, 24035, 30185, 23114, 23114, 23114, 27526, 22420, 23511, 23511, 23511, 32865, 28306, 19803, 36743, 24035, 27017, 24035, 26576, 27535, 23114, 31432, 23114, 33811, 22468, 33271, 23511, 32128, 23511, 23512, 24694, 24035, 27196, 24035, 24035, 24035, 23113, 32459, 23114, 23114, 23114, 28618, 29700, 33829, 36762, 23511, 23511, 34585, 20402, 24035, 36746, 24035, 29722, 23114, 23114, 34437, 23114, 34907, 20271, 23511, 23511, 18801, 23511, 23206, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 36837, 24035, 24035, 33739, 23114, 23114, 25094, 23511, 23261, 23628, 24035, 36780, 23111, 24073, 19874, 27078, 35344, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22720, 19288, 36799, 36866, 17466, 36890, 36864, 21991, 22211, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 17631, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 36883, 36906, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 22705, 19288, 19457, 36866, 17466, 36890, 36866, 19375, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18855, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36124, 19288, 36951, 36866, 17466, 36890, 36866, 21991, 22404, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18567, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 36979, 36995, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36139, 19288, 19457, 36866, 17466, 36890, 36866, 21991, 22971, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18027, 22984, 17553, 17572, 22285, 18462, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 17619, 22083, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 36139, 19288, 21529, 24035, 23112, 23033, 23511, 31507, 25377, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 37040, 23511, 23511, 23511, 23511, 28086, 19803, 24035, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23114, 24254, 37079, 23511, 23511, 23511, 23511, 23512, 34766, 24035, 24035, 24035, 24035, 24035, 23113, 23114, 23114, 23114, 23114, 28618, 29700, 23511, 23511, 23511, 23511, 34585, 20402, 24035, 24035, 24035, 24036, 23114, 23114, 23114, 23114, 23029, 20271, 23511, 23511, 23511, 23511, 30562, 24035, 24035, 24035, 26576, 23114, 23114, 23114, 23036, 29695, 23511, 23511, 23511, 23634, 24035, 24035, 23110, 23114, 23114, 23467, 23511, 23261, 23628, 24035, 24035, 23111, 23114, 19874, 27078, 27689, 19830, 24035, 23112, 19872, 27741, 23266, 24036, 23114, 30243, 19829, 26577, 26597, 20211, 23008, 19876, 20208, 23007, 20046, 20132, 26578, 27685, 20141, 24569, 31691, 19787, 29304, 20268, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 37112, 37160, 18469, 36866, 17466, 36890, 36866, 17656, 37174, 22987, 17556, 17575, 22288, 17486, 17509, 17525, 18373, 18537, 22984, 17553, 17572, 22285, 18780, 17990, 18622, 19411, 20306, 17996, 17689, 17470, 17591, 20896, 17468, 36883, 36906, 36867, 19404, 20299, 36866, 17647, 17862, 18921, 19514, 17705, 20311, 37017, 17728, 17756, 17784, 17800, 17825, 17854, 18403, 18928, 19521, 17712, 37008, 37024, 17878, 18884, 17900, 17922, 17944, 18178, 17960, 18012, 18381, 18064, 18218, 17884, 18890, 17906, 17928, 18102, 25022, 18130, 36931, 36963, 17493, 18150, 18166, 18214, 25010, 25026, 18134, 36935, 18262, 18278, 18294, 18320, 18336, 18361, 18397, 18274, 22096, 18304, 18448, 18485, 18523, 18553, 18583, 19149, 18638, 18497, 19656, 18664, 18680, 18507, 18696, 19164, 18712, 18737, 17681, 22026, 20906, 20915, 22054, 17838, 17450, 22022, 18765, 19225, 18841, 18871, 18906, 19241, 19257, 18976, 19041, 19056, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 19058, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 127011, 110630, 114730, 106539, 127011, 127011, 127011, 53264, 18, 18, 0, 0, 57366, 0, 24, 24, 24, 0, 28, 28, 28, 28, 102432, 0, 0, 127011, 0, 2220032, 110630, 0, 0, 0, 114730, 106539, 0, 2170880, 2170880, 2170880, 2170880, 0, 0, 0, 2170880, 2170880, 2170880, 3002368, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2576384, 2215936, 2215936, 2215936, 2416640, 2424832, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2543616, 2215936, 2215936, 2215936, 2215936, 2215936, 2629632, 2215936, 2617344, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2691072, 2215936, 2707456, 2215936, 2715648, 2215936, 2723840, 2764800, 2215936, 2215936, 2797568, 2215936, 2822144, 2215936, 2215936, 2854912, 2215936, 2215936, 2215936, 2912256, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 0, 0, 180224, 0, 0, 2174976, 0, 0, 2170880, 2617344, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2691072, 2170880, 2707456, 2170880, 2715648, 2170880, 2723840, 2764800, 2170880, 2170880, 2797568, 2170880, 2170880, 2797568, 2170880, 2822144, 2170880, 2170880, 2854912, 2170880, 2170880, 2170880, 2912256, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2215936, 2215936, 2215936, 2215936, 2609152, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2654208, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 0, 0, 184599, 280, 0, 2174976, 0, 0, 2215936, 3117056, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 544, 0, 546, 0, 0, 2179072, 0, 0, 0, 552, 0, 0, 2170880, 2170880, 2170880, 3117056, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 0, 0, 2158592, 2158592, 2232320, 2232320, 0, 2240512, 2240512, 0, 0, 0, 644, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3129344, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2215936, 2215936, 2215936, 2400256, 2215936, 2215936, 2215936, 2215936, 2711552, 2170880, 2170880, 2170880, 2170880, 2170880, 2760704, 2768896, 2789376, 2813952, 2170880, 2170880, 2170880, 2875392, 2904064, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2453504, 2457600, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 167936, 0, 0, 0, 0, 2174976, 0, 0, 2215936, 2215936, 2514944, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2592768, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 32768, 0, 0, 0, 0, 0, 2174976, 32768, 0, 2633728, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2711552, 2215936, 2215936, 2215936, 2215936, 2215936, 2760704, 2768896, 2789376, 2813952, 2215936, 2215936, 2215936, 2875392, 2904064, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2174976, 0, 65819, 2215936, 2215936, 3031040, 2215936, 3055616, 2215936, 2215936, 2215936, 2215936, 3092480, 2215936, 2215936, 3125248, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 3002368, 2215936, 2215936, 2170880, 2170880, 2494464, 2170880, 2170880, 0, 0, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 3198976, 2215936, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 0, 0, 2379776, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2445312, 2170880, 2465792, 2473984, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2523136, 2170880, 2170880, 2641920, 2170880, 2170880, 2170880, 2699264, 2170880, 2727936, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2879488, 2170880, 2916352, 2170880, 2170880, 2170880, 2879488, 2170880, 2916352, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3026944, 2170880, 2170880, 3063808, 2170880, 2170880, 3112960, 2170880, 2170880, 3133440, 2170880, 2170880, 3112960, 2170880, 2170880, 3133440, 2170880, 2170880, 2170880, 3162112, 2170880, 2170880, 3182592, 3186688, 2170880, 2379776, 2215936, 2523136, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2596864, 2215936, 2621440, 2215936, 2215936, 2641920, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2179072, 548, 0, 0, 0, 0, 287, 2170880, 0, 2170880, 2170880, 2170880, 2400256, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3117056, 2170880, 2170880, 2170880, 2170880, 2215936, 2215936, 2699264, 2215936, 2727936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2879488, 2215936, 2916352, 2215936, 2215936, 0, 0, 0, 0, 188416, 0, 2179072, 0, 0, 0, 0, 0, 287, 2170880, 0, 2171019, 2171019, 2171019, 2400395, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 3031179, 2171019, 3055755, 2171019, 2171019, 2215936, 3133440, 2215936, 2215936, 2215936, 3162112, 2215936, 2215936, 3182592, 3186688, 2215936, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2523275, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2597003, 2171019, 2621579, 2170880, 2170880, 2170880, 3162112, 2170880, 2170880, 3182592, 3186688, 2170880, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 53264, 0, 18, 18, 24, 24, 0, 4337664, 28, 2170880, 2170880, 2170880, 2629632, 2170880, 2170880, 2170880, 2170880, 2719744, 2744320, 2170880, 2170880, 2170880, 2834432, 2838528, 2170880, 2908160, 2170880, 2170880, 2936832, 2215936, 2215936, 2215936, 2215936, 2719744, 2744320, 2215936, 2215936, 2215936, 2834432, 2838528, 2215936, 2908160, 2215936, 2215936, 2936832, 2215936, 2215936, 2985984, 2215936, 2994176, 2215936, 2215936, 3014656, 2215936, 3059712, 3076096, 3088384, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2445312, 2215936, 2465792, 2473984, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2171166, 2171166, 2171166, 2171166, 2171166, 0, 0, 0, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171019, 2171019, 2494603, 2171019, 2171019, 2215936, 2215936, 2215936, 3215360, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2379776, 2170880, 2170880, 2170880, 2170880, 2985984, 2170880, 2994176, 2170880, 2170880, 3016168, 2170880, 3059712, 3076096, 3088384, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 53264, 0, 18, 18, 124, 124, 0, 128, 128, 2170880, 2170880, 2170880, 3215360, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2486272, 2170880, 2170880, 2506752, 2170880, 2170880, 2170880, 2535424, 2539520, 2170880, 2170880, 2588672, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2920448, 2170880, 2170880, 2170880, 2990080, 2170880, 2170880, 2170880, 2170880, 3051520, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3170304, 0, 2387968, 2392064, 2170880, 2170880, 2433024, 2170880, 2170880, 2170880, 3170304, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2486272, 2215936, 2215936, 2506752, 2215936, 2215936, 2215936, 2535424, 2539520, 2215936, 2215936, 2588672, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2174976, 136, 0, 2215936, 2215936, 2920448, 2215936, 2215936, 2215936, 2990080, 2215936, 2215936, 2215936, 2215936, 3051520, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 3108864, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 3026944, 2215936, 2215936, 3063808, 2215936, 2215936, 3112960, 2215936, 2215936, 2215936, 3170304, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2453504, 2457600, 2170880, 2170880, 2170880, 2486272, 2170880, 2170880, 2506752, 2170880, 2170880, 2170880, 2537049, 2539520, 2170880, 2170880, 2588672, 2170880, 2170880, 2170880, 1508, 2170880, 2170880, 2170880, 1512, 2170880, 2920448, 2170880, 2170880, 2170880, 2990080, 2170880, 2170880, 2170880, 2461696, 2170880, 2170880, 2170880, 2510848, 2170880, 2170880, 2170880, 2170880, 2580480, 2170880, 2605056, 2637824, 2170880, 2170880, 18, 0, 0, 0, 0, 0, 0, 0, 0, 2220032, 0, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2686976, 2748416, 2170880, 2170880, 2170880, 2924544, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3121152, 2170880, 2170880, 3145728, 3158016, 3166208, 2170880, 2420736, 2428928, 2170880, 2478080, 2170880, 2170880, 2170880, 2170880, 0, 0, 2170880, 2170880, 2170880, 2170880, 2646016, 2670592, 0, 0, 3145728, 3158016, 3166208, 2387968, 2392064, 2215936, 2215936, 2433024, 2215936, 2461696, 2215936, 2215936, 2215936, 2510848, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2179072, 0, 0, 0, 0, 0, 0, 2170880, 2215936, 2215936, 2580480, 2215936, 2605056, 2637824, 2215936, 2215936, 2686976, 2748416, 2215936, 2215936, 2215936, 2924544, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2179072, 0, 0, 0, 0, 0, 286, 2170880, 2215936, 2215936, 2215936, 2215936, 2215936, 3121152, 2215936, 2215936, 3145728, 3158016, 3166208, 2387968, 2392064, 2170880, 2170880, 2433024, 2170880, 2461696, 2170880, 2170880, 2170880, 2510848, 2170880, 2170880, 1625, 2170880, 2170880, 2580480, 2170880, 2605056, 2637824, 2170880, 647, 2170880, 2170880, 2170880, 2400256, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2576384, 2170880, 2170880, 2170880, 2170880, 2170880, 2609152, 2170880, 2170880, 2686976, 0, 0, 2748416, 2170880, 2170880, 0, 2170880, 2924544, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 53264, 0, 18, 18, 24, 0, 0, 28, 28, 2170880, 3141632, 2215936, 2420736, 2428928, 2215936, 2478080, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2646016, 2670592, 2752512, 2756608, 2846720, 2961408, 2215936, 2998272, 2215936, 3010560, 2215936, 2215936, 2215936, 3141632, 2170880, 2420736, 2428928, 2752512, 2756608, 0, 2846720, 2961408, 2170880, 2998272, 2170880, 3010560, 2170880, 2170880, 2170880, 3141632, 2170880, 2170880, 2490368, 2215936, 2490368, 2215936, 2215936, 2215936, 2547712, 2555904, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2174976, 245760, 0, 3129344, 2170880, 2170880, 2490368, 2170880, 2170880, 2170880, 0, 0, 2547712, 2555904, 2170880, 2170880, 2170880, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2220032, 0, 0, 45056, 0, 2584576, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2170880, 2170880, 2170880, 2170880, 0, 0, 0, 2170880, 2170880, 2158592, 0, 0, 0, 0, 0, 0, 0, 0, 2220032, 0, 0, 0, 0, 0, 0, 0, 0, 1482, 97, 97, 97, 97, 97, 97, 97, 1354, 97, 97, 97, 97, 97, 97, 97, 97, 1148, 97, 97, 97, 97, 97, 97, 97, 2584576, 2170880, 2170880, 1512, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2441216, 2170880, 2527232, 2170880, 2600960, 2170880, 2850816, 2170880, 2170880, 2170880, 3022848, 2215936, 2441216, 2215936, 2527232, 2215936, 2600960, 2215936, 2850816, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2179072, 0, 0, 0, 0, 0, 287, 2170880, 2215936, 3022848, 2170880, 2441216, 2170880, 2527232, 0, 0, 2170880, 2600960, 2170880, 0, 2850816, 2170880, 2170880, 2170880, 2170880, 2170880, 2523136, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2596864, 2170880, 2621440, 2170880, 2170880, 2641920, 2170880, 2170880, 2170880, 3022848, 2170880, 2519040, 2170880, 2170880, 2170880, 2170880, 2170880, 2215936, 2519040, 2215936, 2215936, 2215936, 2215936, 2215936, 2170880, 2170880, 2170880, 2453504, 2457600, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2514944, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2592768, 2170880, 2170880, 2519040, 0, 2024, 2170880, 2170880, 0, 2170880, 2170880, 2170880, 2396160, 2170880, 2170880, 2170880, 2170880, 3018752, 2396160, 2215936, 2215936, 2215936, 2215936, 3018752, 2396160, 0, 2024, 2170880, 2170880, 2170880, 2170880, 3018752, 2170880, 2650112, 2965504, 2170880, 2215936, 2650112, 2965504, 2215936, 0, 0, 2170880, 2650112, 2965504, 2170880, 2551808, 2170880, 2551808, 2215936, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 141, 45, 45, 67, 67, 67, 67, 67, 224, 67, 67, 238, 67, 67, 67, 67, 67, 67, 67, 1288, 67, 67, 67, 67, 67, 67, 67, 67, 67, 469, 67, 67, 67, 67, 67, 67, 0, 2551808, 2170880, 2170880, 2215936, 0, 2170880, 2170880, 2215936, 0, 2170880, 2170880, 2215936, 0, 2170880, 2977792, 2977792, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 53264, 18, 49172, 57366, 24, 8192, 29, 102432, 127011, 110630, 114730, 106539, 127011, 127011, 127011, 53264, 18, 18, 49172, 0, 0, 0, 24, 24, 24, 0, 28, 28, 28, 28, 102432, 127, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 2170880, 2170880, 2170880, 2416640, 0, 0, 0, 0, 2220032, 110630, 0, 0, 0, 114730, 106539, 136, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 53264, 0, 4256099, 4256099, 24, 24, 0, 28, 28, 2170880, 2461696, 2170880, 2170880, 2170880, 2510848, 2170880, 2170880, 0, 2170880, 2170880, 2580480, 2170880, 2605056, 2637824, 2170880, 2170880, 2170880, 2547712, 2555904, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3129344, 2215936, 2215936, 543, 543, 545, 545, 0, 0, 2179072, 0, 550, 551, 551, 0, 287, 2171166, 2171166, 18, 0, 0, 0, 0, 0, 0, 0, 0, 2220032, 0, 0, 645, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 45, 149, 2584576, 2170880, 2170880, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2441216, 2170880, 2527232, 2170880, 2600960, 2519040, 0, 0, 2170880, 2170880, 0, 2170880, 2170880, 2170880, 2396160, 2170880, 2170880, 2170880, 2170880, 3018752, 2396160, 2215936, 2215936, 2215936, 2215936, 3018752, 2396160, 0, 0, 2170880, 2170880, 2170880, 2170880, 3018752, 2170880, 2650112, 2965504, 53264, 18, 49172, 57366, 24, 155648, 28, 102432, 155648, 155687, 114730, 106539, 0, 0, 155648, 53264, 18, 18, 49172, 0, 57366, 0, 24, 24, 24, 0, 28, 28, 28, 28, 102432, 0, 0, 0, 0, 2220032, 0, 94208, 0, 0, 114730, 106539, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 53264, 208896, 18, 278528, 24, 24, 0, 28, 28, 53264, 18, 159765, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 0, 53264, 18, 18, 49172, 0, 57366, 0, 24, 24, 24, 0, 28, 139394, 28, 28, 102432, 131, 0, 0, 0, 2220032, 110630, 0, 0, 0, 114730, 106539, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 32768, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 0, 546, 0, 0, 2183168, 0, 0, 552, 832, 2170880, 2170880, 2170880, 2400256, 2170880, 2170880, 2170880, 2170880, 2170880, 2609152, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2654208, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 3198976, 2215936, 0, 1084, 0, 1088, 0, 1092, 0, 0, 0, 0, 0, 41606, 0, 0, 0, 0, 45, 45, 45, 45, 45, 937, 0, 0, 0, 0, 2220032, 110630, 0, 0, 0, 114730, 106539, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3198976, 2170880, 0, 0, 644, 0, 0, 0, 2215936, 3117056, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 826, 0, 828, 0, 0, 2183168, 0, 0, 830, 0, 2170880, 2170880, 2170880, 2400256, 2170880, 2170880, 2170880, 2170880, 2592768, 2170880, 2170880, 2170880, 2170880, 2633728, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2711552, 2170880, 2170880, 2170880, 2170880, 2170880, 2760704, 53264, 18, 49172, 57366, 24, 8192, 28, 172066, 172032, 110630, 172066, 106539, 0, 0, 172032, 53264, 18, 18, 49172, 0, 57366, 0, 24, 24, 24, 16384, 28, 28, 28, 28, 102432, 0, 98304, 0, 0, 2220032, 110630, 0, 0, 0, 0, 106539, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3198976, 2170880, 0, 0, 45056, 0, 0, 0, 53264, 18, 49172, 57366, 25, 8192, 30, 102432, 0, 110630, 114730, 106539, 0, 0, 176219, 53264, 18, 18, 49172, 0, 57366, 0, 124, 124, 124, 0, 128, 128, 128, 128, 102432, 128, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 2170880, 2170880, 2170880, 2416640, 0, 546, 0, 0, 2183168, 0, 65536, 552, 0, 2170880, 2170880, 2170880, 2400256, 2170880, 2170880, 2170880, 2170880, 2646016, 2670592, 2752512, 2756608, 2846720, 2961408, 2170880, 2998272, 2170880, 3010560, 2170880, 2170880, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 3198976, 2215936, 0, 0, 0, 0, 0, 0, 65536, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 143, 45, 45, 67, 67, 67, 67, 67, 227, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1824, 67, 1826, 67, 67, 67, 67, 17, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 32768, 120, 121, 18, 18, 49172, 0, 57366, 0, 24, 24, 24, 0, 28, 28, 28, 28, 102432, 67, 67, 37139, 37139, 24853, 24853, 0, 0, 2179072, 548, 0, 65820, 65820, 0, 287, 97, 0, 0, 97, 97, 0, 97, 97, 97, 45, 45, 45, 45, 2033, 45, 67, 67, 67, 67, 0, 0, 97, 97, 97, 97, 45, 45, 67, 67, 0, 369, 0, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 978, 0, 546, 70179, 0, 2183168, 0, 0, 552, 0, 97, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 1013, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 473, 67, 67, 67, 67, 483, 67, 67, 1025, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 1119, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1359, 97, 97, 97, 67, 67, 1584, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 497, 67, 67, 1659, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1667, 45, 45, 45, 45, 45, 169, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1668, 45, 45, 45, 45, 67, 67, 1694, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 774, 67, 67, 1713, 97, 97, 97, 97, 97, 97, 97, 0, 97, 97, 1723, 97, 97, 97, 97, 0, 45, 45, 45, 45, 45, 45, 1538, 45, 45, 45, 45, 45, 1559, 45, 45, 1561, 45, 45, 45, 45, 45, 45, 45, 687, 45, 45, 45, 45, 45, 45, 45, 45, 448, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 1771, 1772, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 0, 0, 0, 97, 67, 67, 67, 67, 67, 1821, 67, 67, 67, 67, 67, 67, 1827, 67, 67, 67, 0, 0, 0, 0, 0, 0, 97, 97, 1614, 97, 97, 97, 97, 97, 603, 97, 97, 605, 97, 97, 608, 97, 97, 97, 97, 0, 1532, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 450, 45, 45, 45, 45, 67, 67, 97, 97, 97, 97, 97, 97, 0, 0, 1839, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 97, 1883, 97, 1885, 97, 0, 1888, 0, 97, 97, 0, 97, 97, 1848, 97, 97, 97, 97, 1852, 45, 45, 45, 45, 45, 45, 45, 384, 391, 45, 45, 45, 45, 45, 45, 45, 385, 45, 45, 45, 45, 45, 45, 45, 45, 1237, 45, 45, 45, 45, 45, 45, 67, 0, 97, 97, 97, 97, 0, 0, 0, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 45, 1951, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 1963, 97, 2023, 0, 97, 97, 0, 97, 97, 97, 45, 45, 45, 45, 45, 45, 67, 67, 1994, 67, 1995, 67, 67, 67, 67, 67, 67, 97, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 97, 97, 0, 0, 0, 0, 2220032, 110630, 0, 0, 0, 114730, 106539, 137, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2793472, 2805760, 2170880, 2830336, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3031040, 2170880, 3055616, 2170880, 2170880, 67, 67, 37139, 37139, 24853, 24853, 0, 0, 281, 549, 0, 65820, 65820, 0, 287, 97, 0, 0, 97, 97, 0, 97, 97, 97, 45, 45, 2031, 2032, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1769, 67, 0, 546, 70179, 549, 549, 0, 0, 552, 0, 97, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 1858, 45, 641, 0, 0, 0, 0, 41606, 926, 0, 0, 0, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 456, 67, 0, 0, 0, 1313, 0, 0, 0, 1096, 1319, 0, 0, 0, 0, 97, 97, 97, 97, 97, 97, 97, 97, 1110, 97, 97, 97, 97, 67, 67, 67, 67, 1301, 1476, 0, 0, 0, 0, 1307, 1478, 0, 0, 0, 0, 0, 0, 0, 0, 97, 97, 97, 97, 1486, 97, 1487, 97, 1313, 1480, 0, 0, 0, 0, 1319, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 566, 97, 97, 97, 97, 97, 97, 67, 67, 67, 1476, 0, 1478, 0, 1480, 0, 97, 97, 97, 97, 97, 97, 97, 45, 1853, 45, 1855, 45, 45, 45, 45, 53264, 18, 49172, 57366, 26, 8192, 31, 102432, 0, 110630, 114730, 106539, 0, 0, 225368, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 32768, 53264, 18, 18, 49172, 163840, 57366, 0, 24, 24, 229376, 0, 28, 28, 28, 229376, 102432, 0, 0, 0, 0, 2220167, 110630, 0, 0, 0, 114730, 106539, 0, 2171019, 2171019, 2171019, 2171019, 2592907, 2171019, 2171019, 2171019, 2171019, 2633867, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2654347, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 3117195, 2171019, 2171019, 2171019, 2171019, 2240641, 0, 0, 0, 0, 0, 0, 0, 0, 368, 0, 140, 2171019, 2171019, 2171019, 2416779, 2424971, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2617483, 2171019, 2171019, 2642059, 2171019, 2171019, 2171019, 2699403, 2171019, 2728075, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 3215499, 2215936, 2215936, 2215936, 2215936, 2215936, 2437120, 2215936, 2215936, 2171019, 2822283, 2171019, 2171019, 2855051, 2171019, 2171019, 2171019, 2912395, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 3002507, 2171019, 2171019, 2215936, 2215936, 2494464, 2215936, 2215936, 2215936, 2171166, 2171166, 2416926, 2425118, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2576670, 2171166, 2617630, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2691358, 2171166, 2707742, 2171166, 2715934, 2171166, 2724126, 2765086, 2171166, 2171166, 2797854, 2171166, 2822430, 2171166, 2171166, 2855198, 2171166, 2171166, 2171166, 2912542, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2793758, 2806046, 2171166, 2830622, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 3109150, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2543902, 2171166, 2171166, 2171166, 2171166, 2171166, 2629918, 2793611, 2805899, 2171019, 2830475, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 0, 546, 0, 0, 2183168, 0, 0, 552, 0, 2171166, 2171166, 2171166, 2400542, 2171166, 2171166, 2171166, 0, 2171166, 2171166, 2171166, 0, 2171166, 2920734, 2171166, 2171166, 2171166, 2990366, 2171166, 2171166, 2171166, 2171166, 3117342, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 0, 53264, 0, 18, 18, 4329472, 2232445, 0, 2240641, 4337664, 2711691, 2171019, 2171019, 2171019, 2171019, 2171019, 2760843, 2769035, 2789515, 2814091, 2171019, 2171019, 2171019, 2875531, 2904203, 2171019, 2171019, 3092619, 2171019, 2171019, 3125387, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 3199115, 2171019, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2453504, 2457600, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2793472, 2805760, 2215936, 2830336, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2494464, 2170880, 2170880, 2171166, 2171166, 2634014, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2711838, 2171166, 2171166, 2171166, 2171166, 2171166, 2760990, 2769182, 2789662, 2814238, 2171166, 2171166, 2171166, 2875678, 2904350, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 3199262, 2171166, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2379915, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2445451, 2171019, 2465931, 2474123, 2171019, 2171019, 3113099, 2171019, 2171019, 3133579, 2171019, 2171019, 2171019, 3162251, 2171019, 2171019, 3182731, 3186827, 2171019, 2379776, 2879627, 2171019, 2916491, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 3027083, 2171019, 2171019, 3063947, 2699550, 2171166, 2728222, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2879774, 2171166, 2916638, 2171166, 2171166, 2171166, 2171166, 2171166, 2609438, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2654494, 2171166, 2171166, 2171166, 2171166, 2171166, 2445598, 2171166, 2466078, 2474270, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2523422, 2171019, 2437259, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2543755, 2171019, 2171019, 2171019, 2584715, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2908299, 2171019, 2171019, 2936971, 2171019, 2171019, 2986123, 2171019, 2994315, 2171019, 2171019, 3014795, 2171019, 3059851, 3076235, 3088523, 2171166, 2171166, 2986270, 2171166, 2994462, 2171166, 2171166, 3014942, 2171166, 3059998, 3076382, 3088670, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 3027230, 2171166, 2171166, 3064094, 2171166, 2171166, 3113246, 2171166, 2171166, 3133726, 2506891, 2171019, 2171019, 2171019, 2535563, 2539659, 2171019, 2171019, 2588811, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2691211, 2171019, 2707595, 2171019, 2715787, 2171019, 2723979, 2764939, 2171019, 2171019, 2797707, 2215936, 2215936, 3170304, 0, 0, 0, 0, 0, 0, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2453790, 2457886, 2171166, 2171166, 2171166, 2486558, 2171166, 2171166, 2507038, 2171166, 2171166, 2171166, 2535710, 2539806, 2171166, 2171166, 2588958, 2171166, 2171166, 2171166, 2171166, 2515230, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2593054, 2171166, 2171166, 2171166, 2171166, 3051806, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 3170590, 0, 2388107, 2392203, 2171019, 2171019, 2433163, 2171019, 2461835, 2171019, 2171019, 2171019, 2510987, 2171019, 2171019, 2171019, 2171019, 2580619, 2171019, 2605195, 2637963, 2171019, 2171019, 2171019, 2920587, 2171019, 2171019, 2171019, 2990219, 2171019, 2171019, 2171019, 2171019, 3051659, 2171019, 2171019, 2171019, 2453643, 2457739, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2515083, 2171019, 2171019, 2171019, 2171019, 2646155, 2670731, 2752651, 2756747, 2846859, 2961547, 2171019, 2998411, 2171019, 3010699, 2171019, 2171019, 2687115, 2748555, 2171019, 2171019, 2171019, 2924683, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 3121291, 2171019, 2171019, 2171019, 3170443, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2486272, 2215936, 2215936, 2506752, 3145867, 3158155, 3166347, 2387968, 2392064, 2215936, 2215936, 2433024, 2215936, 2461696, 2215936, 2215936, 2215936, 2510848, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2179072, 0, 0, 0, 0, 0, 553, 2170880, 2215936, 2215936, 2215936, 2215936, 2215936, 3121152, 2215936, 2215936, 3145728, 3158016, 3166208, 2388254, 2392350, 2171166, 2171166, 2433310, 2171166, 2461982, 2171166, 2171166, 2171166, 2511134, 2171166, 2171166, 0, 2171166, 2171166, 2580766, 2171166, 2605342, 2638110, 2171166, 2171166, 2171166, 2171166, 3031326, 2171166, 3055902, 2171166, 2171166, 2171166, 2171166, 3092766, 2171166, 2171166, 3125534, 2171166, 2171166, 2171166, 3162398, 2171166, 2171166, 3182878, 3186974, 2171166, 0, 0, 0, 2171019, 2171019, 2171019, 2171019, 3109003, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2215936, 2215936, 2215936, 2400256, 2215936, 2215936, 2215936, 2215936, 2171166, 2687262, 0, 0, 2748702, 2171166, 2171166, 0, 2171166, 2924830, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 2597150, 2171166, 2621726, 2171166, 2171166, 2642206, 2171166, 2171166, 2171166, 2171166, 3121438, 2171166, 2171166, 3146014, 3158302, 3166494, 2171019, 2420875, 2429067, 2171019, 2478219, 2171019, 2171019, 2171019, 2171019, 2547851, 2556043, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 3129483, 2215936, 2171019, 3141771, 2215936, 2420736, 2428928, 2215936, 2478080, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2646016, 2670592, 2752512, 2756608, 2846720, 2961408, 2215936, 2998272, 2215936, 3010560, 2215936, 2215936, 2215936, 3141632, 2171166, 2421022, 2429214, 2171166, 2478366, 2171166, 2171166, 2171166, 2171166, 0, 0, 2171166, 2171166, 2171166, 2171166, 2646302, 2670878, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 0, 45, 45, 45, 45, 45, 1405, 1406, 45, 45, 45, 45, 1409, 45, 45, 45, 45, 45, 1415, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1238, 45, 45, 45, 45, 67, 2752798, 2756894, 0, 2847006, 2961694, 2171166, 2998558, 2171166, 3010846, 2171166, 2171166, 2171166, 3141918, 2171019, 2171019, 2490507, 3129344, 2171166, 2171166, 2490654, 2171166, 2171166, 2171166, 0, 0, 2547998, 2556190, 2171166, 2171166, 2171166, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 45, 45, 167, 45, 45, 45, 45, 185, 187, 45, 45, 198, 45, 45, 0, 2171166, 2171166, 2171166, 2171166, 2171166, 2171166, 3129630, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2576523, 2171019, 2171019, 2171019, 2171019, 2171019, 2609291, 2171019, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 3002368, 2215936, 2215936, 2171166, 2171166, 2494750, 2171166, 2171166, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 45, 147, 2584576, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2171166, 2171166, 2171166, 2171166, 0, 0, 0, 2171166, 2171166, 2171166, 2171166, 0, 0, 0, 2171166, 2171166, 2171166, 3002654, 2171166, 2171166, 2171019, 2171019, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2175257, 0, 0, 2584862, 2171166, 2171166, 0, 0, 2171166, 2171166, 2171166, 2171166, 2171166, 2171019, 2441355, 2171019, 2527371, 2171019, 2601099, 2171019, 2850955, 2171019, 2171019, 2171019, 3022987, 2215936, 2441216, 2215936, 2527232, 2215936, 2600960, 2215936, 2850816, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2179072, 0, 0, 0, 0, 69632, 287, 2170880, 2215936, 3022848, 2171166, 2441502, 2171166, 2527518, 0, 0, 2171166, 2601246, 2171166, 0, 2851102, 2171166, 2171166, 2171166, 2171166, 2720030, 2744606, 2171166, 2171166, 2171166, 2834718, 2838814, 2171166, 2908446, 2171166, 2171166, 2937118, 3023134, 2171019, 2519179, 2171019, 2171019, 2171019, 2171019, 2171019, 2215936, 2519040, 2215936, 2215936, 2215936, 2215936, 2215936, 2171166, 2171166, 2171166, 3215646, 0, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2171019, 2486411, 2171019, 2171019, 2171019, 2629771, 2171019, 2171019, 2171019, 2171019, 2719883, 2744459, 2171019, 2171019, 2171019, 2834571, 2838667, 2171019, 2519326, 0, 0, 2171166, 2171166, 0, 2171166, 2171166, 2171166, 2396299, 2171019, 2171019, 2171019, 2171019, 3018891, 2396160, 2215936, 2215936, 2215936, 2215936, 3018752, 2396446, 0, 0, 2171166, 2171166, 2171166, 2171166, 3019038, 2171019, 2650251, 2965643, 2171019, 2215936, 2650112, 2965504, 2215936, 0, 0, 2171166, 2650398, 2965790, 2171166, 2551947, 2171019, 2551808, 2215936, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 144, 45, 45, 67, 67, 67, 67, 67, 228, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1929, 97, 97, 97, 97, 0, 0, 0, 2552094, 2171166, 2171019, 2215936, 0, 2171166, 2171019, 2215936, 0, 2171166, 2171019, 2215936, 0, 2171166, 2977931, 2977792, 2978078, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 1321, 97, 131072, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 0, 140, 0, 2379776, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2445312, 2170880, 2465792, 2473984, 2170880, 2170880, 2170880, 2584576, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2170880, 2170880, 2170880, 3162112, 2170880, 2170880, 3182592, 3186688, 2170880, 0, 140, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3002368, 2170880, 2170880, 2215936, 2215936, 2494464, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 3215360, 544, 0, 0, 0, 544, 0, 546, 0, 0, 0, 546, 0, 0, 2183168, 0, 0, 552, 0, 2170880, 2170880, 2170880, 2400256, 2170880, 2170880, 2170880, 0, 2170880, 2170880, 2170880, 0, 2170880, 2920448, 2170880, 2170880, 2170880, 2990080, 2170880, 2170880, 552, 0, 0, 0, 552, 0, 287, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2437120, 2170880, 2170880, 18, 0, 0, 0, 0, 0, 0, 0, 0, 2220032, 0, 0, 644, 0, 2215936, 2215936, 3170304, 544, 0, 546, 0, 552, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3198976, 2170880, 0, 0, 0, 140, 0, 0, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 249856, 110630, 114730, 106539, 0, 0, 32768, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 151640, 53264, 18, 18, 49172, 0, 57366, 0, 24, 24, 24, 0, 28, 28, 28, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2416640, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 253952, 110630, 114730, 106539, 0, 0, 32856, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 192512, 53264, 18, 18, 49172, 0, 57366, 0, 2232445, 184320, 2232445, 0, 2240641, 2240641, 184320, 2240641, 102432, 0, 0, 0, 221184, 2220032, 110630, 0, 0, 0, 114730, 106539, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3108864, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2215936, 0, 0, 0, 45056, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 0, 53264, 0, 18, 18, 24, 24, 0, 127, 127, 53264, 18, 49172, 258071, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 32768, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 204800, 53264, 18, 49172, 57366, 24, 27, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 0, 53264, 18, 49172, 57366, 24, 8192, 28, 33, 0, 33, 33, 33, 0, 0, 0, 53264, 18, 18, 49172, 0, 57366, 0, 24, 24, 24, 16384, 28, 28, 28, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 139, 2170880, 2170880, 2170880, 2416640, 67, 67, 37139, 37139, 24853, 24853, 0, 70179, 0, 0, 0, 65820, 65820, 369, 287, 97, 0, 0, 97, 97, 0, 97, 97, 97, 45, 2030, 45, 45, 45, 45, 67, 1573, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1699, 67, 67, 67, 67, 25403, 546, 70179, 0, 0, 66365, 66365, 552, 0, 97, 97, 97, 97, 97, 97, 97, 97, 1355, 97, 97, 97, 1358, 97, 97, 97, 641, 0, 0, 0, 925, 41606, 0, 0, 0, 0, 45, 45, 45, 45, 45, 45, 45, 1187, 45, 45, 45, 45, 45, 0, 1480, 0, 0, 0, 0, 1319, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 592, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1531, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1680, 45, 45, 45, 641, 0, 924, 0, 925, 41606, 0, 0, 0, 0, 45, 45, 45, 45, 45, 45, 1186, 45, 45, 45, 45, 45, 45, 67, 67, 37139, 37139, 24853, 24853, 0, 70179, 282, 0, 0, 65820, 65820, 369, 287, 97, 0, 0, 97, 97, 0, 97, 2028, 97, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1767, 67, 67, 67, 0, 0, 0, 0, 0, 0, 1612, 97, 97, 97, 97, 97, 97, 0, 1785, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 1790, 97, 0, 0, 2170880, 2170880, 3051520, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3170304, 241664, 2387968, 2392064, 2170880, 2170880, 2433024, 53264, 19, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 274432, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 270336, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 1134711, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 1126440, 1126440, 1126440, 0, 0, 1126400, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 36, 110630, 114730, 106539, 0, 0, 217088, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 94, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 96, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 24666, 53264, 18, 18, 49172, 0, 57366, 0, 24, 24, 24, 126, 28, 28, 28, 28, 102432, 53264, 122, 123, 49172, 0, 57366, 0, 24, 24, 24, 0, 28, 28, 28, 28, 102432, 2170880, 2170880, 4256099, 0, 0, 0, 0, 0, 0, 0, 0, 2220032, 0, 0, 0, 0, 0, 0, 0, 0, 1319, 0, 0, 0, 0, 97, 97, 97, 97, 97, 97, 97, 1109, 97, 97, 97, 97, 1113, 132, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 45, 146, 150, 45, 45, 45, 45, 45, 175, 45, 180, 45, 186, 45, 189, 45, 45, 203, 67, 256, 67, 67, 270, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 97, 97, 293, 297, 97, 97, 97, 97, 97, 322, 97, 327, 97, 333, 97, 0, 0, 97, 2026, 0, 2027, 97, 97, 45, 45, 45, 45, 45, 45, 67, 67, 67, 1685, 67, 67, 67, 67, 67, 67, 67, 1690, 67, 336, 97, 97, 350, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 356, 28, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 2170880, 2170880, 2170880, 2416640, 2424832, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2617344, 2170880, 45, 439, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 525, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 97, 97, 97, 622, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1524, 97, 97, 1527, 369, 648, 45, 45, 45, 45, 45, 45, 45, 45, 45, 659, 45, 45, 45, 45, 408, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1239, 45, 45, 45, 67, 729, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 762, 67, 746, 67, 67, 67, 67, 67, 67, 67, 67, 67, 759, 67, 67, 67, 67, 0, 0, 0, 1477, 0, 1086, 0, 0, 0, 1479, 0, 1090, 67, 67, 796, 67, 67, 799, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1291, 67, 67, 67, 811, 67, 67, 67, 67, 67, 816, 67, 67, 67, 67, 67, 67, 67, 37689, 544, 25403, 546, 70179, 0, 0, 66365, 66365, 552, 833, 97, 97, 97, 97, 97, 97, 97, 97, 1380, 0, 0, 0, 45, 45, 45, 45, 45, 1185, 45, 45, 45, 45, 45, 45, 45, 386, 45, 45, 45, 45, 45, 45, 45, 45, 1810, 45, 45, 45, 45, 45, 45, 67, 97, 97, 844, 97, 97, 97, 97, 97, 97, 97, 97, 97, 857, 97, 97, 97, 0, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 45, 45, 45, 97, 97, 97, 894, 97, 97, 897, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 0, 0, 1382, 45, 45, 45, 97, 909, 97, 97, 97, 97, 97, 914, 97, 97, 97, 97, 97, 97, 97, 923, 67, 67, 1079, 67, 67, 67, 67, 67, 37689, 1085, 25403, 1089, 66365, 1093, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 45, 148, 1114, 97, 97, 97, 97, 97, 97, 1122, 97, 97, 97, 97, 97, 97, 97, 97, 97, 606, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1173, 97, 97, 97, 97, 97, 12288, 0, 925, 0, 1179, 0, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 145, 45, 45, 67, 67, 67, 67, 67, 1762, 67, 67, 67, 1766, 67, 67, 67, 67, 67, 67, 528, 67, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 0, 1934, 67, 67, 1255, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1035, 67, 67, 67, 67, 67, 67, 1297, 67, 67, 67, 67, 67, 67, 0, 0, 0, 0, 0, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1111, 97, 97, 97, 97, 97, 97, 1327, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 33344, 97, 97, 97, 1335, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 97, 97, 1377, 97, 97, 97, 97, 97, 97, 0, 1179, 0, 45, 45, 45, 45, 670, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 430, 45, 45, 45, 45, 67, 67, 1438, 67, 67, 1442, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1592, 67, 67, 67, 1451, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1458, 67, 67, 67, 67, 0, 0, 1305, 0, 0, 0, 0, 0, 1311, 0, 0, 0, 1317, 0, 0, 0, 0, 0, 0, 0, 97, 97, 1322, 97, 97, 1491, 97, 97, 1495, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1551, 45, 1553, 45, 1504, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1513, 97, 97, 97, 97, 0, 45, 45, 45, 45, 1536, 45, 45, 45, 45, 1540, 45, 67, 67, 67, 67, 67, 1585, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1700, 67, 67, 67, 97, 1648, 97, 97, 97, 97, 97, 97, 97, 97, 0, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1541, 0, 97, 97, 97, 97, 0, 1940, 0, 97, 97, 97, 97, 97, 97, 45, 45, 2011, 45, 45, 45, 2015, 67, 67, 2017, 67, 67, 67, 2021, 97, 67, 67, 812, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 37689, 544, 97, 97, 97, 910, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 923, 0, 0, 0, 45, 45, 45, 45, 1184, 45, 45, 45, 45, 1188, 45, 45, 45, 45, 1414, 45, 45, 45, 1417, 45, 1419, 45, 45, 45, 45, 45, 443, 45, 45, 45, 45, 45, 45, 453, 45, 45, 67, 67, 67, 67, 1244, 67, 67, 67, 67, 1248, 67, 67, 67, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 282, 41098, 65820, 97, 1324, 97, 97, 97, 97, 1328, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 0, 930, 45, 45, 45, 45, 97, 97, 97, 97, 1378, 97, 97, 97, 97, 0, 1179, 0, 45, 45, 45, 45, 671, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 975, 45, 45, 45, 45, 67, 67, 1923, 67, 1925, 67, 67, 1927, 67, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 1985, 45, 45, 45, 45, 45, 45, 1560, 45, 45, 45, 45, 45, 45, 45, 45, 45, 946, 45, 45, 950, 45, 45, 45, 0, 97, 97, 97, 1939, 0, 0, 0, 97, 1943, 97, 97, 1945, 97, 45, 45, 45, 669, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 990, 45, 45, 45, 67, 257, 67, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 337, 97, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 356, 28, 28, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 370, 2170880, 2170880, 2170880, 2416640, 401, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 459, 461, 67, 67, 67, 67, 67, 67, 67, 67, 475, 67, 480, 67, 67, 67, 67, 67, 67, 1054, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1698, 67, 67, 67, 67, 67, 484, 67, 67, 487, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1459, 67, 67, 97, 556, 558, 97, 97, 97, 97, 97, 97, 97, 97, 572, 97, 577, 97, 97, 0, 0, 1896, 97, 97, 97, 97, 97, 97, 1903, 45, 45, 45, 45, 983, 45, 45, 45, 45, 988, 45, 45, 45, 45, 45, 45, 1195, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1549, 45, 45, 45, 45, 45, 581, 97, 97, 584, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1153, 97, 97, 369, 0, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 662, 45, 45, 45, 684, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1004, 45, 45, 45, 67, 67, 67, 749, 67, 67, 67, 67, 67, 67, 67, 67, 67, 761, 67, 67, 67, 67, 67, 67, 1068, 67, 67, 67, 1071, 67, 67, 67, 67, 1076, 794, 795, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 0, 544, 97, 97, 97, 97, 847, 97, 97, 97, 97, 97, 97, 97, 97, 97, 859, 97, 0, 0, 2025, 97, 20480, 97, 97, 2029, 45, 45, 45, 45, 45, 45, 67, 67, 67, 1575, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1775, 67, 67, 67, 97, 97, 97, 97, 892, 893, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1515, 97, 993, 994, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 992, 67, 67, 67, 1284, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1607, 67, 67, 97, 1364, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 596, 97, 45, 1556, 1557, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 696, 45, 1596, 1597, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 499, 67, 97, 97, 97, 1621, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1346, 97, 97, 97, 97, 1740, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1678, 45, 45, 45, 45, 45, 67, 97, 97, 97, 97, 97, 97, 1836, 0, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 1984, 97, 45, 45, 45, 45, 45, 45, 1808, 45, 45, 45, 45, 45, 45, 45, 45, 67, 739, 67, 67, 67, 67, 67, 744, 45, 45, 1909, 45, 45, 45, 45, 45, 45, 45, 67, 1917, 67, 1918, 67, 67, 67, 67, 67, 67, 1247, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 532, 67, 67, 67, 67, 67, 67, 1922, 67, 67, 67, 67, 67, 67, 67, 97, 1930, 97, 1931, 97, 0, 0, 97, 97, 0, 97, 97, 97, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 1576, 67, 67, 67, 67, 1580, 67, 67, 0, 97, 97, 1938, 97, 0, 0, 0, 97, 97, 97, 97, 97, 97, 45, 45, 45, 699, 45, 45, 45, 704, 45, 45, 45, 45, 45, 45, 45, 45, 987, 45, 45, 45, 45, 45, 45, 45, 67, 67, 97, 97, 97, 97, 0, 0, 97, 97, 97, 2006, 97, 97, 97, 97, 0, 45, 1533, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1416, 45, 45, 45, 45, 45, 45, 45, 45, 722, 723, 45, 45, 45, 45, 45, 45, 2045, 67, 67, 67, 2047, 0, 0, 97, 97, 97, 2051, 45, 45, 67, 67, 0, 0, 0, 0, 925, 41606, 0, 0, 0, 0, 45, 45, 45, 45, 45, 45, 409, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1957, 45, 67, 67, 67, 67, 67, 1836, 97, 97, 45, 67, 0, 97, 45, 67, 0, 97, 45, 67, 0, 97, 45, 45, 67, 67, 67, 1761, 67, 67, 67, 1764, 67, 67, 67, 67, 67, 67, 67, 494, 67, 67, 67, 67, 67, 67, 67, 67, 67, 787, 67, 67, 67, 67, 67, 67, 45, 45, 420, 45, 45, 422, 45, 45, 425, 45, 45, 45, 45, 45, 45, 45, 387, 45, 45, 45, 45, 397, 45, 45, 45, 67, 460, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 515, 67, 485, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 498, 67, 67, 67, 67, 67, 97, 0, 2039, 97, 97, 97, 97, 97, 45, 45, 45, 45, 1426, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1689, 67, 67, 67, 97, 557, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 612, 97, 582, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 595, 97, 97, 97, 97, 97, 896, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 885, 97, 97, 97, 97, 97, 45, 939, 45, 45, 45, 45, 943, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1916, 67, 67, 67, 67, 67, 45, 67, 67, 67, 67, 67, 67, 67, 1015, 67, 67, 67, 67, 1019, 67, 67, 67, 67, 67, 67, 1271, 67, 67, 67, 67, 67, 67, 1277, 67, 67, 67, 67, 67, 67, 1287, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 804, 67, 67, 67, 67, 67, 1077, 67, 67, 67, 67, 67, 67, 67, 37689, 0, 25403, 0, 66365, 0, 0, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2437120, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2543616, 2170880, 2170880, 2170880, 2170880, 2170880, 2629632, 1169, 97, 1171, 97, 97, 97, 97, 97, 97, 97, 12288, 0, 925, 0, 1179, 0, 0, 0, 0, 925, 41606, 0, 0, 0, 0, 45, 45, 45, 45, 936, 45, 45, 67, 67, 214, 67, 220, 67, 67, 233, 67, 243, 67, 248, 67, 67, 67, 67, 67, 67, 1298, 67, 67, 67, 67, 0, 0, 0, 0, 0, 0, 97, 97, 97, 97, 97, 1617, 97, 0, 0, 0, 45, 45, 45, 1183, 45, 45, 45, 45, 45, 45, 45, 45, 45, 393, 45, 45, 45, 45, 45, 45, 67, 67, 1243, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1074, 67, 67, 1281, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 776, 1323, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 907, 45, 1412, 45, 45, 45, 45, 45, 45, 45, 1418, 45, 45, 45, 45, 45, 45, 686, 45, 45, 45, 690, 45, 45, 695, 45, 45, 67, 67, 67, 67, 67, 1465, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 1712, 97, 97, 97, 97, 1741, 97, 97, 97, 45, 45, 45, 45, 45, 45, 45, 45, 45, 426, 45, 45, 45, 45, 45, 45, 67, 67, 67, 1924, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 0, 0, 97, 97, 1983, 97, 97, 45, 45, 1987, 45, 1988, 45, 0, 97, 97, 97, 97, 0, 0, 0, 1942, 97, 97, 97, 97, 97, 45, 45, 45, 700, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 711, 45, 45, 153, 45, 45, 166, 45, 176, 45, 181, 45, 45, 188, 191, 196, 45, 204, 255, 258, 263, 67, 271, 67, 67, 0, 37139, 24853, 0, 0, 0, 282, 41098, 65820, 97, 97, 97, 294, 97, 300, 97, 97, 313, 97, 323, 97, 328, 97, 97, 335, 338, 343, 97, 351, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 356, 28, 28, 0, 0, 0, 0, 0, 0, 0, 0, 41098, 0, 140, 45, 45, 45, 45, 1404, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1411, 67, 67, 486, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1251, 67, 67, 501, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 513, 67, 67, 67, 67, 67, 67, 1443, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1263, 67, 67, 67, 67, 67, 97, 97, 583, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1526, 97, 598, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 610, 97, 97, 0, 97, 97, 1796, 97, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 1744, 45, 45, 45, 369, 0, 651, 45, 653, 45, 654, 45, 656, 45, 45, 45, 660, 45, 45, 45, 45, 1558, 45, 45, 45, 45, 45, 45, 45, 45, 1566, 45, 45, 681, 45, 683, 45, 45, 45, 45, 45, 45, 45, 45, 691, 692, 694, 45, 45, 45, 716, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 709, 45, 45, 712, 45, 714, 45, 45, 45, 718, 45, 45, 45, 45, 45, 45, 45, 726, 45, 45, 45, 733, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1691, 67, 67, 747, 67, 67, 67, 67, 67, 67, 67, 67, 67, 760, 67, 67, 67, 0, 0, 0, 0, 0, 0, 97, 1613, 97, 97, 97, 97, 97, 97, 1509, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 1179, 0, 45, 45, 45, 45, 67, 764, 67, 67, 67, 67, 768, 67, 770, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 0, 0, 0, 1977, 67, 778, 779, 781, 67, 67, 67, 67, 67, 67, 788, 789, 67, 67, 792, 793, 67, 67, 67, 813, 67, 67, 67, 67, 67, 67, 67, 67, 67, 824, 37689, 544, 25403, 546, 70179, 0, 0, 66365, 66365, 552, 0, 836, 97, 838, 97, 839, 97, 841, 97, 97, 97, 845, 97, 97, 97, 97, 97, 97, 97, 97, 97, 858, 97, 97, 0, 1728, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 45, 1802, 45, 97, 97, 862, 97, 97, 97, 97, 866, 97, 868, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 1788, 97, 97, 97, 0, 0, 97, 97, 876, 877, 879, 97, 97, 97, 97, 97, 97, 886, 887, 97, 97, 890, 891, 97, 97, 97, 97, 97, 97, 97, 899, 97, 97, 97, 903, 97, 97, 97, 0, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 1646, 97, 97, 97, 97, 911, 97, 97, 97, 97, 97, 97, 97, 97, 97, 922, 923, 45, 955, 45, 957, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 195, 45, 45, 45, 45, 45, 981, 982, 45, 45, 45, 45, 45, 45, 989, 45, 45, 45, 45, 45, 170, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 411, 45, 45, 45, 45, 45, 67, 1023, 67, 67, 67, 67, 67, 67, 1031, 67, 1033, 67, 67, 67, 67, 67, 67, 67, 817, 819, 67, 67, 67, 67, 67, 37689, 544, 67, 1065, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 516, 67, 67, 1078, 67, 67, 1081, 1082, 67, 67, 37689, 0, 25403, 0, 66365, 0, 0, 0, 0, 0, 0, 0, 0, 2171166, 2171166, 2171166, 2171166, 2171166, 2437406, 2171166, 2171166, 97, 1115, 97, 1117, 97, 97, 97, 97, 97, 97, 1125, 97, 1127, 97, 97, 97, 0, 97, 97, 97, 0, 97, 97, 97, 97, 1644, 97, 97, 97, 0, 97, 97, 97, 0, 97, 97, 1642, 97, 97, 97, 97, 97, 97, 625, 97, 97, 97, 97, 97, 97, 97, 97, 97, 316, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1159, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1502, 97, 97, 97, 97, 97, 1172, 97, 97, 1175, 1176, 97, 97, 12288, 0, 925, 0, 1179, 0, 0, 0, 0, 925, 41606, 0, 0, 0, 0, 45, 45, 45, 935, 45, 45, 45, 1233, 45, 45, 45, 1236, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 1873, 67, 67, 45, 45, 1218, 45, 45, 45, 1223, 45, 45, 45, 45, 45, 45, 45, 1230, 45, 45, 67, 67, 215, 219, 222, 67, 230, 67, 67, 244, 246, 249, 67, 67, 67, 67, 67, 67, 1882, 97, 97, 97, 97, 0, 0, 0, 97, 97, 97, 97, 97, 97, 45, 1904, 45, 1905, 45, 67, 67, 67, 67, 67, 1258, 67, 1260, 67, 67, 67, 67, 67, 67, 67, 67, 67, 495, 67, 67, 67, 67, 67, 67, 67, 67, 1283, 67, 67, 67, 67, 67, 67, 67, 1290, 67, 67, 67, 67, 67, 67, 67, 818, 67, 67, 67, 67, 67, 67, 37689, 544, 67, 67, 1295, 67, 67, 67, 67, 67, 67, 67, 67, 0, 0, 0, 0, 0, 0, 2174976, 0, 0, 97, 97, 97, 1326, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1514, 97, 97, 97, 97, 97, 1338, 97, 1340, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1500, 97, 97, 1503, 97, 1363, 97, 97, 97, 97, 97, 97, 97, 1370, 97, 97, 97, 97, 97, 97, 97, 563, 97, 97, 97, 97, 97, 97, 578, 97, 1375, 97, 97, 97, 97, 97, 97, 97, 97, 0, 1179, 0, 45, 45, 45, 45, 685, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1003, 45, 45, 45, 45, 67, 67, 67, 1463, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1778, 97, 97, 97, 97, 97, 1518, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 609, 97, 97, 97, 45, 1542, 45, 45, 45, 45, 45, 45, 45, 1548, 45, 45, 45, 45, 45, 1554, 45, 1570, 1571, 45, 67, 67, 67, 67, 67, 67, 1578, 67, 67, 67, 67, 67, 67, 67, 1055, 67, 67, 67, 67, 67, 1061, 67, 67, 1582, 67, 67, 67, 67, 67, 67, 67, 1588, 67, 67, 67, 67, 67, 1594, 67, 67, 67, 67, 67, 97, 2038, 0, 97, 97, 97, 97, 97, 2044, 45, 45, 45, 995, 45, 45, 45, 45, 1000, 45, 45, 45, 45, 45, 45, 45, 1809, 45, 1811, 45, 45, 45, 45, 45, 67, 1610, 1611, 67, 1476, 0, 1478, 0, 1480, 0, 97, 97, 97, 97, 97, 97, 1618, 1647, 1649, 97, 97, 97, 1652, 97, 1654, 1655, 97, 0, 45, 45, 45, 1658, 45, 45, 67, 67, 216, 67, 67, 67, 67, 234, 67, 67, 67, 67, 252, 254, 1845, 97, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 45, 45, 945, 45, 947, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 1881, 97, 97, 97, 97, 97, 0, 0, 0, 97, 97, 97, 97, 97, 1902, 45, 45, 45, 45, 45, 45, 1908, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1921, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 0, 0, 0, 97, 97, 0, 97, 1937, 97, 97, 1940, 0, 0, 97, 97, 97, 97, 97, 97, 1947, 1948, 1949, 45, 45, 45, 1952, 45, 1954, 45, 45, 45, 45, 1959, 1960, 1961, 67, 67, 67, 67, 67, 67, 1455, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 757, 67, 67, 67, 67, 67, 67, 1964, 67, 1966, 67, 67, 67, 67, 1971, 1972, 1973, 97, 0, 0, 0, 97, 97, 1104, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 884, 97, 97, 97, 889, 97, 97, 1978, 97, 0, 0, 1981, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 736, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1018, 67, 67, 67, 45, 67, 67, 67, 67, 0, 2049, 97, 97, 97, 97, 45, 45, 67, 67, 0, 0, 0, 0, 925, 41606, 0, 0, 0, 0, 45, 933, 45, 45, 45, 45, 1234, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 97, 97, 288, 97, 97, 97, 97, 97, 97, 317, 97, 97, 97, 97, 97, 97, 0, 0, 97, 1787, 97, 97, 97, 97, 0, 0, 45, 45, 378, 45, 45, 45, 45, 45, 390, 45, 45, 45, 45, 45, 45, 45, 424, 45, 45, 45, 431, 433, 45, 45, 45, 67, 1050, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 518, 67, 97, 97, 97, 1144, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 632, 97, 97, 97, 97, 97, 97, 97, 1367, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 855, 97, 97, 97, 97, 67, 97, 97, 97, 97, 97, 97, 1837, 0, 97, 97, 97, 97, 97, 0, 0, 0, 1897, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 1208, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 724, 45, 45, 45, 45, 45, 97, 2010, 45, 45, 45, 45, 45, 45, 2016, 67, 67, 67, 67, 67, 67, 2022, 45, 2046, 67, 67, 67, 0, 0, 2050, 97, 97, 97, 45, 45, 67, 67, 0, 0, 0, 0, 925, 41606, 0, 0, 0, 0, 932, 45, 45, 45, 45, 45, 1222, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1227, 45, 45, 45, 45, 45, 133, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 45, 45, 701, 702, 45, 45, 705, 706, 45, 45, 45, 45, 45, 45, 703, 45, 45, 45, 45, 45, 45, 45, 45, 45, 719, 45, 45, 45, 45, 45, 725, 45, 45, 45, 369, 649, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1216, 25403, 546, 70179, 0, 0, 66365, 66365, 552, 834, 97, 97, 97, 97, 97, 97, 97, 1342, 97, 97, 97, 97, 97, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 1799, 97, 97, 45, 45, 45, 1569, 45, 45, 45, 1572, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 0, 0, 0, 1306, 0, 67, 67, 67, 1598, 67, 67, 67, 67, 67, 67, 67, 67, 1606, 67, 67, 1609, 97, 97, 97, 1650, 97, 97, 1653, 97, 97, 97, 0, 45, 45, 1657, 45, 45, 45, 1206, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1421, 45, 45, 45, 1703, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 1711, 97, 97, 0, 1895, 0, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 958, 45, 960, 45, 45, 45, 45, 45, 45, 45, 45, 1913, 45, 45, 1915, 67, 67, 67, 67, 67, 67, 67, 466, 67, 67, 67, 67, 67, 67, 481, 67, 45, 1749, 45, 45, 45, 45, 45, 45, 45, 45, 1755, 45, 45, 45, 45, 45, 173, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 974, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 1773, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 1886, 0, 0, 0, 97, 97, 67, 2035, 2036, 67, 67, 97, 0, 0, 97, 2041, 2042, 97, 97, 45, 45, 45, 45, 1662, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1397, 45, 45, 45, 45, 151, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 437, 205, 45, 67, 67, 67, 218, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1047, 67, 67, 67, 67, 97, 97, 97, 97, 298, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 870, 97, 97, 97, 97, 97, 97, 97, 97, 352, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 0, 0, 0, 0, 0, 0, 365, 0, 41098, 0, 140, 45, 45, 45, 45, 45, 1427, 45, 45, 67, 67, 67, 67, 67, 67, 67, 1435, 520, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1037, 617, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 923, 45, 1232, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 1919, 67, 1759, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1021, 45, 154, 45, 162, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 964, 45, 45, 45, 206, 45, 67, 67, 67, 67, 221, 67, 229, 67, 67, 67, 67, 67, 67, 67, 67, 530, 67, 67, 67, 67, 67, 67, 67, 67, 755, 67, 67, 67, 67, 67, 67, 67, 67, 785, 67, 67, 67, 67, 67, 67, 67, 67, 802, 67, 67, 67, 807, 67, 67, 67, 97, 97, 97, 97, 353, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 0, 0, 0, 0, 0, 0, 366, 0, 0, 0, 140, 2170880, 2170880, 2170880, 2416640, 402, 45, 45, 45, 45, 45, 45, 45, 410, 45, 45, 45, 45, 45, 45, 45, 674, 45, 45, 45, 45, 45, 45, 45, 45, 389, 45, 394, 45, 45, 398, 45, 45, 45, 45, 441, 45, 45, 45, 45, 45, 447, 45, 45, 45, 454, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1768, 67, 67, 67, 67, 67, 488, 67, 67, 67, 67, 67, 67, 67, 496, 67, 67, 67, 67, 67, 67, 67, 1774, 67, 67, 67, 67, 67, 97, 97, 97, 97, 0, 0, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 67, 67, 523, 67, 67, 527, 67, 67, 67, 67, 67, 533, 67, 67, 67, 540, 97, 97, 97, 585, 97, 97, 97, 97, 97, 97, 97, 593, 97, 97, 97, 97, 97, 97, 1784, 0, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 97, 97, 0, 0, 0, 18, 18, 24, 24, 0, 28, 28, 97, 97, 620, 97, 97, 624, 97, 97, 97, 97, 97, 630, 97, 97, 97, 637, 713, 45, 45, 45, 45, 45, 45, 721, 45, 45, 45, 45, 45, 45, 45, 45, 1197, 45, 45, 45, 45, 45, 45, 45, 45, 730, 732, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1581, 67, 45, 67, 67, 67, 67, 1012, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1059, 67, 67, 67, 67, 67, 1024, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 775, 67, 67, 67, 67, 1066, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 479, 67, 67, 67, 67, 67, 67, 1080, 67, 67, 67, 67, 37689, 0, 25403, 0, 66365, 0, 0, 0, 0, 0, 0, 0, 287, 0, 0, 0, 287, 0, 2379776, 2170880, 2170880, 97, 97, 97, 1118, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 920, 97, 97, 0, 0, 0, 0, 45, 1181, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 432, 45, 45, 45, 45, 45, 45, 1219, 45, 45, 45, 45, 45, 45, 1226, 45, 45, 45, 45, 45, 45, 959, 45, 45, 45, 45, 45, 45, 45, 45, 45, 184, 45, 45, 45, 45, 202, 45, 1241, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1266, 67, 1268, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1279, 67, 67, 67, 67, 67, 272, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 67, 67, 67, 67, 67, 1286, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1293, 67, 67, 67, 1296, 67, 67, 67, 67, 67, 67, 67, 0, 0, 0, 0, 0, 281, 94, 0, 0, 97, 97, 97, 1366, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1373, 97, 97, 18, 0, 139621, 0, 0, 0, 0, 0, 0, 364, 0, 0, 367, 0, 97, 1376, 97, 97, 97, 97, 97, 97, 97, 0, 0, 0, 45, 45, 1384, 45, 45, 67, 208, 67, 67, 67, 67, 67, 67, 237, 67, 67, 67, 67, 67, 67, 67, 1069, 1070, 67, 67, 67, 67, 67, 67, 67, 0, 37140, 24854, 0, 0, 0, 0, 41098, 65821, 45, 1423, 45, 45, 45, 45, 45, 45, 67, 67, 1431, 67, 67, 67, 67, 67, 67, 67, 1083, 37689, 0, 25403, 0, 66365, 0, 0, 0, 1436, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1830, 67, 1452, 1453, 67, 67, 67, 67, 1456, 67, 67, 67, 67, 67, 67, 67, 67, 67, 771, 67, 67, 67, 67, 67, 67, 1461, 67, 67, 67, 1464, 67, 1466, 67, 67, 67, 67, 67, 67, 1470, 67, 67, 67, 67, 67, 67, 1587, 67, 67, 67, 67, 67, 67, 67, 67, 1595, 1489, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1129, 97, 1505, 1506, 97, 97, 97, 97, 1510, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1163, 1164, 97, 97, 97, 97, 97, 1516, 97, 97, 97, 1519, 97, 1521, 97, 97, 97, 97, 97, 97, 1525, 97, 97, 18, 0, 139621, 0, 0, 0, 0, 0, 0, 364, 0, 0, 367, 41606, 67, 67, 67, 67, 67, 1586, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1276, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1600, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1301, 0, 0, 0, 1307, 97, 97, 1620, 97, 97, 97, 97, 97, 97, 97, 1627, 97, 97, 97, 97, 97, 97, 913, 97, 97, 97, 97, 919, 97, 97, 97, 0, 97, 97, 97, 1781, 97, 97, 0, 0, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 97, 97, 0, 1792, 1860, 45, 1862, 1863, 45, 1865, 45, 67, 67, 67, 67, 67, 67, 67, 67, 1875, 67, 1877, 1878, 67, 1880, 67, 97, 97, 97, 97, 97, 1887, 0, 1889, 97, 97, 18, 0, 139621, 0, 0, 0, 0, 0, 0, 364, 237568, 0, 367, 0, 97, 1893, 0, 0, 0, 97, 1898, 1899, 97, 1901, 97, 45, 45, 45, 45, 45, 2014, 45, 67, 67, 67, 67, 67, 2020, 67, 97, 1989, 45, 1990, 45, 45, 45, 67, 67, 67, 67, 67, 67, 1996, 67, 1997, 67, 67, 67, 67, 67, 273, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 67, 67, 97, 97, 97, 97, 0, 0, 97, 97, 2005, 0, 97, 2007, 97, 97, 18, 0, 139621, 0, 0, 0, 642, 0, 133, 364, 0, 0, 367, 41606, 0, 97, 97, 2056, 2057, 0, 2059, 45, 67, 0, 97, 45, 67, 0, 97, 45, 45, 67, 209, 67, 67, 67, 223, 67, 67, 67, 67, 67, 67, 67, 67, 67, 786, 67, 67, 67, 791, 67, 67, 45, 45, 940, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 727, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 1016, 67, 67, 67, 67, 67, 67, 67, 67, 37689, 0, 25403, 0, 66365, 0, 0, 0, 133, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 142, 45, 45, 67, 210, 67, 67, 67, 225, 67, 67, 239, 67, 67, 67, 250, 67, 67, 67, 67, 67, 464, 67, 67, 67, 67, 67, 476, 67, 67, 67, 67, 67, 67, 67, 1709, 67, 67, 67, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 97, 1843, 0, 67, 259, 67, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 97, 289, 97, 97, 97, 303, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 901, 97, 97, 97, 97, 97, 339, 97, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 0, 358, 0, 0, 0, 0, 0, 0, 41098, 0, 140, 45, 45, 45, 45, 45, 1953, 45, 1955, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 1687, 1688, 67, 67, 67, 67, 45, 45, 405, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1203, 45, 458, 67, 67, 67, 67, 67, 67, 67, 67, 67, 470, 477, 67, 67, 67, 67, 67, 67, 67, 1970, 97, 97, 97, 1974, 0, 0, 0, 97, 1103, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1372, 97, 97, 97, 97, 67, 522, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 536, 67, 67, 67, 67, 67, 67, 1696, 67, 67, 67, 67, 67, 67, 67, 1701, 67, 555, 97, 97, 97, 97, 97, 97, 97, 97, 97, 567, 574, 97, 97, 97, 97, 97, 301, 97, 309, 97, 97, 97, 97, 97, 97, 97, 97, 97, 900, 97, 97, 97, 905, 97, 97, 97, 619, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 633, 97, 97, 18, 0, 139621, 0, 0, 362, 0, 0, 0, 364, 0, 0, 367, 41606, 369, 649, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 663, 664, 67, 67, 67, 67, 750, 751, 67, 67, 67, 67, 758, 67, 67, 67, 67, 67, 67, 67, 1272, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1057, 1058, 67, 67, 67, 67, 67, 67, 67, 67, 797, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 512, 67, 67, 67, 97, 97, 97, 97, 895, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 902, 97, 97, 97, 97, 67, 67, 1051, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1062, 67, 67, 67, 67, 67, 491, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1302, 0, 0, 0, 1308, 97, 97, 97, 97, 1145, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1139, 97, 97, 97, 97, 1156, 97, 97, 97, 97, 97, 97, 1161, 97, 97, 97, 97, 97, 1166, 97, 97, 18, 640, 139621, 0, 641, 0, 0, 0, 0, 364, 0, 0, 367, 41606, 67, 67, 67, 67, 1257, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 0, 0, 1305, 0, 0, 97, 97, 1337, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1630, 97, 67, 1474, 67, 67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2380062, 2171166, 2171166, 97, 1529, 97, 97, 0, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1228, 45, 45, 45, 45, 67, 67, 67, 67, 1707, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 0, 0, 0, 97, 1891, 1739, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1198, 45, 1200, 45, 45, 45, 45, 97, 97, 1894, 0, 0, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 672, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1420, 45, 45, 45, 45, 67, 67, 1965, 67, 1967, 67, 67, 67, 97, 97, 97, 97, 0, 1976, 0, 97, 97, 45, 67, 0, 97, 45, 67, 0, 97, 45, 67, 0, 97, 45, 97, 97, 1979, 0, 0, 97, 1982, 97, 97, 97, 1986, 45, 45, 45, 45, 45, 735, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1770, 67, 67, 2000, 97, 97, 97, 2002, 0, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 1798, 97, 97, 97, 45, 45, 45, 2034, 67, 67, 67, 67, 97, 0, 0, 2040, 97, 97, 97, 97, 45, 45, 45, 45, 1752, 45, 45, 45, 1753, 1754, 45, 45, 45, 45, 45, 45, 383, 45, 45, 45, 45, 45, 45, 45, 45, 45, 675, 45, 45, 45, 45, 45, 45, 438, 45, 45, 45, 45, 45, 445, 45, 45, 45, 45, 45, 45, 45, 45, 67, 1430, 67, 67, 67, 67, 67, 67, 67, 67, 67, 524, 67, 67, 67, 67, 67, 531, 67, 67, 67, 67, 67, 67, 67, 67, 37689, 0, 25403, 0, 66365, 0, 0, 1096, 97, 97, 97, 621, 97, 97, 97, 97, 97, 628, 97, 97, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 356, 28, 28, 665, 45, 45, 45, 45, 45, 45, 45, 45, 45, 676, 45, 45, 45, 45, 45, 942, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 707, 708, 45, 45, 45, 45, 763, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 809, 810, 67, 67, 67, 67, 783, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 0, 1303, 0, 0, 0, 97, 861, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 613, 97, 45, 45, 956, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1215, 45, 67, 67, 67, 67, 1027, 67, 67, 67, 67, 1032, 67, 67, 67, 67, 67, 67, 67, 67, 37689, 0, 25403, 0, 66365, 0, 0, 1097, 1064, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1075, 67, 1098, 0, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 331, 97, 97, 97, 97, 1158, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 594, 97, 97, 1309, 0, 0, 0, 1315, 0, 0, 0, 0, 0, 0, 0, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1374, 97, 45, 45, 1543, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1240, 67, 67, 1583, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1252, 67, 97, 97, 97, 1635, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 1800, 97, 45, 45, 45, 97, 97, 1793, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 45, 45, 45, 1743, 45, 45, 45, 1746, 45, 0, 97, 97, 97, 97, 97, 1851, 97, 45, 45, 45, 45, 1856, 45, 45, 45, 45, 1864, 45, 45, 67, 67, 1869, 67, 67, 67, 67, 1874, 67, 0, 97, 97, 45, 67, 2058, 97, 45, 67, 0, 97, 45, 67, 0, 97, 45, 45, 67, 211, 67, 67, 67, 67, 67, 67, 240, 67, 67, 67, 67, 67, 67, 67, 1444, 67, 67, 67, 67, 67, 67, 67, 67, 67, 509, 67, 67, 67, 67, 67, 67, 67, 67, 67, 268, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 97, 290, 97, 97, 97, 305, 97, 97, 319, 97, 97, 97, 330, 97, 97, 18, 640, 139621, 0, 641, 0, 0, 0, 0, 364, 0, 643, 367, 41606, 97, 97, 348, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 139621, 0, 0, 0, 0, 364, 0, 367, 41098, 369, 140, 45, 45, 45, 45, 380, 45, 45, 45, 45, 45, 45, 395, 45, 45, 45, 400, 369, 0, 45, 45, 45, 45, 45, 45, 45, 45, 658, 45, 45, 45, 45, 45, 972, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 427, 45, 45, 45, 45, 45, 745, 67, 67, 67, 67, 67, 67, 67, 67, 756, 67, 67, 67, 67, 67, 67, 67, 67, 37689, 1086, 25403, 1090, 66365, 1094, 0, 0, 97, 843, 97, 97, 97, 97, 97, 97, 97, 97, 854, 97, 97, 97, 97, 97, 97, 1121, 97, 97, 97, 97, 1126, 97, 97, 97, 97, 45, 980, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1400, 45, 67, 67, 67, 1011, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 0, 1304, 0, 0, 0, 1190, 45, 45, 1193, 1194, 45, 45, 45, 45, 45, 1199, 45, 1201, 45, 45, 45, 45, 1911, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 1579, 67, 67, 67, 67, 45, 1205, 45, 45, 45, 45, 45, 45, 45, 45, 1211, 45, 45, 45, 45, 45, 984, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1550, 45, 45, 45, 45, 45, 1217, 45, 45, 45, 45, 45, 45, 1225, 45, 45, 45, 45, 1229, 45, 45, 45, 1388, 45, 45, 45, 45, 45, 45, 1396, 45, 45, 45, 45, 45, 444, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 1574, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1590, 67, 67, 67, 67, 67, 1254, 67, 67, 67, 67, 67, 1259, 67, 1261, 67, 67, 67, 67, 1265, 67, 67, 67, 67, 67, 67, 1708, 67, 67, 67, 67, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 97, 0, 0, 67, 67, 67, 67, 1285, 67, 67, 67, 67, 1289, 67, 67, 67, 67, 67, 67, 67, 67, 37689, 1087, 25403, 1091, 66365, 1095, 0, 0, 97, 97, 97, 97, 1339, 97, 1341, 97, 97, 97, 97, 1345, 97, 97, 97, 97, 97, 561, 97, 97, 97, 97, 97, 573, 97, 97, 97, 97, 97, 97, 1717, 97, 0, 97, 97, 97, 97, 97, 97, 97, 591, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1329, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1351, 97, 97, 97, 97, 97, 97, 1357, 97, 97, 97, 97, 97, 588, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 568, 97, 97, 97, 97, 97, 97, 97, 1365, 97, 97, 97, 97, 1369, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1356, 97, 97, 97, 97, 97, 97, 45, 45, 1403, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1399, 45, 45, 45, 1413, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1669, 45, 1422, 45, 45, 1425, 45, 45, 1428, 45, 1429, 67, 67, 67, 67, 67, 67, 67, 67, 1468, 67, 67, 67, 67, 67, 67, 67, 67, 529, 67, 67, 67, 67, 67, 67, 539, 67, 67, 1475, 67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 140, 2170880, 2170880, 2170880, 2416640, 97, 97, 1530, 97, 0, 45, 45, 1534, 45, 45, 45, 45, 45, 45, 45, 45, 1956, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1599, 67, 67, 1601, 67, 67, 67, 67, 67, 67, 67, 67, 67, 803, 67, 67, 67, 67, 67, 67, 1632, 97, 1634, 0, 97, 97, 97, 1640, 97, 97, 97, 1643, 97, 97, 1645, 97, 97, 97, 97, 97, 912, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 0, 0, 45, 45, 45, 45, 45, 45, 1660, 1661, 45, 45, 45, 45, 1665, 1666, 45, 45, 45, 45, 45, 1670, 1692, 1693, 67, 67, 67, 67, 67, 1697, 67, 67, 67, 67, 67, 67, 67, 1702, 97, 97, 1714, 1715, 97, 97, 97, 97, 0, 1721, 1722, 97, 97, 97, 97, 97, 97, 1353, 97, 97, 97, 97, 97, 97, 97, 97, 1362, 1726, 97, 0, 0, 97, 97, 97, 0, 97, 97, 97, 1734, 97, 97, 97, 97, 97, 848, 849, 97, 97, 97, 97, 856, 97, 97, 97, 97, 97, 354, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 45, 45, 1750, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1681, 45, 0, 1846, 97, 97, 97, 97, 97, 97, 45, 45, 1854, 45, 45, 45, 45, 1859, 67, 67, 67, 1879, 67, 67, 97, 97, 1884, 97, 97, 0, 0, 0, 97, 97, 97, 1105, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1344, 97, 97, 97, 1347, 97, 1892, 97, 0, 0, 0, 97, 97, 97, 1900, 97, 97, 45, 45, 45, 45, 45, 997, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1002, 45, 45, 1005, 1006, 45, 67, 67, 67, 67, 67, 1926, 67, 67, 1928, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 1737, 97, 0, 97, 97, 97, 97, 0, 0, 0, 97, 97, 1944, 97, 97, 1946, 45, 45, 45, 1544, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 190, 45, 45, 45, 152, 155, 45, 163, 45, 45, 177, 179, 182, 45, 45, 45, 193, 197, 45, 45, 45, 1672, 45, 45, 45, 45, 45, 1677, 45, 1679, 45, 45, 45, 45, 996, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1212, 45, 45, 45, 45, 67, 260, 264, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 97, 97, 295, 299, 302, 97, 310, 97, 97, 324, 326, 329, 97, 97, 97, 0, 97, 97, 1639, 0, 1641, 97, 97, 97, 97, 97, 97, 97, 97, 1511, 97, 97, 97, 97, 97, 97, 97, 97, 1523, 97, 97, 97, 97, 97, 97, 97, 97, 1719, 97, 97, 97, 97, 97, 97, 97, 97, 1720, 97, 97, 97, 97, 97, 97, 97, 312, 97, 97, 97, 97, 97, 97, 97, 97, 1123, 97, 97, 97, 97, 97, 97, 97, 340, 344, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 139621, 0, 0, 0, 0, 364, 0, 367, 41098, 369, 140, 45, 45, 373, 375, 419, 45, 45, 45, 45, 45, 45, 45, 45, 45, 428, 45, 45, 435, 45, 45, 45, 1751, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1410, 45, 45, 45, 67, 67, 67, 505, 67, 67, 67, 67, 67, 67, 67, 67, 67, 514, 67, 67, 67, 67, 67, 67, 1969, 67, 97, 97, 97, 97, 0, 0, 0, 97, 97, 45, 67, 0, 97, 45, 67, 0, 97, 2064, 2065, 0, 2066, 45, 521, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 534, 67, 67, 67, 67, 67, 67, 465, 67, 67, 67, 474, 67, 67, 67, 67, 67, 67, 67, 1467, 67, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 1933, 0, 97, 97, 97, 602, 97, 97, 97, 97, 97, 97, 97, 97, 97, 611, 97, 97, 18, 640, 139621, 358, 641, 0, 0, 0, 0, 364, 0, 0, 367, 0, 618, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 631, 97, 97, 97, 97, 97, 881, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 569, 97, 97, 97, 97, 97, 369, 0, 45, 652, 45, 45, 45, 45, 45, 657, 45, 45, 45, 45, 45, 45, 1235, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 1432, 67, 67, 67, 67, 67, 67, 67, 766, 67, 67, 67, 67, 67, 67, 67, 67, 773, 67, 67, 67, 0, 1305, 0, 1311, 0, 1317, 97, 97, 97, 97, 97, 97, 97, 1624, 97, 97, 97, 97, 97, 97, 97, 97, 0, 97, 97, 97, 1724, 97, 97, 97, 777, 67, 67, 782, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 535, 67, 67, 67, 67, 67, 67, 67, 814, 67, 67, 67, 67, 67, 67, 67, 67, 67, 37689, 544, 25403, 546, 70179, 0, 0, 66365, 66365, 552, 0, 97, 837, 97, 97, 97, 97, 97, 97, 1496, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 918, 97, 97, 97, 97, 0, 842, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1168, 97, 97, 97, 97, 864, 97, 97, 97, 97, 97, 97, 97, 97, 871, 97, 97, 97, 0, 1637, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1801, 45, 45, 97, 875, 97, 97, 880, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1151, 1152, 97, 97, 97, 67, 67, 67, 1040, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 790, 67, 67, 67, 1180, 0, 649, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 200, 45, 45, 67, 67, 67, 1454, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 806, 67, 67, 67, 0, 0, 0, 1481, 0, 1094, 0, 0, 97, 1483, 97, 97, 97, 97, 97, 97, 304, 97, 97, 318, 97, 97, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 97, 97, 97, 1507, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1332, 97, 97, 97, 1619, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1631, 97, 1633, 97, 0, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1381, 0, 0, 45, 45, 45, 45, 97, 97, 1727, 0, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 626, 97, 97, 97, 97, 97, 97, 636, 45, 45, 1760, 67, 67, 67, 67, 67, 67, 67, 1765, 67, 67, 67, 67, 67, 67, 67, 1299, 67, 67, 67, 0, 0, 0, 0, 0, 0, 97, 97, 97, 97, 1616, 97, 97, 1803, 45, 45, 45, 45, 1807, 45, 45, 45, 45, 45, 1813, 45, 45, 45, 67, 67, 1684, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 822, 67, 67, 37689, 544, 67, 67, 1818, 67, 67, 67, 67, 1822, 67, 67, 67, 67, 67, 1828, 67, 67, 67, 67, 67, 97, 0, 0, 97, 97, 97, 97, 97, 45, 45, 45, 2012, 2013, 45, 45, 67, 67, 67, 2018, 2019, 67, 67, 97, 67, 97, 97, 97, 1833, 97, 97, 0, 0, 97, 97, 1840, 97, 97, 0, 0, 97, 97, 97, 0, 97, 97, 1733, 97, 1735, 97, 97, 97, 0, 97, 97, 97, 1849, 97, 97, 97, 45, 45, 45, 45, 45, 1857, 45, 45, 45, 1910, 45, 1912, 45, 45, 1914, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1017, 67, 67, 1020, 67, 45, 1861, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 1872, 67, 67, 67, 67, 67, 67, 752, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1446, 67, 67, 67, 67, 67, 1876, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 0, 0, 0, 1890, 97, 97, 97, 97, 97, 1134, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 570, 97, 97, 97, 97, 580, 1935, 97, 97, 97, 97, 0, 0, 0, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 1906, 45, 67, 67, 67, 67, 2048, 0, 97, 97, 97, 97, 45, 45, 67, 67, 0, 0, 0, 0, 925, 41606, 0, 0, 0, 931, 45, 45, 45, 45, 45, 45, 1674, 45, 1676, 45, 45, 45, 45, 45, 45, 45, 446, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 1871, 67, 67, 67, 67, 0, 97, 97, 45, 67, 0, 97, 2060, 2061, 0, 2063, 45, 67, 0, 97, 45, 45, 156, 45, 45, 45, 45, 45, 45, 45, 45, 45, 192, 45, 45, 45, 45, 1673, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 429, 45, 45, 45, 45, 67, 67, 67, 269, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 97, 349, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 139621, 0, 0, 0, 0, 364, 0, 367, 41098, 369, 140, 45, 45, 374, 45, 45, 67, 67, 213, 217, 67, 67, 67, 67, 67, 242, 67, 247, 67, 253, 45, 45, 698, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 399, 45, 45, 0, 0, 0, 0, 925, 41606, 0, 929, 0, 0, 45, 45, 45, 45, 45, 45, 1391, 45, 45, 1395, 45, 45, 45, 45, 45, 45, 423, 45, 45, 45, 45, 45, 45, 45, 436, 45, 67, 67, 67, 67, 1041, 67, 1043, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1776, 67, 67, 97, 97, 97, 1099, 0, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 888, 97, 97, 97, 1131, 97, 97, 97, 97, 1135, 97, 1137, 97, 97, 97, 97, 97, 97, 97, 1497, 97, 97, 97, 97, 97, 97, 97, 97, 97, 883, 97, 97, 97, 97, 97, 97, 1310, 0, 0, 0, 1316, 0, 0, 0, 0, 1100, 0, 0, 0, 97, 97, 97, 97, 97, 1107, 97, 97, 97, 97, 97, 97, 97, 97, 1343, 97, 97, 97, 97, 97, 97, 1348, 0, 0, 1317, 0, 0, 0, 0, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1112, 97, 45, 1804, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 1868, 67, 1870, 67, 67, 67, 67, 67, 1817, 67, 67, 1819, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 823, 67, 37689, 544, 67, 97, 1832, 97, 97, 1834, 97, 0, 0, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 0, 1732, 97, 97, 97, 97, 97, 97, 97, 850, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1177, 0, 0, 925, 0, 0, 0, 0, 97, 97, 97, 97, 0, 0, 1941, 97, 97, 97, 97, 97, 97, 45, 45, 45, 1991, 1992, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1998, 134, 0, 0, 0, 37, 110630, 0, 0, 0, 114730, 106539, 41098, 45, 45, 45, 45, 941, 45, 45, 944, 45, 45, 45, 45, 45, 45, 952, 45, 45, 207, 67, 67, 67, 67, 67, 226, 67, 67, 67, 67, 67, 67, 67, 67, 67, 820, 67, 67, 67, 67, 37689, 544, 369, 650, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1682, 25403, 546, 70179, 0, 0, 66365, 66365, 552, 835, 97, 97, 97, 97, 97, 97, 97, 1522, 97, 97, 97, 97, 97, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 1725, 67, 67, 67, 1695, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1034, 67, 1036, 67, 67, 67, 265, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 97, 97, 296, 97, 97, 97, 97, 314, 97, 97, 97, 97, 332, 334, 97, 97, 97, 97, 97, 1146, 1147, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1626, 97, 97, 97, 97, 97, 97, 345, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 139621, 0, 0, 0, 0, 364, 0, 367, 41098, 369, 140, 45, 372, 45, 45, 45, 1220, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1213, 45, 45, 45, 45, 404, 406, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 434, 45, 45, 45, 440, 45, 45, 45, 45, 45, 45, 45, 45, 451, 452, 45, 45, 45, 67, 1683, 67, 67, 67, 1686, 67, 67, 67, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 67, 67, 67, 67, 490, 492, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1447, 67, 67, 1450, 67, 67, 67, 67, 67, 526, 67, 67, 67, 67, 67, 67, 67, 67, 537, 538, 67, 67, 67, 67, 67, 506, 67, 67, 508, 67, 67, 511, 67, 67, 67, 67, 0, 1476, 0, 0, 0, 0, 0, 1478, 0, 0, 0, 0, 0, 0, 0, 0, 97, 97, 1484, 97, 97, 97, 97, 97, 97, 865, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1499, 97, 97, 97, 97, 97, 97, 97, 97, 97, 587, 589, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 629, 97, 97, 97, 97, 97, 97, 97, 97, 97, 623, 97, 97, 97, 97, 97, 97, 97, 97, 634, 635, 97, 97, 97, 97, 97, 1160, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1628, 97, 97, 97, 97, 369, 0, 45, 45, 45, 45, 45, 655, 45, 45, 45, 45, 45, 45, 45, 45, 999, 45, 1001, 45, 45, 45, 45, 45, 45, 45, 45, 715, 45, 45, 45, 720, 45, 45, 45, 45, 45, 45, 45, 45, 728, 25403, 546, 70179, 0, 0, 66365, 66365, 552, 0, 97, 97, 97, 97, 97, 840, 97, 97, 97, 97, 97, 1174, 97, 97, 97, 97, 0, 0, 925, 0, 0, 0, 0, 0, 0, 0, 1100, 97, 97, 97, 97, 97, 97, 97, 97, 627, 97, 97, 97, 97, 97, 97, 97, 938, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 680, 45, 968, 45, 970, 45, 973, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 962, 45, 45, 45, 45, 45, 979, 45, 45, 45, 45, 45, 985, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1224, 45, 45, 45, 45, 45, 45, 45, 45, 688, 45, 45, 45, 45, 45, 45, 45, 1007, 1008, 67, 67, 67, 67, 67, 1014, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1045, 67, 67, 67, 67, 67, 67, 67, 1038, 67, 67, 67, 67, 67, 67, 1044, 67, 1046, 67, 1049, 67, 67, 67, 67, 67, 67, 800, 67, 67, 67, 67, 67, 67, 808, 67, 67, 0, 0, 0, 1102, 97, 97, 97, 97, 97, 1108, 97, 97, 97, 97, 97, 97, 306, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1371, 97, 97, 97, 97, 97, 97, 97, 97, 1132, 97, 97, 97, 97, 97, 97, 1138, 97, 1140, 97, 1143, 97, 97, 97, 97, 97, 1352, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 869, 97, 97, 97, 97, 97, 45, 1191, 45, 45, 45, 45, 45, 1196, 45, 45, 45, 45, 45, 45, 45, 45, 1407, 45, 45, 45, 45, 45, 45, 45, 45, 986, 45, 45, 45, 45, 45, 45, 991, 45, 67, 67, 67, 1256, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1048, 67, 67, 67, 97, 1336, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 615, 97, 1386, 45, 1387, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 455, 45, 457, 45, 45, 1424, 45, 45, 45, 45, 45, 67, 67, 67, 67, 1433, 67, 1434, 67, 67, 67, 67, 67, 767, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1591, 67, 1593, 67, 67, 45, 45, 1805, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1814, 45, 45, 1816, 67, 67, 67, 67, 1820, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1829, 67, 67, 67, 67, 67, 815, 67, 67, 67, 67, 821, 67, 67, 67, 37689, 544, 67, 1831, 97, 97, 97, 97, 1835, 0, 0, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 1731, 97, 97, 97, 97, 97, 97, 97, 97, 97, 853, 97, 97, 97, 97, 97, 97, 0, 97, 97, 97, 97, 1850, 97, 97, 45, 45, 45, 45, 45, 45, 45, 45, 1547, 45, 45, 45, 45, 45, 45, 45, 45, 1664, 45, 45, 45, 45, 45, 45, 45, 45, 961, 45, 45, 45, 45, 965, 45, 967, 1907, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 1920, 0, 1936, 97, 97, 97, 0, 0, 0, 97, 97, 97, 97, 97, 97, 45, 45, 67, 67, 67, 67, 67, 67, 1763, 67, 67, 67, 67, 67, 67, 67, 67, 1056, 67, 67, 67, 67, 67, 67, 67, 67, 1273, 67, 67, 67, 67, 67, 67, 67, 67, 1457, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 0, 0, 28672, 97, 45, 67, 67, 67, 67, 0, 0, 97, 97, 97, 97, 45, 45, 67, 67, 2054, 97, 97, 291, 97, 97, 97, 97, 97, 97, 320, 97, 97, 97, 97, 97, 97, 307, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 12288, 0, 925, 926, 1179, 0, 45, 377, 45, 45, 45, 381, 45, 45, 392, 45, 45, 396, 45, 45, 45, 45, 971, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1756, 45, 45, 45, 67, 67, 67, 67, 463, 67, 67, 67, 467, 67, 67, 478, 67, 67, 482, 67, 67, 67, 67, 67, 1028, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1469, 67, 67, 1472, 67, 502, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1460, 67, 97, 97, 97, 97, 560, 97, 97, 97, 564, 97, 97, 575, 97, 97, 579, 97, 97, 97, 97, 97, 1368, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 0, 925, 0, 0, 930, 97, 599, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 872, 97, 45, 666, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1758, 0, 362, 0, 0, 925, 41606, 0, 0, 0, 0, 45, 45, 934, 45, 45, 45, 164, 168, 174, 178, 45, 45, 45, 45, 45, 194, 45, 45, 45, 165, 45, 45, 45, 45, 45, 45, 45, 45, 45, 199, 45, 45, 45, 67, 67, 1010, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1060, 67, 67, 67, 67, 67, 67, 1052, 1053, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1063, 97, 1157, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1167, 97, 97, 97, 97, 97, 1379, 97, 97, 97, 0, 0, 0, 45, 1383, 45, 45, 45, 1806, 45, 45, 45, 45, 45, 45, 1812, 45, 45, 45, 45, 67, 67, 67, 67, 67, 1577, 67, 67, 67, 67, 67, 67, 67, 753, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1262, 67, 67, 67, 67, 67, 67, 67, 1282, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1471, 67, 45, 1402, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 417, 45, 67, 1462, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 37689, 544, 97, 1517, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1128, 97, 97, 97, 97, 1636, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 851, 97, 97, 97, 97, 97, 97, 97, 67, 67, 1705, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 1842, 0, 0, 1779, 97, 97, 97, 1782, 97, 0, 0, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 1789, 97, 97, 0, 0, 0, 97, 1847, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 45, 45, 1675, 45, 45, 45, 45, 45, 45, 45, 45, 737, 738, 67, 740, 67, 741, 67, 743, 67, 67, 67, 67, 67, 67, 1968, 67, 67, 97, 97, 97, 97, 0, 0, 0, 97, 97, 45, 67, 0, 97, 45, 67, 2062, 97, 45, 67, 0, 97, 45, 67, 67, 97, 97, 2001, 97, 0, 0, 2004, 97, 97, 0, 97, 97, 97, 97, 1797, 97, 97, 97, 97, 97, 45, 45, 45, 67, 261, 67, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 97, 292, 97, 97, 97, 97, 311, 315, 321, 325, 97, 97, 97, 97, 97, 97, 1623, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1330, 97, 97, 1333, 1334, 97, 341, 97, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 139621, 0, 0, 0, 363, 364, 0, 367, 41098, 369, 140, 45, 45, 45, 45, 1221, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 413, 45, 45, 416, 45, 376, 45, 45, 45, 45, 382, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1408, 45, 45, 45, 45, 45, 403, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 414, 45, 45, 45, 418, 67, 67, 67, 462, 67, 67, 67, 67, 468, 67, 67, 67, 67, 67, 67, 67, 67, 1602, 67, 1604, 67, 67, 67, 67, 67, 67, 67, 67, 489, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 500, 67, 67, 67, 67, 67, 1067, 67, 67, 67, 67, 67, 1072, 67, 67, 67, 67, 67, 67, 274, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 67, 67, 504, 67, 67, 67, 67, 67, 67, 67, 510, 67, 67, 67, 517, 519, 541, 67, 37139, 37139, 24853, 24853, 0, 70179, 0, 0, 0, 65820, 65820, 369, 287, 554, 97, 97, 97, 559, 97, 97, 97, 97, 565, 97, 97, 97, 97, 97, 97, 97, 1718, 0, 97, 97, 97, 97, 97, 97, 97, 898, 97, 97, 97, 97, 97, 97, 906, 97, 97, 97, 97, 586, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 597, 97, 97, 97, 97, 97, 1520, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 45, 1656, 45, 45, 45, 97, 97, 601, 97, 97, 97, 97, 97, 97, 97, 607, 97, 97, 97, 614, 616, 638, 97, 18, 0, 139621, 0, 0, 0, 0, 0, 0, 364, 0, 0, 367, 41606, 369, 0, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 661, 45, 45, 45, 407, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1815, 45, 67, 45, 667, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 678, 45, 45, 45, 421, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 976, 977, 45, 45, 45, 682, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 693, 45, 45, 697, 67, 67, 748, 67, 67, 67, 67, 754, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1274, 67, 67, 67, 67, 67, 67, 67, 67, 765, 67, 67, 67, 67, 769, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1589, 67, 67, 67, 67, 67, 67, 67, 67, 780, 67, 67, 784, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1777, 67, 97, 97, 97, 97, 97, 97, 846, 97, 97, 97, 97, 852, 97, 97, 97, 97, 97, 97, 97, 1742, 45, 45, 45, 45, 45, 45, 45, 1747, 97, 97, 97, 863, 97, 97, 97, 97, 867, 97, 97, 97, 97, 97, 97, 97, 308, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 12288, 1178, 925, 0, 1179, 0, 97, 97, 97, 878, 97, 97, 882, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 12288, 0, 925, 0, 1179, 0, 908, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 0, 925, 0, 0, 0, 954, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 963, 45, 45, 966, 45, 45, 157, 45, 45, 171, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 948, 45, 45, 45, 45, 45, 1022, 67, 67, 1026, 67, 67, 67, 1030, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1603, 1605, 67, 67, 67, 1608, 67, 67, 67, 1039, 67, 67, 1042, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 471, 67, 67, 67, 67, 67, 0, 1100, 0, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 904, 97, 97, 97, 97, 1116, 97, 97, 1120, 97, 97, 97, 1124, 97, 97, 97, 97, 97, 97, 562, 97, 97, 97, 571, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1133, 97, 97, 1136, 97, 97, 97, 97, 97, 97, 97, 97, 915, 917, 97, 97, 97, 97, 97, 0, 97, 1170, 97, 97, 97, 97, 97, 97, 97, 97, 0, 0, 925, 0, 0, 0, 0, 0, 41606, 0, 0, 0, 0, 45, 45, 45, 45, 45, 45, 1993, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1275, 67, 67, 67, 1278, 67, 0, 0, 0, 45, 45, 1182, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1189, 1204, 45, 45, 45, 1207, 45, 45, 1209, 45, 1210, 45, 45, 45, 45, 45, 45, 1546, 45, 45, 45, 45, 45, 45, 45, 45, 45, 689, 45, 45, 45, 45, 45, 45, 1231, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 236, 67, 67, 67, 67, 67, 67, 67, 801, 67, 67, 67, 805, 67, 67, 67, 67, 67, 1242, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1249, 67, 67, 67, 67, 67, 67, 507, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1300, 0, 0, 0, 0, 0, 1267, 67, 67, 1269, 67, 1270, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1280, 97, 1349, 97, 1350, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1360, 97, 97, 97, 0, 1980, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 673, 45, 45, 45, 45, 677, 45, 45, 45, 45, 1401, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 953, 67, 1437, 67, 1440, 67, 67, 67, 67, 1445, 67, 67, 67, 1448, 67, 67, 67, 67, 67, 67, 1029, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1825, 67, 67, 67, 67, 67, 1473, 67, 67, 67, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1320, 0, 834, 97, 97, 97, 97, 1490, 97, 1493, 97, 97, 97, 97, 1498, 97, 97, 97, 1501, 97, 97, 97, 0, 97, 1638, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 916, 97, 97, 97, 97, 97, 97, 0, 1528, 97, 97, 97, 0, 45, 45, 45, 1535, 45, 45, 45, 45, 45, 45, 45, 1867, 67, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 1932, 0, 0, 1555, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1567, 45, 45, 158, 45, 45, 172, 45, 45, 45, 183, 45, 45, 45, 45, 201, 45, 45, 67, 212, 67, 67, 67, 67, 231, 235, 241, 245, 67, 67, 67, 67, 67, 67, 493, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 472, 67, 67, 67, 67, 67, 97, 97, 97, 97, 1651, 97, 97, 97, 97, 97, 0, 45, 45, 45, 45, 45, 45, 45, 1539, 45, 45, 45, 67, 1704, 67, 1706, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 1841, 97, 0, 1844, 97, 97, 97, 97, 1716, 97, 97, 97, 0, 97, 97, 97, 97, 97, 97, 97, 590, 97, 97, 97, 97, 97, 97, 97, 97, 97, 0, 0, 0, 45, 45, 45, 1385, 1748, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1757, 45, 45, 159, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 415, 45, 45, 97, 97, 1780, 97, 97, 97, 0, 0, 1786, 97, 97, 97, 97, 97, 0, 0, 97, 97, 1730, 0, 97, 97, 97, 97, 97, 1736, 97, 1738, 67, 97, 97, 97, 97, 97, 97, 0, 1838, 97, 97, 97, 97, 97, 0, 0, 97, 1729, 97, 0, 97, 97, 97, 97, 97, 97, 97, 97, 1162, 97, 97, 97, 1165, 97, 97, 97, 45, 1950, 45, 45, 45, 45, 45, 45, 45, 45, 1958, 67, 67, 67, 1962, 67, 67, 67, 67, 67, 1246, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 97, 1710, 97, 97, 97, 1999, 67, 97, 97, 97, 97, 0, 2003, 97, 97, 97, 0, 97, 97, 2008, 2009, 45, 67, 67, 67, 67, 0, 0, 97, 97, 97, 97, 45, 2052, 67, 2053, 0, 0, 0, 0, 925, 41606, 0, 0, 930, 0, 45, 45, 45, 45, 45, 45, 1392, 45, 1394, 45, 45, 45, 45, 45, 45, 45, 1545, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1563, 1565, 45, 45, 45, 1568, 0, 97, 2055, 45, 67, 0, 97, 45, 67, 0, 97, 45, 67, 28672, 97, 45, 45, 160, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 679, 45, 45, 67, 67, 266, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 346, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 139621, 0, 0, 362, 0, 364, 0, 367, 41098, 369, 140, 371, 45, 45, 45, 379, 45, 45, 45, 388, 45, 45, 45, 45, 45, 45, 45, 45, 1663, 45, 45, 45, 45, 45, 45, 45, 45, 45, 449, 45, 45, 45, 45, 45, 67, 67, 542, 37139, 37139, 24853, 24853, 0, 70179, 0, 0, 0, 65820, 65820, 369, 287, 97, 97, 97, 97, 97, 1622, 97, 97, 97, 97, 97, 97, 97, 1629, 97, 97, 0, 1794, 1795, 97, 97, 97, 97, 97, 97, 97, 97, 45, 45, 45, 45, 45, 45, 1745, 45, 45, 97, 639, 18, 0, 139621, 0, 0, 0, 0, 0, 0, 364, 0, 0, 367, 41606, 45, 731, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 251, 67, 67, 67, 67, 67, 798, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1073, 67, 67, 67, 860, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 873, 0, 0, 1101, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 921, 97, 0, 67, 67, 67, 67, 1245, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1250, 67, 67, 1253, 0, 0, 1312, 0, 0, 0, 1318, 0, 0, 0, 0, 0, 0, 97, 97, 97, 97, 1106, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1149, 97, 97, 97, 97, 97, 1155, 97, 97, 1325, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1141, 97, 97, 67, 67, 1439, 67, 1441, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1264, 67, 67, 67, 97, 97, 1492, 97, 1494, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1331, 97, 97, 97, 97, 67, 67, 67, 2037, 67, 97, 0, 0, 97, 97, 97, 2043, 97, 45, 45, 45, 442, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 67, 67, 67, 67, 67, 67, 232, 67, 67, 67, 67, 67, 67, 67, 67, 1823, 67, 67, 67, 67, 67, 67, 67, 67, 97, 97, 97, 97, 1975, 0, 0, 97, 874, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1142, 97, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 65, 86, 117, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 63, 84, 115, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 61, 82, 113, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 59, 80, 111, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 57, 78, 109, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 55, 76, 107, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 53, 74, 105, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 51, 72, 103, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 49, 70, 101, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 47, 68, 99, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 45, 67, 97, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 213085, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 0, 0, 44, 0, 0, 32863, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 41, 41, 41, 0, 0, 1138688, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 0, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 89, 53264, 18, 18, 49172, 0, 57366, 0, 24, 24, 24, 0, 127, 127, 127, 127, 102432, 67, 262, 67, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 342, 97, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 139621, 0, 360, 0, 0, 364, 0, 367, 41098, 369, 140, 45, 45, 45, 45, 717, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 412, 45, 45, 45, 45, 45, 67, 1009, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1292, 67, 67, 1294, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 0, 0, 0, 0, 0, 0, 97, 97, 97, 1615, 97, 97, 97, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 66, 87, 118, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 64, 85, 116, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 62, 83, 114, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 60, 81, 112, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 58, 79, 110, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 56, 77, 108, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 54, 75, 106, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 52, 73, 104, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 50, 71, 102, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 48, 69, 100, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 37, 110630, 114730, 106539, 46, 67, 98, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 233472, 53264, 18, 49172, 57366, 24, 8192, 28, 102432, 0, 110630, 114730, 106539, 0, 0, 69724, 53264, 18, 18, 49172, 0, 57366, 262144, 24, 24, 24, 0, 28, 28, 28, 28, 102432, 45, 45, 161, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 710, 45, 45, 28, 139621, 359, 0, 0, 0, 364, 0, 367, 41098, 369, 140, 45, 45, 45, 45, 1389, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 949, 45, 45, 45, 45, 67, 503, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 1449, 67, 67, 97, 600, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1154, 97, 0, 0, 0, 0, 925, 41606, 927, 0, 0, 0, 45, 45, 45, 45, 45, 45, 1866, 67, 67, 67, 67, 67, 67, 67, 67, 67, 67, 772, 67, 67, 67, 67, 67, 45, 45, 969, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 951, 45, 45, 45, 45, 1192, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1202, 45, 45, 0, 0, 0, 1314, 0, 0, 0, 0, 0, 0, 0, 0, 0, 97, 97, 97, 97, 97, 97, 97, 1488, 67, 67, 267, 67, 67, 67, 67, 0, 37139, 24853, 0, 0, 0, 0, 41098, 65820, 97, 347, 97, 97, 97, 97, 0, 53264, 0, 18, 18, 24, 24, 0, 28, 28, 139621, 0, 361, 0, 0, 364, 0, 367, 41098, 369, 140, 45, 45, 45, 45, 734, 45, 45, 45, 67, 67, 67, 67, 67, 742, 67, 67, 45, 45, 668, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1214, 45, 45, 1130, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1361, 97, 45, 45, 1671, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1552, 45, 45, 0, 0, 0, 0, 2220032, 0, 0, 1130496, 0, 0, 0, 0, 2170880, 2171020, 2170880, 2170880, 18, 0, 0, 131072, 0, 0, 0, 90112, 0, 2220032, 0, 0, 0, 0, 0, 0, 0, 0, 97, 97, 97, 1485, 97, 97, 97, 97, 0, 45, 45, 45, 45, 45, 1537, 45, 45, 45, 45, 45, 1390, 45, 1393, 45, 45, 45, 45, 1398, 45, 45, 45, 2170880, 2171167, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2576384, 2215936, 3117056, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 0, 0, 0, 0, 0, 2174976, 0, 0, 0, 0, 0, 0, 2183168, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2400256, 2170880, 2170880, 2170880, 2170880, 2721252, 2744320, 2170880, 2170880, 2170880, 2834432, 2840040, 2170880, 2908160, 2170880, 2170880, 2936832, 2170880, 2170880, 2985984, 2170880, 2994176, 2170880, 2170880, 3014656, 2170880, 3059712, 3076096, 3088384, 2170880, 2170880, 2170880, 2170880, 0, 0, 0, 0, 2220032, 0, 0, 0, 1142784, 0, 0, 0, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3215360, 2215936, 2215936, 2215936, 2215936, 2215936, 2437120, 2215936, 2215936, 2215936, 3117056, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 2215936, 0, 543, 0, 545, 0, 0, 2183168, 0, 0, 831, 0, 2170880, 2170880, 2170880, 2400256, 2170880, 2170880, 2170880, 2170880, 3031040, 2170880, 3055616, 2170880, 2170880, 2170880, 2170880, 3092480, 2170880, 2170880, 3125248, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 2170880, 3198976, 2170880, 0, 0, 0, 0, 0, 0, 67, 67, 37139, 37139, 24853, 24853, 0, 0, 0, 0, 0, 65820, 65820, 0, 287, 97, 97, 97, 97, 97, 1783, 0, 0, 97, 97, 97, 97, 97, 97, 0, 0, 97, 97, 97, 97, 97, 97, 1791, 0, 0, 546, 70179, 0, 0, 0, 0, 552, 0, 97, 97, 97, 97, 97, 97, 97, 604, 97, 97, 97, 97, 97, 97, 97, 97, 97, 97, 1150, 97, 97, 97, 97, 97, 147456, 147456, 147456, 147456, 147456, 147456, 147456, 147456, 147456, 147456, 147456, 147456, 0, 0, 147456, 0, 0, 0, 0, 925, 41606, 0, 928, 0, 0, 45, 45, 45, 45, 45, 45, 998, 45, 45, 45, 45, 45, 45, 45, 45, 45, 1562, 45, 1564, 45, 45, 45, 45, 0, 2158592, 2158592, 0, 0, 0, 0, 2232320, 2232320, 2232320, 0, 2240512, 2240512, 2240512, 2240512, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 2170880, 2170880, 2170880, 2416640 ]; JSONiqTokenizer.EXPECTED = [ 291, 300, 304, 341, 315, 309, 305, 295, 319, 323, 327, 329, 296, 333, 337, 339, 342, 346, 350, 294, 356, 360, 312, 367, 352, 371, 363, 375, 379, 383, 387, 391, 395, 726, 399, 405, 518, 684, 405, 405, 405, 405, 808, 405, 405, 405, 512, 405, 405, 405, 431, 405, 405, 406, 405, 405, 404, 405, 405, 405, 405, 405, 405, 405, 908, 631, 410, 415, 405, 414, 419, 608, 405, 429, 602, 405, 435, 443, 405, 441, 641, 478, 405, 447, 451, 450, 456, 643, 461, 460, 762, 679, 465, 469, 741, 473, 477, 482, 486, 492, 932, 931, 523, 498, 504, 720, 405, 510, 596, 405, 516, 941, 580, 522, 929, 527, 590, 589, 897, 939, 534, 538, 547, 551, 555, 559, 563, 567, 571, 969, 575, 708, 690, 689, 579, 584, 634, 405, 594, 731, 405, 600, 882, 405, 606, 895, 786, 452, 612, 405, 615, 620, 876, 624, 628, 638, 647, 651, 655, 659, 663, 667, 676, 683, 688, 695, 694, 791, 405, 699, 437, 405, 706, 714, 405, 712, 825, 870, 405, 718, 724, 769, 768, 823, 730, 735, 745, 751, 422, 755, 759, 425, 766, 902, 810, 587, 775, 888, 887, 405, 773, 992, 405, 779, 962, 405, 785, 781, 986, 790, 795, 797, 506, 500, 499, 801, 805, 814, 820, 829, 833, 837, 841, 845, 849, 853, 857, 861, 616, 865, 869, 868, 488, 405, 874, 816, 405, 880, 738, 405, 886, 892, 543, 405, 901, 906, 913, 912, 918, 494, 541, 922, 926, 936, 945, 949, 953, 957, 530, 966, 973, 960, 702, 701, 405, 979, 981, 405, 985, 747, 405, 990, 998, 914, 405, 996, 1004, 672, 975, 974, 1014, 1002, 1008, 670, 1012, 405, 405, 405, 405, 405, 401, 1018, 1022, 1026, 1106, 1071, 1111, 1111, 1111, 1082, 1145, 1030, 1101, 1034, 1038, 1106, 1106, 1106, 1106, 1046, 1206, 1052, 1106, 1072, 1111, 1111, 1042, 1134, 1065, 1111, 1112, 1056, 1160, 1207, 1062, 1204, 1208, 1069, 1106, 1106, 1106, 1076, 1111, 1207, 1161, 1122, 1205, 1064, 1094, 1106, 1106, 1107, 1111, 1111, 1111, 1078, 1086, 1207, 1092, 1098, 1046, 1058, 1106, 1106, 1110, 1111, 1111, 1116, 1120, 1161, 1126, 1202, 1104, 1106, 1145, 1146, 1129, 1138, 1088, 1151, 1048, 1157, 1153, 1132, 1141, 1165, 1107, 1111, 1172, 1179, 1109, 1183, 1175, 1143, 1147, 1187, 1108, 1191, 1195, 1144, 1199, 1168, 1212, 1216, 1220, 1224, 1228, 1232, 1236, 1557, 1247, 1241, 1241, 1038, 1434, 1241, 1241, 1241, 1241, 1254, 1275, 1617, 1241, 1280, 1287, 1241, 1241, 1241, 1287, 1241, 2114, 1291, 1241, 1243, 1241, 2049, 1824, 2094, 2095, 1520, 1309, 1241, 1241, 1302, 1241, 1321, 1311, 1241, 1241, 1313, 1778, 1325, 1336, 1241, 1241, 1325, 1330, 1353, 1241, 1241, 1695, 1354, 1241, 1241, 1241, 1294, 1686, 1331, 1241, 1696, 1368, 1241, 1338, 1370, 1241, 1392, 1399, 1364, 2017, 1406, 2016, 1405, 1716, 1406, 1407, 1422, 1417, 1421, 1241, 1241, 1241, 1349, 1426, 1241, 1774, 1756, 1241, 1773, 1241, 1241, 1345, 1964, 1812, 1432, 1241, 1241, 1345, 1993, 1459, 1241, 1241, 1241, 1395, 1848, 1767, 1465, 1241, 1241, 1394, 1847, 1242, 1477, 1241, 1241, 1428, 1241, 1445, 1492, 1241, 1241, 1438, 1241, 1499, 1241, 1241, 1241, 1455, 1241, 1818, 1448, 1241, 1250, 1241, 2026, 1623, 1449, 1241, 1612, 1616, 1241, 1614, 1241, 1257, 1241, 1241, 1985, 1292, 1586, 1512, 1241, 1517, 2050, 1526, 1674, 1519, 1524, 1647, 2051, 1532, 1537, 1551, 1544, 1550, 1555, 1561, 1571, 1578, 1584, 1590, 1591, 1653, 1595, 1602, 1606, 1610, 1634, 1628, 1640, 1633, 1645, 1241, 1241, 1241, 1469, 1241, 1970, 1651, 1241, 1270, 1241, 1241, 1819, 1449, 1241, 1293, 1664, 1241, 1241, 1481, 1485, 1574, 1672, 1241, 1241, 1513, 1317, 1487, 1684, 1241, 1241, 1533, 1299, 1694, 1241, 1241, 1295, 1241, 1241, 1241, 1546, 1700, 1241, 1241, 1707, 1241, 1713, 1241, 1849, 1715, 1241, 1720, 1241, 1276, 1267, 1241, 1241, 2107, 1657, 1864, 1241, 1881, 1241, 1326, 1292, 1241, 1685, 1358, 1724, 1338, 1241, 1363, 1362, 1342, 1340, 1361, 1339, 1833, 1372, 1360, 1833, 1833, 1342, 1343, 1835, 1341, 1731, 1738, 1344, 1241, 1745, 1241, 1379, 1241, 1241, 2092, 1241, 1388, 1761, 1754, 1241, 1386, 1241, 1400, 1760, 1241, 1241, 1241, 1598, 1734, 1241, 1241, 1241, 1635, 1645, 1241, 1780, 1766, 1241, 1241, 1332, 1771, 1241, 1241, 1629, 2079, 1241, 1242, 1784, 1241, 1241, 1680, 1639, 2063, 1790, 1241, 1241, 1741, 1241, 1241, 1800, 1241, 1241, 1762, 1473, 1241, 1806, 1241, 1241, 1786, 1240, 1709, 1241, 1241, 1241, 1668, 1811, 1241, 1940, 1241, 1401, 1974, 1241, 1408, 1413, 1382, 1241, 1816, 1241, 1241, 1802, 2086, 1811, 1241, 1817, 1945, 1823, 2095, 2095, 2047, 2094, 2046, 2080, 1241, 1409, 1312, 1376, 2096, 2048, 1241, 1241, 1807, 1241, 1241, 1241, 2035, 1241, 1241, 1828, 1241, 2057, 2061, 1241, 1241, 1843, 1241, 2059, 1241, 1241, 1241, 1690, 1847, 1241, 1241, 1241, 1703, 2102, 1848, 1241, 1241, 1853, 1292, 1848, 1241, 2016, 1857, 1241, 2002, 1868, 1241, 1436, 1241, 1241, 1271, 1305, 1241, 1874, 1241, 1241, 1884, 2037, 1892, 1241, 1890, 1241, 1461, 1241, 1241, 1795, 1241, 1241, 1891, 1241, 1878, 1241, 1888, 1241, 1888, 1905, 1896, 2087, 1912, 1903, 1241, 1911, 1906, 1916, 1905, 2027, 1863, 1925, 2088, 1859, 1861, 1922, 1927, 1931, 1935, 1494, 1241, 1241, 1918, 1907, 1939, 1917, 1944, 1949, 1241, 1241, 1451, 1955, 1241, 1241, 1241, 1796, 1727, 2061, 1241, 1241, 1899, 1241, 1660, 1968, 1241, 1241, 1951, 1678, 1978, 1241, 1241, 1241, 1839, 1241, 1241, 1984, 1982, 1241, 1488, 1241, 1241, 1624, 1450, 1989, 1241, 1241, 1241, 1870, 1995, 1292, 1241, 1241, 1958, 1261, 1241, 1996, 1241, 1241, 1241, 2039, 2008, 1241, 1241, 1750, 2000, 1241, 1256, 2001, 1960, 1241, 1564, 1241, 1504, 1241, 1241, 1442, 1241, 1241, 1564, 1528, 1263, 1241, 1508, 1241, 1241, 1468, 1498, 2006, 1540, 2015, 1539, 2014, 1748, 2013, 1539, 1831, 2014, 2012, 1500, 1567, 2022, 2021, 1241, 1580, 1241, 1241, 2033, 2037, 1791, 2045, 2031, 1241, 1621, 1241, 1641, 2044, 1241, 1241, 1241, 2093, 1241, 1241, 2055, 1241, 1241, 2067, 1241, 1283, 1241, 1241, 1241, 2101, 2071, 1241, 1241, 1241, 2073, 1848, 2040, 1241, 1241, 1241, 2077, 1241, 1241, 2106, 1241, 1241, 2084, 1241, 2111, 1241, 1241, 1381, 1380, 1241, 1241, 1241, 2100, 1241, 2129, 2118, 2122, 2126, 2197, 2133, 3010, 2825, 2145, 2698, 2156, 2226, 2160, 2161, 2165, 2174, 2293, 2194, 2630, 2201, 2203, 2152, 3019, 2226, 2263, 2209, 2213, 2218, 2269, 2292, 2269, 2269, 2184, 2226, 2238, 2148, 2151, 3017, 2245, 2214, 2269, 2269, 2185, 2226, 2292, 2269, 2291, 2269, 2269, 2269, 2292, 2205, 3019, 2226, 2226, 2160, 2160, 2160, 2261, 2160, 2160, 2160, 2262, 2276, 2160, 2160, 2277, 2216, 2283, 2216, 2269, 2269, 2268, 2269, 2267, 2269, 2269, 2269, 2271, 2568, 2292, 2269, 2293, 2269, 2182, 2190, 2269, 2186, 2226, 2226, 2226, 2226, 2227, 2160, 2160, 2160, 2160, 2263, 2160, 2275, 2277, 2282, 2215, 2217, 2269, 2269, 2291, 2269, 2269, 2293, 2291, 2269, 2220, 2269, 2295, 2294, 2269, 2269, 2305, 2233, 2262, 2278, 2218, 2269, 2234, 2226, 2226, 2228, 2160, 2160, 2160, 2289, 2220, 2294, 2294, 2269, 2269, 2304, 2269, 2160, 2160, 2287, 2269, 2269, 2305, 2269, 2269, 2312, 2269, 2269, 2225, 2226, 2160, 2287, 2289, 2219, 2304, 2295, 2314, 2234, 2226, 2314, 2269, 2226, 2226, 2160, 2288, 2219, 2222, 2304, 2296, 2269, 2224, 2160, 2160, 2269, 2302, 2294, 2314, 2224, 2226, 2288, 2220, 2294, 2269, 2290, 2269, 2269, 2293, 2269, 2269, 2269, 2269, 2270, 2221, 2313, 2225, 2227, 2160, 2300, 2269, 2225, 2261, 2309, 2234, 2229, 2223, 2318, 2318, 2318, 2328, 2336, 2340, 2344, 2350, 2637, 2712, 2358, 2362, 2372, 2135, 2378, 2398, 2135, 2135, 2135, 2135, 2136, 2417, 2241, 2135, 2378, 2135, 2135, 2980, 2984, 2135, 3006, 2135, 2135, 2135, 2945, 2931, 2425, 2400, 2135, 2135, 2135, 2954, 2135, 2481, 2433, 2135, 2135, 2988, 2824, 2135, 2135, 2482, 2434, 2135, 2135, 2440, 2445, 2452, 2135, 2135, 2998, 3002, 2961, 2441, 2446, 2453, 2463, 2974, 2135, 2135, 2135, 2140, 2642, 2709, 2459, 2470, 2465, 2135, 2135, 3005, 2135, 2135, 2987, 2823, 2458, 2469, 2464, 2975, 2135, 2135, 2135, 2353, 2488, 2447, 2324, 2974, 2135, 2409, 2459, 2448, 2135, 2961, 2487, 2446, 2476, 2323, 2973, 2135, 2135, 2135, 2354, 2476, 2974, 2135, 2135, 2135, 2957, 2135, 2135, 2960, 2135, 2135, 2135, 2363, 2409, 2459, 2474, 2465, 2487, 2571, 2973, 2135, 2135, 2168, 2973, 2135, 2135, 2135, 2959, 2135, 2135, 2135, 2506, 2135, 2957, 2488, 2170, 2135, 2135, 2135, 2960, 2135, 2818, 2493, 2135, 2135, 3033, 2135, 2135, 2135, 2934, 2819, 2494, 2135, 2135, 2135, 2976, 2780, 2499, 2135, 2135, 2135, 3000, 2968, 2135, 2935, 2135, 2135, 2135, 2364, 2507, 2135, 2135, 2934, 2135, 2135, 2780, 2492, 2507, 2135, 2135, 2506, 2780, 2135, 2135, 2782, 2780, 2135, 2782, 2135, 2783, 2374, 2514, 2135, 2135, 2135, 3007, 2530, 2974, 2135, 2135, 2135, 3008, 2135, 2135, 2134, 2135, 2526, 2531, 2975, 2135, 2135, 3042, 2581, 2575, 2956, 2135, 2135, 2135, 2394, 2135, 2508, 2535, 2840, 2844, 2495, 2135, 2135, 2136, 2684, 2537, 2842, 2846, 2135, 2136, 2561, 2581, 2551, 2536, 2841, 2845, 2975, 3043, 2582, 2843, 2555, 2135, 3040, 3044, 2538, 2844, 2975, 2135, 2135, 2253, 2644, 2672, 2542, 2554, 2135, 2135, 2346, 2873, 2551, 2555, 2135, 2135, 2135, 2381, 2559, 2565, 2538, 2553, 2135, 2560, 2914, 2576, 2590, 2135, 2135, 2135, 2408, 2136, 2596, 2624, 2135, 2135, 2135, 2409, 2135, 2618, 2597, 3008, 2135, 2135, 2380, 2956, 2601, 2135, 2135, 2135, 2410, 2620, 2624, 2135, 2136, 2383, 2135, 2135, 2783, 2623, 2135, 2135, 2393, 2888, 2136, 2621, 3008, 2135, 2618, 2618, 2622, 2135, 2135, 2405, 2414, 2619, 2384, 2624, 2135, 2136, 2950, 2135, 2138, 2135, 2139, 2135, 2604, 2623, 2135, 2140, 2878, 2665, 2957, 2622, 2135, 2135, 2428, 2762, 2606, 2612, 2135, 2135, 2501, 2586, 2604, 3038, 2135, 2604, 3036, 2387, 2958, 2386, 2135, 2141, 2135, 2421, 2387, 2385, 2135, 2385, 2384, 2384, 2135, 2386, 2628, 2384, 2135, 2135, 2501, 2596, 2591, 2135, 2135, 2135, 2400, 2135, 2634, 2135, 2135, 2559, 2580, 2575, 2648, 2135, 2135, 2135, 2429, 2649, 2135, 2135, 2135, 2435, 2654, 2658, 2135, 2135, 2135, 2436, 2649, 2178, 2659, 2135, 2135, 2595, 2601, 2669, 2677, 2135, 2135, 2616, 2957, 2879, 2665, 2691, 2135, 2363, 2367, 2900, 2878, 2664, 2690, 2975, 2877, 2643, 2670, 2974, 2671, 2975, 2135, 2135, 2619, 2608, 2669, 2673, 2135, 2135, 2653, 2177, 2672, 2135, 2135, 2135, 2486, 2168, 2251, 2255, 2695, 2974, 2709, 2135, 2135, 2135, 2487, 2169, 2399, 2716, 2975, 2135, 2363, 2770, 2776, 2640, 2717, 2135, 2135, 2729, 2135, 2135, 2641, 2718, 2135, 2135, 2135, 2505, 2135, 2640, 2257, 2974, 2135, 2727, 2975, 2135, 2365, 2332, 2895, 2957, 2135, 2959, 2135, 2365, 2749, 2754, 2959, 2958, 2958, 2135, 2380, 2793, 2799, 2135, 2735, 2738, 2135, 2381, 2135, 2135, 2940, 2974, 2135, 2744, 2135, 2135, 2739, 2519, 2976, 2745, 2135, 2135, 2135, 2509, 2755, 2135, 2135, 2135, 2510, 2772, 2778, 2135, 2135, 2740, 2520, 2135, 2771, 2777, 2135, 2135, 2759, 2750, 2792, 2798, 2135, 2135, 2781, 2392, 2779, 2135, 2135, 2135, 2521, 2135, 2679, 2248, 2135, 2135, 2681, 2480, 2135, 2135, 2786, 3000, 2135, 2679, 2683, 2135, 2135, 2416, 2135, 2135, 2135, 2525, 2135, 2730, 2135, 2135, 2135, 2560, 2581, 2135, 2805, 2135, 2135, 2804, 2962, 2832, 2974, 2135, 2382, 2135, 2135, 2958, 2135, 2135, 2960, 2135, 2829, 2833, 2975, 2961, 2965, 2969, 2973, 2968, 2972, 2135, 2135, 2135, 2641, 2135, 2515, 2966, 2970, 2851, 2478, 2135, 2135, 2808, 2135, 2809, 2135, 2135, 2135, 2722, 2852, 2479, 2135, 2135, 2815, 2135, 2135, 2766, 2853, 2480, 2135, 2857, 2479, 2135, 2388, 2723, 2135, 2364, 2331, 2894, 2858, 2480, 2135, 2135, 2850, 2478, 2135, 2135, 2135, 2806, 2864, 2135, 2399, 2256, 2974, 2865, 2135, 2135, 2862, 2135, 2135, 2135, 2685, 2807, 2865, 2135, 2135, 2807, 2863, 2135, 2135, 2135, 2686, 2884, 2807, 2135, 2809, 2807, 2135, 2135, 2807, 2806, 2705, 2810, 2808, 2700, 2869, 2702, 2702, 2702, 2704, 2883, 2135, 2135, 2135, 2730, 2884, 2135, 2135, 2135, 2731, 2321, 2546, 2135, 2135, 2876, 2255, 2889, 2322, 2547, 2135, 2401, 2135, 2135, 2135, 2949, 2367, 2893, 2544, 2973, 2906, 2973, 2135, 2135, 2877, 2663, 2368, 2901, 2907, 2974, 2366, 2899, 2905, 2972, 2920, 2974, 2135, 2135, 2911, 2900, 2920, 2363, 2913, 2918, 2465, 2941, 2975, 2135, 2135, 2924, 2928, 2974, 2945, 2931, 2135, 2135, 2135, 2765, 2136, 2955, 2135, 2135, 2939, 2931, 2380, 2135, 2135, 2380, 2135, 2135, 2135, 2780, 2507, 2137, 2135, 2137, 2135, 2139, 2135, 2806, 2810, 2135, 2135, 2135, 2992, 2135, 2135, 2962, 2966, 2970, 2974, 2135, 2135, 2787, 3014, 2135, 2521, 2993, 2135, 2135, 2135, 2803, 2135, 2135, 2135, 2618, 2607, 2997, 3001, 2135, 2135, 2963, 2967, 2971, 2975, 2135, 2135, 2791, 2797, 2135, 3009, 2999, 3003, 2787, 3001, 2135, 2135, 2964, 2968, 2785, 2999, 3003, 2135, 2135, 2135, 2804, 2785, 2999, 3004, 2135, 2135, 2135, 2807, 2135, 2135, 3023, 2135, 2135, 2135, 2811, 2135, 2135, 3027, 2135, 2135, 2135, 2837, 2968, 3028, 2135, 2135, 2135, 2875, 2135, 2784, 3029, 2135, 2408, 2457, 2446, 0, 14, 0, -2120220672, 1610612736, -2074083328, -2002780160, -2111830528, 1073872896, 1342177280, 1075807216, 4096, 16384, 2048, 8192, 0, 8192, 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, -2145386496, 8388608, 1073741824, 0, 0x80000000, 0x80000000, 2097152, 2097152, 2097152, 536870912, 0, 0, 134217728, 33554432, 1536, 268435456, 268435456, 268435456, 268435456, 128, 256, 32, 0, 65536, 131072, 524288, 16777216, 268435456, 0x80000000, 1572864, 1835008, 640, 32768, 65536, 262144, 1048576, 2097152, 196608, 196800, 196608, 196608, 0, 131072, 131072, 131072, 196608, 196624, 196608, 196624, 196608, 196608, 128, 4096, 16384, 16384, 2048, 0, 4, 0, 0, 0x80000000, 2097152, 0, 1024, 32, 32, 0, 65536, 1572864, 1048576, 32768, 32768, 32768, 32768, 196608, 196608, 196608, 64, 64, 196608, 196608, 131072, 131072, 131072, 131072, 268435456, 268435456, 64, 196736, 196608, 196608, 196608, 131072, 196608, 196608, 16384, 4, 4, 4, 2, 32, 32, 65536, 1048576, 12582912, 1073741824, 0, 0, 2, 8, 16, 96, 2048, 32768, 0, 0, 131072, 268435456, 268435456, 268435456, 256, 256, 196608, 196672, 196608, 196608, 196608, 196608, 4, 0, 256, 256, 256, 256, 32, 32, 32768, 32, 32, 32, 32, 32768, 268435456, 268435456, 268435456, 196608, 196608, 196608, 196624, 196608, 196608, 196608, 16, 16, 16, 268435456, 196608, 64, 64, 64, 196608, 196608, 196608, 196672, 268435456, 64, 64, 196608, 196608, 16, 196608, 196608, 196608, 268435456, 64, 196608, 131072, 262144, 4194304, 25165824, 33554432, 134217728, 268435456, 268435456, 196608, 262152, 8, 256, 512, 3072, 16384, 200, -1073741816, 8392713, 40, 8392718, 520, 807404072, 40, 520, 100663304, 0, 0, -540651761, -540651761, 257589048, 0, 262144, 0, 0, 3, 8, 256, 0, 4, 6, 4100, 8388612, 0, 0, 0, 3, 4, 8, 256, 512, 1024, 0, 2097152, 0, 0, -537854471, -537854471, 0, 100663296, 0, 0, 1, 2, 0, 0, 0, 16384, 0, 0, 0, 96, 14336, 0, 0, 0, 7, 8, 234881024, 0, 0, 0, 8, 0, 0, 0, 0, 262144, 0, 0, 16, 64, 384, 512, 0, 1, 1, 0, 12582912, 0, 0, 0, 0, 33554432, 67108864, -606084144, -606084144, -606084138, 0, 0, 28, 32, 768, 1966080, -608174080, 0, 0, 0, 14, 35056, 16, 64, 896, 24576, 98304, 98304, 131072, 262144, 524288, 1048576, 4194304, 25165824, 1048576, 62914560, 134217728, -805306368, 0, 384, 512, 16384, 65536, 131072, 262144, 29360128, 33554432, 134217728, 268435456, 1073741824, 0x80000000, 262144, 524288, 1048576, 29360128, 33554432, 524288, 1048576, 16777216, 33554432, 134217728, 268435456, 1073741824, 0, 0, 0, 123856, 1966080, 0, 64, 384, 16384, 65536, 131072, 16384, 65536, 524288, 268435456, 0x80000000, 0, 0, 524288, 0x80000000, 0, 0, 1, 16, 0, 256, 524288, 0, 0, 0, 25, 96, 128, -537854471, 0, 0, 0, 32, 7404800, -545259520, 0, 0, 0, 60, 0, 249, 64768, 1048576, 6291456, 6291456, 25165824, 100663296, 402653184, 1073741824, 96, 128, 1280, 2048, 4096, 57344, 6291456, 57344, 6291456, 8388608, 16777216, 33554432, 201326592, 1342177280, 0x80000000, 0, 57344, 6291456, 8388608, 100663296, 134217728, 0x80000000, 0, 0, 0, 1, 8, 16, 64, 128, 64, 128, 256, 1024, 131072, 131072, 131072, 262144, 524288, 16777216, 57344, 6291456, 8388608, 67108864, 134217728, 64, 256, 1024, 2048, 4096, 57344, 64, 256, 0, 24576, 32768, 6291456, 67108864, 134217728, 0, 1, 64, 256, 24576, 32768, 4194304, 32768, 4194304, 67108864, 0, 0, 64, 256, 0, 0, 24576, 32768, 0, 16384, 4194304, 67108864, 64, 16384, 0, 0, 1, 64, 256, 16384, 4194304, 67108864, 0, 0, 0, 16384, 0, 16384, 16384, 0, -470447874, -470447874, -470447874, 0, 0, 128, 0, 0, 8, 96, 2048, 32768, 262144, 8388608, 35056, 1376256, -471859200, 0, 0, 14, 16, 224, 2048, 32768, 2097152, 4194304, 8388608, -486539264, 0, 96, 128, 2048, 32768, 262144, 2097152, 262144, 2097152, 8388608, 33554432, 536870912, 1073741824, 0x80000000, 0, 1610612736, 0x80000000, 0, 0, 1, 524288, 1048576, 12582912, 0, 0, 0, 151311, 264503296, 2097152, 8388608, 33554432, 1610612736, 0x80000000, 262144, 8388608, 33554432, 536870912, 67108864, 4194304, 0, 4194304, 0, 4194304, 4194304, 0, 0, 524288, 8388608, 536870912, 1073741824, 0x80000000, 1, 4097, 8388609, 96, 2048, 32768, 1073741824, 0x80000000, 0, 96, 2048, 0x80000000, 0, 0, 96, 2048, 0, 0, 1, 12582912, 0, 0, 0, 0, 1641895695, 1641895695, 0, 0, 0, 249, 7404800, 15, 87808, 1835008, 1639972864, 0, 768, 5120, 16384, 65536, 1835008, 1835008, 12582912, 16777216, 1610612736, 0, 3, 4, 8, 768, 4096, 65536, 0, 0, 256, 512, 786432, 8, 256, 512, 4096, 16384, 1835008, 16384, 1835008, 12582912, 1610612736, 0, 0, 0, 256, 0, 0, 0, 4, 8, 16, 32, 1, 2, 8, 256, 16384, 524288, 16384, 524288, 1048576, 12582912, 1610612736, 0, 0, 0, 8388608, 0, 0, 0, 524288, 4194304, 0, 0, 0, 8388608, -548662288, -548662288, -548662288, 0, 0, 256, 16384, 65536, 520093696, -1073741824, 0, 0, 0, 16777216, 0, 16, 32, 960, 4096, 4980736, 520093696, 1073741824, 0, 32, 896, 4096, 57344, 1048576, 6291456, 8388608, 16777216, 100663296, 134217728, 268435456, 0x80000000, 0, 512, 786432, 4194304, 33554432, 134217728, 268435456, 0, 786432, 4194304, 134217728, 268435456, 0, 524288, 4194304, 268435456, 0, 0, 0, 0, 0, 4194304, 4194304, -540651761, 0, 0, 0, 2, 4, 8, 16, 96, 128, 264503296, -805306368, 0, 0, 0, 8, 256, 512, 19456, 131072, 3072, 16384, 131072, 262144, 8388608, 16777216, 512, 1024, 2048, 16384, 131072, 262144, 131072, 262144, 8388608, 33554432, 201326592, 268435456, 0, 3, 4, 256, 1024, 2048, 57344, 16384, 131072, 8388608, 33554432, 134217728, 268435456, 0, 3, 256, 1024, 16384, 131072, 33554432, 134217728, 1073741824, 0x80000000, 0, 0, 256, 524288, 0x80000000, 0, 3, 256, 33554432, 134217728, 1073741824, 0, 1, 2, 33554432, 1, 2, 134217728, 1073741824, 0, 1, 2, 134217728, 0, 0, 0, 64, 0, 0, 0, 16, 32, 896, 4096, 786432, 4194304, 16777216, 33554432, 201326592, 268435456, 1073741824, 0x80000000, 0, 0, 0, 15, 0, 4980736, 4980736, 4980736, 70460, 70460, 3478332, 0, 0, 1008, 4984832, 520093696, 60, 4864, 65536, 0, 0, 0, 12, 16, 32, 256, 512, 4096, 65536, 0, 0, 0, 67108864, 0, 0, 0, 12, 0, 256, 512, 65536, 0, 0, 1024, 512, 131072, 131072, 4, 16, 32, 65536, 0, 4, 16, 32, 0, 0, 0, 4, 16, 0, 0, 16384, 67108864, 0, 0, 1, 24, 96, 128, 256, 1024 ]; JSONiqTokenizer.TOKEN = [ "(0)", "JSONChar", "JSONCharRef", "JSONPredefinedCharRef", "ModuleDecl", "Annotation", "OptionDecl", "Operator", "Variable", "Tag", "EndTag", "PragmaContents", "DirCommentContents", "DirPIContents", "CDataSectionContents", "AttrTest", "Wildcard", "EQName", "IntegerLiteral", "DecimalLiteral", "DoubleLiteral", "PredefinedEntityRef", "'\"\"'", "EscapeApos", "AposChar", "ElementContentChar", "QuotAttrContentChar", "AposAttrContentChar", "NCName", "QName", "S", "CharRef", "CommentContents", "DocTag", "DocCommentContents", "EOF", "'!'", "'\"'", "'#'", "'#)'", "'$$'", "''''", "'('", "'(#'", "'(:'", "'(:~'", "')'", "'*'", "'*'", "','", "'-->'", "'.'", "'/'", "'/>'", "':'", "':)'", "';'", "'<!--'", "'<![CDATA['", "'<?'", "'='", "'>'", "'?'", "'?>'", "'NaN'", "'['", "']'", "']]>'", "'after'", "'all'", "'allowing'", "'ancestor'", "'ancestor-or-self'", "'and'", "'any'", "'append'", "'array'", "'as'", "'ascending'", "'at'", "'attribute'", "'base-uri'", "'before'", "'boundary-space'", "'break'", "'by'", "'case'", "'cast'", "'castable'", "'catch'", "'check'", "'child'", "'collation'", "'collection'", "'comment'", "'constraint'", "'construction'", "'contains'", "'content'", "'context'", "'continue'", "'copy'", "'copy-namespaces'", "'count'", "'decimal-format'", "'decimal-separator'", "'declare'", "'default'", "'delete'", "'descendant'", "'descendant-or-self'", "'descending'", "'diacritics'", "'different'", "'digit'", "'distance'", "'div'", "'document'", "'document-node'", "'element'", "'else'", "'empty'", "'empty-sequence'", "'encoding'", "'end'", "'entire'", "'eq'", "'every'", "'exactly'", "'except'", "'exit'", "'external'", "'first'", "'following'", "'following-sibling'", "'for'", "'foreach'", "'foreign'", "'from'", "'ft-option'", "'ftand'", "'ftnot'", "'ftor'", "'function'", "'ge'", "'greatest'", "'group'", "'grouping-separator'", "'gt'", "'idiv'", "'if'", "'import'", "'in'", "'index'", "'infinity'", "'inherit'", "'insensitive'", "'insert'", "'instance'", "'integrity'", "'intersect'", "'into'", "'is'", "'item'", "'json'", "'json-item'", "'key'", "'language'", "'last'", "'lax'", "'le'", "'least'", "'let'", "'levels'", "'loop'", "'lowercase'", "'lt'", "'minus-sign'", "'mod'", "'modify'", "'module'", "'most'", "'namespace'", "'namespace-node'", "'ne'", "'next'", "'no'", "'no-inherit'", "'no-preserve'", "'node'", "'nodes'", "'not'", "'object'", "'occurs'", "'of'", "'on'", "'only'", "'option'", "'or'", "'order'", "'ordered'", "'ordering'", "'paragraph'", "'paragraphs'", "'parent'", "'pattern-separator'", "'per-mille'", "'percent'", "'phrase'", "'position'", "'preceding'", "'preceding-sibling'", "'preserve'", "'previous'", "'processing-instruction'", "'relationship'", "'rename'", "'replace'", "'return'", "'returning'", "'revalidation'", "'same'", "'satisfies'", "'schema'", "'schema-attribute'", "'schema-element'", "'score'", "'self'", "'sensitive'", "'sentence'", "'sentences'", "'skip'", "'sliding'", "'some'", "'stable'", "'start'", "'stemming'", "'stop'", "'strict'", "'strip'", "'structured-item'", "'switch'", "'text'", "'then'", "'thesaurus'", "'times'", "'to'", "'treat'", "'try'", "'tumbling'", "'type'", "'typeswitch'", "'union'", "'unique'", "'unordered'", "'updating'", "'uppercase'", "'using'", "'validate'", "'value'", "'variable'", "'version'", "'weight'", "'when'", "'where'", "'while'", "'wildcards'", "'window'", "'with'", "'without'", "'word'", "'words'", "'xquery'", "'zero-digit'", "'{'", "'{{'", "'|'", "'}'", "'}}'" ]; }, {}], 2:[function(_dereq_,module,exports){ 'use strict'; var JSONiqTokenizer = _dereq_('./JSONiqTokenizer').JSONiqTokenizer; var Lexer = _dereq_('./lexer').Lexer; var keys = 'NaN|after|allowing|ancestor|ancestor-or-self|and|append|array|as|ascending|at|attribute|base-uri|before|boundary-space|break|by|case|cast|castable|catch|child|collation|comment|constraint|construction|contains|context|continue|copy|copy-namespaces|count|decimal-format|decimal-separator|declare|default|delete|descendant|descendant-or-self|descending|digit|div|document|document-node|element|else|empty|empty-sequence|encoding|end|eq|every|except|exit|external|false|first|following|following-sibling|for|from|ft-option|function|ge|greatest|group|grouping-separator|gt|idiv|if|import|in|index|infinity|insert|instance|integrity|intersect|into|is|item|json|json-item|jsoniq|last|lax|le|least|let|loop|lt|minus-sign|mod|modify|module|namespace|namespace-node|ne|next|node|nodes|not|null|object|of|only|option|or|order|ordered|ordering|paragraphs|parent|pattern-separator|per-mille|percent|preceding|preceding-sibling|previous|processing-instruction|rename|replace|return|returning|revalidation|satisfies|schema|schema-attribute|schema-element|score|select|self|sentences|sliding|some|stable|start|strict|switch|text|then|times|to|treat|true|try|tumbling|type|typeswitch|union|unordered|updating|validate|value|variable|version|when|where|while|window|with|words|xquery|zero-digit'.split('|'); var keywords = keys.map(function(val) { return { name: '\'' + val + '\'', token: 'keyword' }; }); var ncnames = keys.map(function(val) { return { name: '\'' + val + '\'', token: 'text', next: function(stack){ stack.pop(); } }; }); var cdata = 'constant.language'; var number = 'constant'; var xmlcomment = 'comment'; var pi = 'xml-pe'; var pragma = 'constant.buildin'; var n = function(name){ return '\'' + name + '\''; }; var Rules = { start: [ { name: n('(#'), token: pragma, next: function(stack){ stack.push('Pragma'); } }, { name: n('(:'), token: 'comment', next: function(stack){ stack.push('Comment'); } }, { name: n('(:~'), token: 'comment.doc', next: function(stack){ stack.push('CommentDoc'); } }, { name: n('<!--'), token: xmlcomment, next: function(stack){ stack.push('XMLComment'); } }, { name: n('<?'), token: pi, next: function(stack) { stack.push('PI'); } }, { name: n('\'\''), token: 'string', next: function(stack){ stack.push('AposString'); } }, { name: n('"'), token: 'string', next: function(stack){ stack.push('QuotString'); } }, { name: 'Annotation', token: 'support.function' }, { name: 'ModuleDecl', token: 'keyword', next: function(stack){ stack.push('Prefix'); } }, { name: 'OptionDecl', token: 'keyword', next: function(stack){ stack.push('_EQName'); } }, { name: 'AttrTest', token: 'support.type' }, { name: 'Variable', token: 'variable' }, { name: n('<![CDATA['), token: cdata, next: function(stack){ stack.push('CData'); } }, { name: 'IntegerLiteral', token: number }, { name: 'DecimalLiteral', token: number }, { name: 'DoubleLiteral', token: number }, { name: 'Operator', token: 'keyword.operator' }, { name: 'EQName', token: function(val) { return keys.indexOf(val) !== -1 ? 'keyword' : 'support.function'; } }, { name: n('('), token: 'lparen' }, { name: n(')'), token: 'rparen' }, { name: 'Tag', token: 'meta.tag', next: function(stack){ stack.push('StartTag'); } }, { name: n('}'), token: 'text', next: function(stack){ if(stack.length > 1) { stack.pop(); } } }, { name: n('{'), token: 'text', next: function(stack){ stack.push('start'); } } //, next: function(stack){ if(stack.length > 1) { stack.pop(); } } } ].concat(keywords), _EQName: [ { name: 'EQName', token: 'text', next: function(stack) { stack.pop(); } } ].concat(ncnames), Prefix: [ { name: 'NCName', token: 'text', next: function(stack) { stack.pop(); } } ].concat(ncnames), StartTag: [ { name: n('>'), token: 'meta.tag', next: function(stack){ stack.push('TagContent'); } }, { name: 'QName', token: 'entity.other.attribute-name' }, { name: n('='), token: 'text' }, { name: n('\'\''), token: 'string', next: function(stack){ stack.push('AposAttr'); } }, { name: n('"'), token: 'string', next: function(stack){ stack.push('QuotAttr'); } }, { name: n('/>'), token: 'meta.tag.r', next: function(stack){ stack.pop(); } } ], TagContent: [ { name: 'ElementContentChar', token: 'text' }, { name: n('<![CDATA['), token: cdata, next: function(stack){ stack.push('CData'); } }, { name: n('<!--'), token: xmlcomment, next: function(stack){ stack.push('XMLComment'); } }, { name: 'Tag', token: 'meta.tag', next: function(stack){ stack.push('StartTag'); } }, { name: 'PredefinedEntityRef', token: 'constant.language.escape' }, { name: 'CharRef', token: 'constant.language.escape' }, { name: n('{{'), token: 'text' }, { name: n('}}'), token: 'text' }, { name: n('{'), token: 'text', next: function(stack){ stack.push('start'); } }, { name: 'EndTag', token: 'meta.tag', next: function(stack){ stack.pop(); stack.pop(); } } ], AposAttr: [ { name: n('\'\''), token: 'string', next: function(stack){ stack.pop(); } }, { name: 'EscapeApos', token: 'constant.language.escape' }, { name: 'AposAttrContentChar', token: 'string' }, { name: 'PredefinedEntityRef', token: 'constant.language.escape' }, { name: 'CharRef', token: 'constant.language.escape' }, { name: n('{{'), token: 'string' }, { name: n('}}'), token: 'string' }, { name: n('{'), token: 'text', next: function(stack){ stack.push('start'); } } ], QuotAttr: [ { name: n('\"'), token: 'string', next: function(stack){ stack.pop(); } }, { name: 'EscapeQuot', token: 'constant.language.escape' }, { name: 'QuotAttrContentChar', token: 'string' }, { name: 'PredefinedEntityRef', token: 'constant.language.escape' }, { name: 'CharRef', token: 'constant.language.escape' }, { name: n('{{'), token: 'string' }, { name: n('}}'), token: 'string' }, { name: n('{'), token: 'text', next: function(stack){ stack.push('start'); } } ], Pragma: [ { name: 'PragmaContents', token: pragma }, { name: n('#'), token: pragma }, { name: n('#)'), token: pragma, next: function(stack){ stack.pop(); } } ], Comment: [ { name: 'CommentContents', token: 'comment' }, { name: n('(:'), token: 'comment', next: function(stack){ stack.push('Comment'); } }, { name: n(':)'), token: 'comment', next: function(stack){ stack.pop(); } } ], CommentDoc: [ { name: 'DocCommentContents', token: 'comment.doc' }, { name: 'DocTag', token: 'comment.doc.tag' }, { name: n('(:'), token: 'comment.doc', next: function(stack){ stack.push('CommentDoc'); } }, { name: n(':)'), token: 'comment.doc', next: function(stack){ stack.pop(); } } ], XMLComment: [ { name: 'DirCommentContents', token: xmlcomment }, { name: n('-->'), token: xmlcomment, next: function(stack){ stack.pop(); } } ], CData: [ { name: 'CDataSectionContents', token: cdata }, { name: n(']]>'), token: cdata, next: function(stack){ stack.pop(); } } ], PI: [ { name: 'DirPIContents', token: pi }, { name: n('?'), token: pi }, { name: n('?>'), token: pi, next: function(stack){ stack.pop(); } } ], AposString: [ { name: n('\'\''), token: 'string', next: function(stack){ stack.pop(); } }, { name: 'PredefinedEntityRef', token: 'constant.language.escape' }, { name: 'CharRef', token: 'constant.language.escape' }, { name: 'EscapeApos', token: 'constant.language.escape' }, { name: 'AposChar', token: 'string' } ], QuotString: [ { name: n('"'), token: 'string', next: function(stack){ stack.pop(); } }, { name: 'JSONPredefinedCharRef', token: 'constant.language.escape' }, { name: 'JSONCharRef', token: 'constant.language.escape' }, { name: 'JSONChar', token: 'string' } ] }; exports.JSONiqLexer = function(){ return new Lexer(JSONiqTokenizer, Rules); }; }, {"./JSONiqTokenizer":1,"./lexer":3}], 3:[function(_dereq_,module,exports){ 'use strict'; var TokenHandler = function(code) { var input = code; this.tokens = []; this.reset = function() { input = input; this.tokens = []; }; this.startNonterminal = function() {}; this.endNonterminal = function() {}; this.terminal = function(name, begin, end) { this.tokens.push({ name: name, value: input.substring(begin, end) }); }; this.whitespace = function(begin, end) { this.tokens.push({ name: 'WS', value: input.substring(begin, end) }); }; }; exports.Lexer = function(Tokenizer, Rules) { this.tokens = []; this.getLineTokens = function(line, state) { state = (state === 'start' || !state) ? '["start"]' : state; var stack = JSON.parse(state); var h = new TokenHandler(line); var tokenizer = new Tokenizer(line, h); var tokens = []; while(true) { var currentState = stack[stack.length - 1]; try { h.tokens = []; tokenizer['parse_' + currentState](); var info = null; if(h.tokens.length > 1 && h.tokens[0].name === 'WS') { tokens.push({ type: 'text', value: h.tokens[0].value }); h.tokens.splice(0, 1); } var token = h.tokens[0]; var rules = Rules[currentState]; for(var k = 0; k < rules.length; k++) { var rule = Rules[currentState][k]; if((typeof(rule.name) === 'function' && rule.name(token)) || rule.name === token.name) { info = rule; break; } } if(token.name === 'EOF') { break; } if(token.value === '') { throw 'Encountered empty string lexical rule.'; } tokens.push({ type: info === null ? 'text' : (typeof(info.token) === 'function' ? info.token(token.value) : info.token), value: token.value }); if(info && info.next) { info.next(stack); } } catch(e) { if(e instanceof tokenizer.ParseException) { var index = 0; for(var i=0; i < tokens.length; i++) { index += tokens[i].value.length; } tokens.push({ type: 'text', value: line.substring(index) }); return { tokens: tokens, state: JSON.stringify(['start']) }; } else { throw e; } } } return { tokens: tokens, state: JSON.stringify(stack) }; }; }; }, {}]},{},[2]) (2) }); ace.define("ace/mode/behaviour/cstyle",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); var SAFE_INSERT_IN_TOKENS = ["text", "paren.rparen", "punctuation.operator"]; var SAFE_INSERT_BEFORE_TOKENS = ["text", "paren.rparen", "punctuation.operator", "comment"]; var context; var contextCache = {}; var initContext = function(editor) { var id = -1; if (editor.multiSelect) { id = editor.selection.index; if (contextCache.rangeCount != editor.multiSelect.rangeCount) contextCache = {rangeCount: editor.multiSelect.rangeCount}; } if (contextCache[id]) return context = contextCache[id]; context = contextCache[id] = { autoInsertedBrackets: 0, autoInsertedRow: -1, autoInsertedLineEnd: "", maybeInsertedBrackets: 0, maybeInsertedRow: -1, maybeInsertedLineStart: "", maybeInsertedLineEnd: "" }; }; var getWrapped = function(selection, selected, opening, closing) { var rowDiff = selection.end.row - selection.start.row; return { text: opening + selected + closing, selection: [ 0, selection.start.column + 1, rowDiff, selection.end.column + (rowDiff ? 0 : 1) ] }; }; var CstyleBehaviour = function() { this.add("braces", "insertion", function(state, action, editor, session, text) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (text == '{') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "{" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '{', '}'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { if (/[\]\}\)]/.test(line[cursor.column]) || editor.inMultiSelectMode) { CstyleBehaviour.recordAutoInsert(editor, session, "}"); return { text: '{}', selection: [1, 1] }; } else { CstyleBehaviour.recordMaybeInsert(editor, session, "{"); return { text: '{', selection: [1, 1] }; } } } else if (text == '}') { initContext(editor); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == '}') { var matching = session.$findOpeningBracket('}', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } else if (text == "\n" || text == "\r\n") { initContext(editor); var closing = ""; if (CstyleBehaviour.isMaybeInsertedClosing(cursor, line)) { closing = lang.stringRepeat("}", context.maybeInsertedBrackets); CstyleBehaviour.clearMaybeInsertedClosing(); } var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar === '}') { var openBracePos = session.findMatchingBracket({row: cursor.row, column: cursor.column+1}, '}'); if (!openBracePos) return null; var next_indent = this.$getIndent(session.getLine(openBracePos.row)); } else if (closing) { var next_indent = this.$getIndent(line); } else { CstyleBehaviour.clearMaybeInsertedClosing(); return; } var indent = next_indent + session.getTabString(); return { text: '\n' + indent + '\n' + next_indent + closing, selection: [1, indent.length, 1, indent.length] }; } else { CstyleBehaviour.clearMaybeInsertedClosing(); } }); this.add("braces", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '{') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.end.column, range.end.column + 1); if (rightChar == '}') { range.end.column++; return range; } else { context.maybeInsertedBrackets--; } } }); this.add("parens", "insertion", function(state, action, editor, session, text) { if (text == '(') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '(', ')'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, ")"); return { text: '()', selection: [1, 1] }; } } else if (text == ')') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ')') { var matching = session.$findOpeningBracket(')', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("parens", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '(') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ')') { range.end.column++; return range; } } }); this.add("brackets", "insertion", function(state, action, editor, session, text) { if (text == '[') { initContext(editor); var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, '[', ']'); } else if (CstyleBehaviour.isSaneInsertion(editor, session)) { CstyleBehaviour.recordAutoInsert(editor, session, "]"); return { text: '[]', selection: [1, 1] }; } } else if (text == ']') { initContext(editor); var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); if (rightChar == ']') { var matching = session.$findOpeningBracket(']', {column: cursor.column + 1, row: cursor.row}); if (matching !== null && CstyleBehaviour.isAutoInsertedClosing(cursor, line, text)) { CstyleBehaviour.popAutoInsertedClosing(); return { text: '', selection: [1, 1] }; } } } }); this.add("brackets", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && selected == '[') { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == ']') { range.end.column++; return range; } } }); this.add("string_dquotes", "insertion", function(state, action, editor, session, text) { if (text == '"' || text == "'") { initContext(editor); var quote = text; var selection = editor.getSelectionRange(); var selected = session.doc.getTextRange(selection); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return getWrapped(selection, selected, quote, quote); } else if (!selected) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var leftChar = line.substring(cursor.column-1, cursor.column); var rightChar = line.substring(cursor.column, cursor.column + 1); var token = session.getTokenAt(cursor.row, cursor.column); var rightToken = session.getTokenAt(cursor.row, cursor.column + 1); if (leftChar == "\\" && token && /escape/.test(token.type)) return null; var stringBefore = token && /string|escape/.test(token.type); var stringAfter = !rightToken || /string|escape/.test(rightToken.type); var pair; if (rightChar == quote) { pair = stringBefore !== stringAfter; } else { if (stringBefore && !stringAfter) return null; // wrap string with different quote if (stringBefore && stringAfter) return null; // do not pair quotes inside strings var wordRe = session.$mode.tokenRe; wordRe.lastIndex = 0; var isWordBefore = wordRe.test(leftChar); wordRe.lastIndex = 0; var isWordAfter = wordRe.test(leftChar); if (isWordBefore || isWordAfter) return null; // before or after alphanumeric if (rightChar && !/[\s;,.})\]\\]/.test(rightChar)) return null; // there is rightChar and it isn't closing pair = true; } return { text: pair ? quote + quote : "", selection: [1,1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { initContext(editor); var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); }; CstyleBehaviour.isSaneInsertion = function(editor, session) { var cursor = editor.getCursorPosition(); var iterator = new TokenIterator(session, cursor.row, cursor.column); if (!this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) { var iterator2 = new TokenIterator(session, cursor.row, cursor.column + 1); if (!this.$matchTokenType(iterator2.getCurrentToken() || "text", SAFE_INSERT_IN_TOKENS)) return false; } iterator.stepForward(); return iterator.getCurrentTokenRow() !== cursor.row || this.$matchTokenType(iterator.getCurrentToken() || "text", SAFE_INSERT_BEFORE_TOKENS); }; CstyleBehaviour.$matchTokenType = function(token, types) { return types.indexOf(token.type || token) > -1; }; CstyleBehaviour.recordAutoInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isAutoInsertedClosing(cursor, line, context.autoInsertedLineEnd[0])) context.autoInsertedBrackets = 0; context.autoInsertedRow = cursor.row; context.autoInsertedLineEnd = bracket + line.substr(cursor.column); context.autoInsertedBrackets++; }; CstyleBehaviour.recordMaybeInsert = function(editor, session, bracket) { var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); if (!this.isMaybeInsertedClosing(cursor, line)) context.maybeInsertedBrackets = 0; context.maybeInsertedRow = cursor.row; context.maybeInsertedLineStart = line.substr(0, cursor.column) + bracket; context.maybeInsertedLineEnd = line.substr(cursor.column); context.maybeInsertedBrackets++; }; CstyleBehaviour.isAutoInsertedClosing = function(cursor, line, bracket) { return context.autoInsertedBrackets > 0 && cursor.row === context.autoInsertedRow && bracket === context.autoInsertedLineEnd[0] && line.substr(cursor.column) === context.autoInsertedLineEnd; }; CstyleBehaviour.isMaybeInsertedClosing = function(cursor, line) { return context.maybeInsertedBrackets > 0 && cursor.row === context.maybeInsertedRow && line.substr(cursor.column) === context.maybeInsertedLineEnd && line.substr(0, cursor.column) == context.maybeInsertedLineStart; }; CstyleBehaviour.popAutoInsertedClosing = function() { context.autoInsertedLineEnd = context.autoInsertedLineEnd.substr(1); context.autoInsertedBrackets--; }; CstyleBehaviour.clearMaybeInsertedClosing = function() { if (context) { context.maybeInsertedBrackets = 0; context.maybeInsertedRow = -1; } }; oop.inherits(CstyleBehaviour, Behaviour); exports.CstyleBehaviour = CstyleBehaviour; }); ace.define("ace/mode/behaviour/xml",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/token_iterator","ace/lib/lang"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require("../behaviour").Behaviour; var TokenIterator = require("../../token_iterator").TokenIterator; var lang = require("../../lib/lang"); function is(token, type) { return token.type.lastIndexOf(type + ".xml") > -1; } var XmlBehaviour = function () { this.add("string_dquotes", "insertion", function (state, action, editor, session, text) { if (text == '"' || text == "'") { var quote = text; var selected = session.doc.getTextRange(editor.getSelectionRange()); if (selected !== "" && selected !== "'" && selected != '"' && editor.getWrapBehavioursEnabled()) { return { text: quote + selected + quote, selection: false }; } var cursor = editor.getCursorPosition(); var line = session.doc.getLine(cursor.row); var rightChar = line.substring(cursor.column, cursor.column + 1); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (rightChar == quote && (is(token, "attribute-value") || is(token, "string"))) { return { text: "", selection: [1, 1] }; } if (!token) token = iterator.stepBackward(); if (!token) return; while (is(token, "tag-whitespace") || is(token, "whitespace")) { token = iterator.stepBackward(); } var rightSpace = !rightChar || rightChar.match(/\s/); if (is(token, "attribute-equals") && (rightSpace || rightChar == '>') || (is(token, "decl-attribute-equals") && (rightSpace || rightChar == '?'))) { return { text: quote + quote, selection: [1, 1] }; } } }); this.add("string_dquotes", "deletion", function(state, action, editor, session, range) { var selected = session.doc.getTextRange(range); if (!range.isMultiLine() && (selected == '"' || selected == "'")) { var line = session.doc.getLine(range.start.row); var rightChar = line.substring(range.start.column + 1, range.start.column + 2); if (rightChar == selected) { range.end.column++; return range; } } }); this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getCursorPosition(); var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken() || iterator.stepBackward(); if (!token || !(is(token, "tag-name") || is(token, "tag-whitespace") || is(token, "attribute-name") || is(token, "attribute-equals") || is(token, "attribute-value"))) return; if (is(token, "reference.attribute-value")) return; if (is(token, "attribute-value")) { var firstChar = token.value.charAt(0); if (firstChar == '"' || firstChar == "'") { var lastChar = token.value.charAt(token.value.length - 1); var tokenEnd = iterator.getCurrentTokenColumn() + token.value.length; if (tokenEnd > position.column || tokenEnd == position.column && firstChar != lastChar) return; } } while (!is(token, "tag-name")) { token = iterator.stepBackward(); } var tokenRow = iterator.getCurrentTokenRow(); var tokenColumn = iterator.getCurrentTokenColumn(); if (is(iterator.stepBackward(), "end-tag-open")) return; var element = token.value; if (tokenRow == position.row) element = element.substring(0, position.column - tokenColumn); if (this.voidElements.hasOwnProperty(element.toLowerCase())) return; return { text: ">" + "</" + element + ">", selection: [1, 1] }; } }); this.add("autoindent", "insertion", function (state, action, editor, session, text) { if (text == "\n") { var cursor = editor.getCursorPosition(); var line = session.getLine(cursor.row); var iterator = new TokenIterator(session, cursor.row, cursor.column); var token = iterator.getCurrentToken(); if (token && token.type.indexOf("tag-close") !== -1) { if (token.value == "/>") return; while (token && token.type.indexOf("tag-name") === -1) { token = iterator.stepBackward(); } if (!token) { return; } var tag = token.value; var row = iterator.getCurrentTokenRow(); token = iterator.stepBackward(); if (!token || token.type.indexOf("end-tag") !== -1) { return; } if (this.voidElements && !this.voidElements[tag]) { var nextToken = session.getTokenAt(cursor.row, cursor.column+1); var line = session.getLine(row); var nextIndent = this.$getIndent(line); var indent = nextIndent + session.getTabString(); if (nextToken && nextToken.value === "</") { return { text: "\n" + indent + "\n" + nextIndent, selection: [1, indent.length, 1, indent.length] }; } else { return { text: "\n" + indent }; } } } } }); }; oop.inherits(XmlBehaviour, Behaviour); exports.XmlBehaviour = XmlBehaviour; }); ace.define("ace/mode/behaviour/xquery",["require","exports","module","ace/lib/oop","ace/mode/behaviour","ace/mode/behaviour/cstyle","ace/mode/behaviour/xml","ace/token_iterator"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Behaviour = require('../behaviour').Behaviour; var CstyleBehaviour = require('./cstyle').CstyleBehaviour; var XmlBehaviour = require("../behaviour/xml").XmlBehaviour; var TokenIterator = require("../../token_iterator").TokenIterator; function hasType(token, type) { var hasType = true; var typeList = token.type.split('.'); var needleList = type.split('.'); needleList.forEach(function(needle){ if (typeList.indexOf(needle) == -1) { hasType = false; return false; } }); return hasType; } var XQueryBehaviour = function () { this.inherit(CstyleBehaviour, ["braces", "parens", "string_dquotes"]); // Get string behaviour this.inherit(XmlBehaviour); // Get xml behaviour this.add("autoclosing", "insertion", function (state, action, editor, session, text) { if (text == '>') { var position = editor.getCursorPosition(); var iterator = new TokenIterator(session, position.row, position.column); var token = iterator.getCurrentToken(); var atCursor = false; var state = JSON.parse(state).pop(); if ((token && token.value === '>') || state !== "StartTag") return; if (!token || !hasType(token, 'meta.tag') && !(hasType(token, 'text') && token.value.match('/'))){ do { token = iterator.stepBackward(); } while (token && (hasType(token, 'string') || hasType(token, 'keyword.operator') || hasType(token, 'entity.attribute-name') || hasType(token, 'text'))); } else { atCursor = true; } var previous = iterator.stepBackward(); if (!token || !hasType(token, 'meta.tag') || (previous !== null && previous.value.match('/'))) { return } var tag = token.value.substring(1); if (atCursor){ var tag = tag.substring(0, position.column - token.start); } return { text: '>' + '</' + tag + '>', selection: [1, 1] } } }); } oop.inherits(XQueryBehaviour, Behaviour); exports.XQueryBehaviour = XQueryBehaviour; }); ace.define("ace/mode/folding/cstyle",["require","exports","module","ace/lib/oop","ace/range","ace/mode/folding/fold_mode"], function(require, exports, module) { "use strict"; var oop = require("../../lib/oop"); var Range = require("../../range").Range; var BaseFoldMode = require("./fold_mode").FoldMode; var FoldMode = exports.FoldMode = function(commentRegex) { if (commentRegex) { this.foldingStartMarker = new RegExp( this.foldingStartMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.start) ); this.foldingStopMarker = new RegExp( this.foldingStopMarker.source.replace(/\|[^|]*?$/, "|" + commentRegex.end) ); } }; oop.inherits(FoldMode, BaseFoldMode); (function() { this.foldingStartMarker = /(\{|\[)[^\}\]]*$|^\s*(\/\*)/; this.foldingStopMarker = /^[^\[\{]*(\}|\])|^[\s\*]*(\*\/)/; this.singleLineBlockCommentRe= /^\s*(\/\*).*\*\/\s*$/; this.tripleStarBlockCommentRe = /^\s*(\/\*\*\*).*\*\/\s*$/; this.startRegionRe = /^\s*(\/\*|\/\/)#?region\b/; this._getFoldWidgetBase = this.getFoldWidget; this.getFoldWidget = function(session, foldStyle, row) { var line = session.getLine(row); if (this.singleLineBlockCommentRe.test(line)) { if (!this.startRegionRe.test(line) && !this.tripleStarBlockCommentRe.test(line)) return ""; } var fw = this._getFoldWidgetBase(session, foldStyle, row); if (!fw && this.startRegionRe.test(line)) return "start"; // lineCommentRegionStart return fw; }; this.getFoldWidgetRange = function(session, foldStyle, row, forceMultiline) { var line = session.getLine(row); if (this.startRegionRe.test(line)) return this.getCommentRegionBlock(session, line, row); var match = line.match(this.foldingStartMarker); if (match) { var i = match.index; if (match[1]) return this.openingBracketBlock(session, match[1], row, i); var range = session.getCommentFoldRange(row, i + match[0].length, 1); if (range && !range.isMultiLine()) { if (forceMultiline) { range = this.getSectionRange(session, row); } else if (foldStyle != "all") range = null; } return range; } if (foldStyle === "markbegin") return; var match = line.match(this.foldingStopMarker); if (match) { var i = match.index + match[0].length; if (match[1]) return this.closingBracketBlock(session, match[1], row, i); return session.getCommentFoldRange(row, i, -1); } }; this.getSectionRange = function(session, row) { var line = session.getLine(row); var startIndent = line.search(/\S/); var startRow = row; var startColumn = line.length; row = row + 1; var endRow = row; var maxRow = session.getLength(); while (++row < maxRow) { line = session.getLine(row); var indent = line.search(/\S/); if (indent === -1) continue; if (startIndent > indent) break; var subRange = this.getFoldWidgetRange(session, "all", row); if (subRange) { if (subRange.start.row <= startRow) { break; } else if (subRange.isMultiLine()) { row = subRange.end.row; } else if (startIndent == indent) { break; } } endRow = row; } return new Range(startRow, startColumn, endRow, session.getLine(endRow).length); }; this.getCommentRegionBlock = function(session, line, row) { var startColumn = line.search(/\s*$/); var maxRow = session.getLength(); var startRow = row; var re = /^\s*(?:\/\*|\/\/|--)#?(end)?region\b/; var depth = 1; while (++row < maxRow) { line = session.getLine(row); var m = re.exec(line); if (!m) continue; if (m[1]) depth--; else depth++; if (!depth) break; } var endRow = row; if (endRow > startRow) { return new Range(startRow, startColumn, endRow, line.length); } }; }).call(FoldMode.prototype); }); ace.define("ace/mode/jsoniq",["require","exports","module","ace/worker/worker_client","ace/lib/oop","ace/mode/text","ace/mode/text_highlight_rules","ace/mode/xquery/jsoniq_lexer","ace/range","ace/mode/behaviour/xquery","ace/mode/folding/cstyle","ace/anchor"], function(require, exports, module) { "use strict"; var WorkerClient = require("../worker/worker_client").WorkerClient; var oop = require("../lib/oop"); var TextMode = require("./text").Mode; var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules; var JSONiqLexer = require("./xquery/jsoniq_lexer").JSONiqLexer; var Range = require("../range").Range; var XQueryBehaviour = require("./behaviour/xquery").XQueryBehaviour; var CStyleFoldMode = require("./folding/cstyle").FoldMode; var Anchor = require("../anchor").Anchor; var Mode = function() { this.$tokenizer = new JSONiqLexer(); this.$behaviour = new XQueryBehaviour(); this.foldingRules = new CStyleFoldMode(); this.$highlightRules = new TextHighlightRules(); }; oop.inherits(Mode, TextMode); (function() { this.completer = { getCompletions: function(editor, session, pos, prefix, callback) { if (!session.$worker) return callback(); session.$worker.emit("complete", { data: { pos: pos, prefix: prefix } }); session.$worker.on("complete", function(e){ callback(null, e.data); }); } }; this.getNextLineIndent = function(state, line, tab) { var indent = this.$getIndent(line); var match = line.match(/\s*(?:then|else|return|[{\(]|<\w+>)\s*$/); if (match) indent += tab; return indent; }; this.checkOutdent = function(state, line, input) { if (! /^\s+$/.test(line)) return false; return /^\s*[\}\)]/.test(input); }; this.autoOutdent = function(state, doc, row) { var line = doc.getLine(row); var match = line.match(/^(\s*[\}\)])/); if (!match) return 0; var column = match[1].length; var openBracePos = doc.findMatchingBracket({row: row, column: column}); if (!openBracePos || openBracePos.row == row) return 0; var indent = this.$getIndent(doc.getLine(openBracePos.row)); doc.replace(new Range(row, 0, row, column-1), indent); }; this.toggleCommentLines = function(state, doc, startRow, endRow) { var i, line; var outdent = true; var re = /^\s*\(:(.*):\)/; for (i=startRow; i<= endRow; i++) { if (!re.test(doc.getLine(i))) { outdent = false; break; } } var range = new Range(0, 0, 0, 0); for (i=startRow; i<= endRow; i++) { line = doc.getLine(i); range.start.row = i; range.end.row = i; range.end.column = line.length; doc.replace(range, outdent ? line.match(re)[1] : "(:" + line + ":)"); } }; this.createWorker = function(session) { var worker = new WorkerClient(["ace"], "ace/mode/xquery_worker", "XQueryWorker"); var that = this; worker.attachToDocument(session.getDocument()); worker.on("ok", function(e) { session.clearAnnotations(); }); worker.on("markers", function(e) { session.clearAnnotations(); that.addMarkers(e.data, session); }); return worker; }; this.removeMarkers = function(session) { var markers = session.getMarkers(false); for (var id in markers) { if (markers[id].clazz.indexOf('language_highlight_') === 0) { session.removeMarker(id); } } for (var i = 0; i < session.markerAnchors.length; i++) { session.markerAnchors[i].detach(); } session.markerAnchors = []; }; this.addMarkers = function(annos, mySession) { var _self = this; if (!mySession.markerAnchors) mySession.markerAnchors = []; this.removeMarkers(mySession); mySession.languageAnnos = []; annos.forEach(function(anno) { var anchor = new Anchor(mySession.getDocument(), anno.pos.sl, anno.pos.sc || 0); mySession.markerAnchors.push(anchor); var markerId; var colDiff = anno.pos.ec - anno.pos.sc; var rowDiff = anno.pos.el - anno.pos.sl; var gutterAnno = { guttertext: anno.message, type: anno.level || "warning", text: anno.message }; function updateFloat(single) { if (markerId) mySession.removeMarker(markerId); gutterAnno.row = anchor.row; if (anno.pos.sc !== undefined && anno.pos.ec !== undefined) { var range = new Range(anno.pos.sl, anno.pos.sc, anno.pos.el, anno.pos.ec); markerId = mySession.addMarker(range, "language_highlight_" + (anno.type ? anno.type : "default")); } if (single) mySession.setAnnotations(mySession.languageAnnos); } updateFloat(); anchor.on("change", function() { updateFloat(true); }); if (anno.message) mySession.languageAnnos.push(gutterAnno); }); mySession.setAnnotations(mySession.languageAnnos); }; this.$id = "ace/mode/jsoniq"; }).call(Mode.prototype); exports.Mode = Mode; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/libs/sinon.js
4,081
/** * Sinon.JS 1.4.2, 2012/07/11 * * @author Christian Johansen ([email protected]) * @author Contributors: https://github.com/cjohansen/Sinon.JS/blob/master/AUTHORS * * (The BSD License) * * Copyright (c) 2010-2012, Christian Johansen, [email protected] * 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 Christian Johansen nor the names of his contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ "use strict"; var sinon = (function () { var buster = (function (setTimeout, B) { var isNode = typeof require == "function" && typeof module == "object"; var div = typeof document != "undefined" && document.createElement("div"); var F = function () {}; var buster = { bind: function bind(obj, methOrProp) { var method = typeof methOrProp == "string" ? obj[methOrProp] : methOrProp; var args = Array.prototype.slice.call(arguments, 2); return function () { var allArgs = args.concat(Array.prototype.slice.call(arguments)); return method.apply(obj, allArgs); }; }, partial: function partial(fn) { var args = [].slice.call(arguments, 1); return function () { return fn.apply(this, args.concat([].slice.call(arguments))); }; }, create: function create(object) { F.prototype = object; return new F(); }, extend: function extend(target) { if (!target) { return; } for (var i = 1, l = arguments.length, prop; i < l; ++i) { for (prop in arguments[i]) { target[prop] = arguments[i][prop]; } } return target; }, nextTick: function nextTick(callback) { if (typeof process != "undefined" && process.nextTick) { return process.nextTick(callback); } setTimeout(callback, 0); }, functionName: function functionName(func) { if (!func) return ""; if (func.displayName) return func.displayName; if (func.name) return func.name; var matches = func.toString().match(/function\s+([^\(]+)/m); return matches && matches[1] || ""; }, isNode: function isNode(obj) { if (!div) return false; try { obj.appendChild(div); obj.removeChild(div); } catch (e) { return false; } return true; }, isElement: function isElement(obj) { return obj && obj.nodeType === 1 && buster.isNode(obj); }, isArray: function isArray(arr) { return Object.prototype.toString.call(arr) == "[object Array]"; }, flatten: function flatten(arr) { var result = [], arr = arr || []; for (var i = 0, l = arr.length; i < l; ++i) { result = result.concat(buster.isArray(arr[i]) ? flatten(arr[i]) : arr[i]); } return result; }, each: function each(arr, callback) { for (var i = 0, l = arr.length; i < l; ++i) { callback(arr[i]); } }, map: function map(arr, callback) { var results = []; for (var i = 0, l = arr.length; i < l; ++i) { results.push(callback(arr[i])); } return results; }, parallel: function parallel(fns, callback) { function cb(err, res) { if (typeof callback == "function") { callback(err, res); callback = null; } } if (fns.length == 0) { return cb(null, []); } var remaining = fns.length, results = []; function makeDone(num) { return function done(err, result) { if (err) { return cb(err); } results[num] = result; if (--remaining == 0) { cb(null, results); } }; } for (var i = 0, l = fns.length; i < l; ++i) { fns[i](makeDone(i)); } }, series: function series(fns, callback) { function cb(err, res) { if (typeof callback == "function") { callback(err, res); } } var remaining = fns.slice(); var results = []; function callNext() { if (remaining.length == 0) return cb(null, results); var promise = remaining.shift()(next); if (promise && typeof promise.then == "function") { promise.then(buster.partial(next, null), next); } } function next(err, result) { if (err) return cb(err); results.push(result); callNext(); } callNext(); }, countdown: function countdown(num, done) { return function () { if (--num == 0) done(); }; } }; if (typeof process === "object" && typeof require === "function" && typeof module === "object") { var crypto = require("crypto"); var path = require("path"); buster.tmpFile = function (fileName) { var hashed = crypto.createHash("sha1"); hashed.update(fileName); var tmpfileName = hashed.digest("hex"); if (process.platform == "win32") { return path.join(process.env["TEMP"], tmpfileName); } else { return path.join("/tmp", tmpfileName); } }; } if (Array.prototype.some) { buster.some = function (arr, fn, thisp) { return arr.some(fn, thisp); }; } else { // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/some buster.some = function (arr, fun, thisp) { if (arr == null) { throw new TypeError(); } arr = Object(arr); var len = arr.length >>> 0; if (typeof fun !== "function") { throw new TypeError(); } for (var i = 0; i < len; i++) { if (arr.hasOwnProperty(i) && fun.call(thisp, arr[i], i, arr)) { return true; } } return false; }; } if (Array.prototype.filter) { buster.filter = function (arr, fn, thisp) { return arr.filter(fn, thisp); }; } else { // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter buster.filter = function (fn, thisp) { if (this == null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; if (typeof fn != "function") { throw new TypeError(); } var res = []; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // in case fun mutates this if (fn.call(thisp, val, i, t)) { res.push(val); } } } return res; }; } if (isNode) { module.exports = buster; buster.eventEmitter = require("./buster-event-emitter"); Object.defineProperty(buster, "defineVersionGetter", { get: function () { return require("./define-version-getter"); } }); } return buster.extend(B || {}, buster); }(setTimeout, buster)); if (typeof buster === "undefined") { var buster = {}; } if (typeof module === "object" && typeof require === "function") { buster = require("buster-core"); } buster.format = buster.format || {}; buster.format.excludeConstructors = ["Object", /^.$/]; buster.format.quoteStrings = true; buster.format.ascii = (function () { var hasOwn = Object.prototype.hasOwnProperty; var specialObjects = []; if (typeof global != "undefined") { specialObjects.push({ obj: global, value: "[object global]" }); } if (typeof document != "undefined") { specialObjects.push({ obj: document, value: "[object HTMLDocument]" }); } if (typeof window != "undefined") { specialObjects.push({ obj: window, value: "[object Window]" }); } function keys(object) { var k = Object.keys && Object.keys(object) || []; if (k.length == 0) { for (var prop in object) { if (hasOwn.call(object, prop)) { k.push(prop); } } } return k.sort(); } function isCircular(object, objects) { if (typeof object != "object") { return false; } for (var i = 0, l = objects.length; i < l; ++i) { if (objects[i] === object) { return true; } } return false; } function ascii(object, processed, indent) { if (typeof object == "string") { var quote = typeof this.quoteStrings != "boolean" || this.quoteStrings; return processed || quote ? '"' + object + '"' : object; } if (typeof object == "function" && !(object instanceof RegExp)) { return ascii.func(object); } processed = processed || []; if (isCircular(object, processed)) { return "[Circular]"; } if (Object.prototype.toString.call(object) == "[object Array]") { return ascii.array.call(this, object, processed); } if (!object) { return "" + object; } if (buster.isElement(object)) { return ascii.element(object); } if (typeof object.toString == "function" && object.toString !== Object.prototype.toString) { return object.toString(); } for (var i = 0, l = specialObjects.length; i < l; i++) { if (object === specialObjects[i].obj) { return specialObjects[i].value; } } return ascii.object.call(this, object, processed, indent); } ascii.func = function (func) { return "function " + buster.functionName(func) + "() {}"; }; ascii.array = function (array, processed) { processed = processed || []; processed.push(array); var pieces = []; for (var i = 0, l = array.length; i < l; ++i) { pieces.push(ascii.call(this, array[i], processed)); } return "[" + pieces.join(", ") + "]"; }; ascii.object = function (object, processed, indent) { processed = processed || []; processed.push(object); indent = indent || 0; var pieces = [], properties = keys(object), prop, str, obj; var is = ""; var length = 3; for (var i = 0, l = indent; i < l; ++i) { is += " "; } for (i = 0, l = properties.length; i < l; ++i) { prop = properties[i]; obj = object[prop]; if (isCircular(obj, processed)) { str = "[Circular]"; } else { str = ascii.call(this, obj, processed, indent + 2); } str = (/\s/.test(prop) ? '"' + prop + '"' : prop) + ": " + str; length += str.length; pieces.push(str); } var cons = ascii.constructorName.call(this, object); var prefix = cons ? "[" + cons + "] " : "" return (length + indent) > 80 ? prefix + "{\n " + is + pieces.join(",\n " + is) + "\n" + is + "}" : prefix + "{ " + pieces.join(", ") + " }"; }; ascii.element = function (element) { var tagName = element.tagName.toLowerCase(); var attrs = element.attributes, attribute, pairs = [], attrName; for (var i = 0, l = attrs.length; i < l; ++i) { attribute = attrs.item(i); attrName = attribute.nodeName.toLowerCase().replace("html:", ""); if (attrName == "contenteditable" && attribute.nodeValue == "inherit") { continue; } if (!!attribute.nodeValue) { pairs.push(attrName + "=\"" + attribute.nodeValue + "\""); } } var formatted = "<" + tagName + (pairs.length > 0 ? " " : ""); var content = element.innerHTML; if (content.length > 20) { content = content.substr(0, 20) + "[...]"; } var res = formatted + pairs.join(" ") + ">" + content + "</" + tagName + ">"; return res.replace(/ contentEditable="inherit"/, ""); }; ascii.constructorName = function (object) { var name = buster.functionName(object && object.constructor); var excludes = this.excludeConstructors || buster.format.excludeConstructors || []; for (var i = 0, l = excludes.length; i < l; ++i) { if (typeof excludes[i] == "string" && excludes[i] == name) { return ""; } else if (excludes[i].test && excludes[i].test(name)) { return ""; } } return name; }; return ascii; }()); if (typeof module != "undefined") { module.exports = buster.format; } /*jslint eqeqeq: false, onevar: false, forin: true, nomen: false, regexp: false, plusplus: false*/ /*global module, require, __dirname, document*/ /** * Sinon core utilities. For internal use only. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ var sinon = (function (buster) { var div = typeof document != "undefined" && document.createElement("div"); var hasOwn = Object.prototype.hasOwnProperty; function isDOMNode(obj) { var success = false; try { obj.appendChild(div); success = div.parentNode == obj; } catch (e) { return false; } finally { try { obj.removeChild(div); } catch (e) { // Remove failed, not much we can do about that } } return success; } function isElement(obj) { return div && obj && obj.nodeType === 1 && isDOMNode(obj); } function isFunction(obj) { return !!(obj && obj.constructor && obj.call && obj.apply); } function mirrorProperties(target, source) { for (var prop in source) { if (!hasOwn.call(target, prop)) { target[prop] = source[prop]; } } } var sinon = { wrapMethod: function wrapMethod(object, property, method) { if (!object) { throw new TypeError("Should wrap property of object"); } if (typeof method != "function") { throw new TypeError("Method wrapper should be function"); } var wrappedMethod = object[property]; if (!isFunction(wrappedMethod)) { throw new TypeError("Attempted to wrap " + (typeof wrappedMethod) + " property " + property + " as function"); } if (wrappedMethod.restore && wrappedMethod.restore.sinon) { throw new TypeError("Attempted to wrap " + property + " which is already wrapped"); } if (wrappedMethod.calledBefore) { var verb = !!wrappedMethod.returns ? "stubbed" : "spied on"; throw new TypeError("Attempted to wrap " + property + " which is already " + verb); } // IE 8 does not support hasOwnProperty on the window object. var owned = hasOwn.call(object, property); object[property] = method; method.displayName = property; method.restore = function () { // For prototype properties try to reset by delete first. // If this fails (ex: localStorage on mobile safari) then force a reset // via direct assignment. if (!owned) { delete object[property]; } if (object[property] === method) { object[property] = wrappedMethod; } }; method.restore.sinon = true; mirrorProperties(method, wrappedMethod); return method; }, extend: function extend(target) { for (var i = 1, l = arguments.length; i < l; i += 1) { for (var prop in arguments[i]) { if (arguments[i].hasOwnProperty(prop)) { target[prop] = arguments[i][prop]; } // DONT ENUM bug, only care about toString if (arguments[i].hasOwnProperty("toString") && arguments[i].toString != target.toString) { target.toString = arguments[i].toString; } } } return target; }, create: function create(proto) { var F = function () {}; F.prototype = proto; return new F(); }, deepEqual: function deepEqual(a, b) { if (sinon.match && sinon.match.isMatcher(a)) { return a.test(b); } if (typeof a != "object" || typeof b != "object") { return a === b; } if (isElement(a) || isElement(b)) { return a === b; } if (a === b) { return true; } var aString = Object.prototype.toString.call(a); if (aString != Object.prototype.toString.call(b)) { return false; } if (aString == "[object Array]") { if (a.length !== b.length) { return false; } for (var i = 0, l = a.length; i < l; i += 1) { if (!deepEqual(a[i], b[i])) { return false; } } return true; } var prop, aLength = 0, bLength = 0; for (prop in a) { aLength += 1; if (!deepEqual(a[prop], b[prop])) { return false; } } for (prop in b) { bLength += 1; } if (aLength != bLength) { return false; } return true; }, functionName: function functionName(func) { var name = func.displayName || func.name; // Use function decomposition as a last resort to get function // name. Does not rely on function decomposition to work - if it // doesn't debugging will be slightly less informative // (i.e. toString will say 'spy' rather than 'myFunc'). if (!name) { var matches = func.toString().match(/function ([^\s\(]+)/); name = matches && matches[1]; } return name; }, functionToString: function toString() { if (this.getCall && this.callCount) { var thisValue, prop, i = this.callCount; while (i--) { thisValue = this.getCall(i).thisValue; for (prop in thisValue) { if (thisValue[prop] === this) { return prop; } } } } return this.displayName || "sinon fake"; }, getConfig: function (custom) { var config = {}; custom = custom || {}; var defaults = sinon.defaultConfig; for (var prop in defaults) { if (defaults.hasOwnProperty(prop)) { config[prop] = custom.hasOwnProperty(prop) ? custom[prop] : defaults[prop]; } } return config; }, format: function (val) { return "" + val; }, defaultConfig: { injectIntoThis: true, injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true }, timesInWords: function timesInWords(count) { return count == 1 && "once" || count == 2 && "twice" || count == 3 && "thrice" || (count || 0) + " times"; }, calledInOrder: function (spies) { for (var i = 1, l = spies.length; i < l; i++) { if (!spies[i - 1].calledBefore(spies[i])) { return false; } } return true; }, orderByFirstCall: function (spies) { return spies.sort(function (a, b) { // uuid, won't ever be equal var aCall = a.getCall(0); var bCall = b.getCall(0); var aId = aCall && aCall.callId || -1; var bId = bCall && bCall.callId || -1; return aId < bId ? -1 : 1; }); }, log: function () {}, logError: function (label, err) { var msg = label + " threw exception: " sinon.log(msg + "[" + err.name + "] " + err.message); if (err.stack) { sinon.log(err.stack); } setTimeout(function () { err.message = msg + err.message; throw err; }, 0); }, typeOf: function (value) { if (value === null) { return "null"; } var string = Object.prototype.toString.call(value); return string.substring(8, string.length - 1).toLowerCase(); } }; var isNode = typeof module == "object" && typeof require == "function"; if (isNode) { try { buster = { format: require("buster-format") }; } catch (e) {} module.exports = sinon; module.exports.spy = require("./sinon/spy"); module.exports.stub = require("./sinon/stub"); module.exports.mock = require("./sinon/mock"); module.exports.collection = require("./sinon/collection"); module.exports.assert = require("./sinon/assert"); module.exports.sandbox = require("./sinon/sandbox"); module.exports.test = require("./sinon/test"); module.exports.testCase = require("./sinon/test_case"); module.exports.assert = require("./sinon/assert"); module.exports.match = require("./sinon/match"); } if (buster) { var formatter = sinon.create(buster.format); formatter.quoteStrings = false; sinon.format = function () { return formatter.ascii.apply(formatter, arguments); }; } else if (isNode) { try { var util = require("util"); sinon.format = function (value) { return typeof value == "object" && value.toString === Object.prototype.toString ? util.inspect(value) : value; }; } catch (e) { /* Node, but no util module - would be very old, but better safe than sorry */ } } return sinon; }(typeof buster == "object" && buster)); /* @depend ../sinon.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Match functions * * @author Maximilian Antoni ([email protected]) * @license BSD * * Copyright (c) 2012 Maximilian Antoni */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function assertType(value, type, name) { var actual = sinon.typeOf(value); if (actual !== type) { throw new TypeError("Expected type of " + name + " to be " + type + ", but was " + actual); } } var matcher = { toString: function () { return this.message; } }; function isMatcher(object) { return matcher.isPrototypeOf(object); } function matchObject(expectation, actual) { if (actual === null || actual === undefined) { return false; } for (var key in expectation) { if (expectation.hasOwnProperty(key)) { var exp = expectation[key]; var act = actual[key]; if (match.isMatcher(exp)) { if (!exp.test(act)) { return false; } } else if (sinon.typeOf(exp) === "object") { if (!matchObject(exp, act)) { return false; } } else if (!sinon.deepEqual(exp, act)) { return false; } } } return true; } matcher.or = function (m2) { if (!isMatcher(m2)) { throw new TypeError("Matcher expected"); } var m1 = this; var or = sinon.create(matcher); or.test = function (actual) { return m1.test(actual) || m2.test(actual); }; or.message = m1.message + ".or(" + m2.message + ")"; return or; }; matcher.and = function (m2) { if (!isMatcher(m2)) { throw new TypeError("Matcher expected"); } var m1 = this; var and = sinon.create(matcher); and.test = function (actual) { return m1.test(actual) && m2.test(actual); }; and.message = m1.message + ".and(" + m2.message + ")"; return and; }; var match = function (expectation, message) { var m = sinon.create(matcher); var type = sinon.typeOf(expectation); switch (type) { case "object": if (typeof expectation.test === "function") { m.test = function (actual) { return expectation.test(actual) === true; }; m.message = "match(" + sinon.functionName(expectation.test) + ")"; return m; } var str = []; for (var key in expectation) { if (expectation.hasOwnProperty(key)) { str.push(key + ": " + expectation[key]); } } m.test = function (actual) { return matchObject(expectation, actual); }; m.message = "match(" + str.join(", ") + ")"; break; case "number": m.test = function (actual) { return expectation == actual; }; break; case "string": m.test = function (actual) { if (typeof actual !== "string") { return false; } return actual.indexOf(expectation) !== -1; }; m.message = "match(\"" + expectation + "\")"; break; case "regexp": m.test = function (actual) { if (typeof actual !== "string") { return false; } return expectation.test(actual); }; break; case "function": m.test = expectation; if (message) { m.message = message; } else { m.message = "match(" + sinon.functionName(expectation) + ")"; } break; default: m.test = function (actual) { return sinon.deepEqual(expectation, actual); }; } if (!m.message) { m.message = "match(" + expectation + ")"; } return m; }; match.isMatcher = isMatcher; match.any = match(function () { return true; }, "any"); match.defined = match(function (actual) { return actual !== null && actual !== undefined; }, "defined"); match.truthy = match(function (actual) { return !!actual; }, "truthy"); match.falsy = match(function (actual) { return !actual; }, "falsy"); match.same = function (expectation) { return match(function (actual) { return expectation === actual; }, "same(" + expectation + ")"); }; match.typeOf = function (type) { assertType(type, "string", "type"); return match(function (actual) { return sinon.typeOf(actual) === type; }, "typeOf(\"" + type + "\")"); }; match.instanceOf = function (type) { assertType(type, "function", "type"); return match(function (actual) { return actual instanceof type; }, "instanceOf(" + sinon.functionName(type) + ")"); }; function createPropertyMatcher(propertyTest, messagePrefix) { return function (property, value) { assertType(property, "string", "property"); var onlyProperty = arguments.length === 1; var message = messagePrefix + "(\"" + property + "\""; if (!onlyProperty) { message += ", " + value; } message += ")"; return match(function (actual) { if (actual === undefined || actual === null || !propertyTest(actual, property)) { return false; } return onlyProperty || sinon.deepEqual(value, actual[property]); }, message); }; } match.has = createPropertyMatcher(function (actual, property) { if (typeof actual === "object") { return property in actual; } return actual[property] !== undefined; }, "has"); match.hasOwn = createPropertyMatcher(function (actual, property) { return actual.hasOwnProperty(property); }, "hasOwn"); match.bool = match.typeOf("boolean"); match.number = match.typeOf("number"); match.string = match.typeOf("string"); match.object = match.typeOf("object"); match.func = match.typeOf("function"); match.array = match.typeOf("array"); match.regexp = match.typeOf("regexp"); match.date = match.typeOf("date"); if (commonJSModule) { module.exports = match; } else { sinon.match = match; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend match.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global module, require, sinon*/ /** * Spy functions * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var spyCall; var callId = 0; var push = [].push; var slice = Array.prototype.slice; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function spy(object, property) { if (!property && typeof object == "function") { return spy.create(object); } if (!object && !property) { return spy.create(function () {}); } var method = object[property]; return sinon.wrapMethod(object, property, spy.create(method)); } sinon.extend(spy, (function () { function delegateToCalls(api, method, matchAny, actual, notCalled) { api[method] = function () { if (!this.called) { if (notCalled) { return notCalled.apply(this, arguments); } return false; } var currentCall; var matches = 0; for (var i = 0, l = this.callCount; i < l; i += 1) { currentCall = this.getCall(i); if (currentCall[actual || method].apply(currentCall, arguments)) { matches += 1; if (matchAny) { return true; } } } return matches === this.callCount; }; } function matchingFake(fakes, args, strict) { if (!fakes) { return; } var alen = args.length; for (var i = 0, l = fakes.length; i < l; i++) { if (fakes[i].matches(args, strict)) { return fakes[i]; } } } function incrementCallCount() { this.called = true; this.callCount += 1; this.notCalled = false; this.calledOnce = this.callCount == 1; this.calledTwice = this.callCount == 2; this.calledThrice = this.callCount == 3; } function createCallProperties() { this.firstCall = this.getCall(0); this.secondCall = this.getCall(1); this.thirdCall = this.getCall(2); this.lastCall = this.getCall(this.callCount - 1); } var uuid = 0; // Public API var spyApi = { reset: function () { this.called = false; this.notCalled = true; this.calledOnce = false; this.calledTwice = false; this.calledThrice = false; this.callCount = 0; this.firstCall = null; this.secondCall = null; this.thirdCall = null; this.lastCall = null; this.args = []; this.returnValues = []; this.thisValues = []; this.exceptions = []; this.callIds = []; if (this.fakes) { for (var i = 0; i < this.fakes.length; i++) { this.fakes[i].reset(); } } }, create: function create(func) { var name; if (typeof func != "function") { func = function () {}; } else { name = sinon.functionName(func); } function proxy() { return proxy.invoke(func, this, slice.call(arguments)); } sinon.extend(proxy, spy); delete proxy.create; sinon.extend(proxy, func); proxy.reset(); proxy.prototype = func.prototype; proxy.displayName = name || "spy"; proxy.toString = sinon.functionToString; proxy._create = sinon.spy.create; proxy.id = "spy#" + uuid++; return proxy; }, invoke: function invoke(func, thisValue, args) { var matching = matchingFake(this.fakes, args); var exception, returnValue; incrementCallCount.call(this); push.call(this.thisValues, thisValue); push.call(this.args, args); push.call(this.callIds, callId++); try { if (matching) { returnValue = matching.invoke(func, thisValue, args); } else { returnValue = (this.func || func).apply(thisValue, args); } } catch (e) { push.call(this.returnValues, undefined); exception = e; throw e; } finally { push.call(this.exceptions, exception); } push.call(this.returnValues, returnValue); createCallProperties.call(this); return returnValue; }, getCall: function getCall(i) { if (i < 0 || i >= this.callCount) { return null; } return spyCall.create(this, this.thisValues[i], this.args[i], this.returnValues[i], this.exceptions[i], this.callIds[i]); }, calledBefore: function calledBefore(spyFn) { if (!this.called) { return false; } if (!spyFn.called) { return true; } return this.callIds[0] < spyFn.callIds[spyFn.callIds.length - 1]; }, calledAfter: function calledAfter(spyFn) { if (!this.called || !spyFn.called) { return false; } return this.callIds[this.callCount - 1] > spyFn.callIds[spyFn.callCount - 1]; }, withArgs: function () { var args = slice.call(arguments); if (this.fakes) { var match = matchingFake(this.fakes, args, true); if (match) { return match; } } else { this.fakes = []; } var original = this; var fake = this._create(); fake.matchingAguments = args; push.call(this.fakes, fake); fake.withArgs = function () { return original.withArgs.apply(original, arguments); }; for (var i = 0; i < this.args.length; i++) { if (fake.matches(this.args[i])) { incrementCallCount.call(fake); push.call(fake.thisValues, this.thisValues[i]); push.call(fake.args, this.args[i]); push.call(fake.returnValues, this.returnValues[i]); push.call(fake.exceptions, this.exceptions[i]); push.call(fake.callIds, this.callIds[i]); } } createCallProperties.call(fake); return fake; }, matches: function (args, strict) { var margs = this.matchingAguments; if (margs.length <= args.length && sinon.deepEqual(margs, args.slice(0, margs.length))) { return !strict || margs.length == args.length; } }, printf: function (format) { var spy = this; var args = slice.call(arguments, 1); var formatter; return (format || "").replace(/%(.)/g, function (match, specifyer) { formatter = spyApi.formatters[specifyer]; if (typeof formatter == "function") { return formatter.call(null, spy, args); } else if (!isNaN(parseInt(specifyer), 10)) { return sinon.format(args[specifyer - 1]); } return "%" + specifyer; }); } }; delegateToCalls(spyApi, "calledOn", true); delegateToCalls(spyApi, "alwaysCalledOn", false, "calledOn"); delegateToCalls(spyApi, "calledWith", true); delegateToCalls(spyApi, "calledWithMatch", true); delegateToCalls(spyApi, "alwaysCalledWith", false, "calledWith"); delegateToCalls(spyApi, "alwaysCalledWithMatch", false, "calledWithMatch"); delegateToCalls(spyApi, "calledWithExactly", true); delegateToCalls(spyApi, "alwaysCalledWithExactly", false, "calledWithExactly"); delegateToCalls(spyApi, "neverCalledWith", false, "notCalledWith", function () { return true; }); delegateToCalls(spyApi, "neverCalledWithMatch", false, "notCalledWithMatch", function () { return true; }); delegateToCalls(spyApi, "threw", true); delegateToCalls(spyApi, "alwaysThrew", false, "threw"); delegateToCalls(spyApi, "returned", true); delegateToCalls(spyApi, "alwaysReturned", false, "returned"); delegateToCalls(spyApi, "calledWithNew", true); delegateToCalls(spyApi, "alwaysCalledWithNew", false, "calledWithNew"); delegateToCalls(spyApi, "callArg", false, "callArgWith", function () { throw new Error(this.toString() + " cannot call arg since it was not yet invoked."); }); spyApi.callArgWith = spyApi.callArg; delegateToCalls(spyApi, "yield", false, "yield", function () { throw new Error(this.toString() + " cannot yield since it was not yet invoked."); }); // "invokeCallback" is an alias for "yield" since "yield" is invalid in strict mode. spyApi.invokeCallback = spyApi.yield; delegateToCalls(spyApi, "yieldTo", false, "yieldTo", function (property) { throw new Error(this.toString() + " cannot yield to '" + property + "' since it was not yet invoked."); }); spyApi.formatters = { "c": function (spy) { return sinon.timesInWords(spy.callCount); }, "n": function (spy) { return spy.toString(); }, "C": function (spy) { var calls = []; for (var i = 0, l = spy.callCount; i < l; ++i) { push.call(calls, " " + spy.getCall(i).toString()); } return calls.length > 0 ? "\n" + calls.join("\n") : ""; }, "t": function (spy) { var objects = []; for (var i = 0, l = spy.callCount; i < l; ++i) { push.call(objects, sinon.format(spy.thisValues[i])); } return objects.join(", "); }, "*": function (spy, args) { var formatted = []; for (var i = 0, l = args.length; i < l; ++i) { push.call(formatted, sinon.format(args[i])); } return formatted.join(", "); } }; return spyApi; }())); spyCall = (function () { function throwYieldError(proxy, text, args) { var msg = sinon.functionName(proxy) + text; if (args.length) { msg += " Received [" + slice.call(args).join(", ") + "]"; } throw new Error(msg); } return { create: function create(spy, thisValue, args, returnValue, exception, id) { var proxyCall = sinon.create(spyCall); delete proxyCall.create; proxyCall.proxy = spy; proxyCall.thisValue = thisValue; proxyCall.args = args; proxyCall.returnValue = returnValue; proxyCall.exception = exception; proxyCall.callId = typeof id == "number" && id || callId++; return proxyCall; }, calledOn: function calledOn(thisValue) { return this.thisValue === thisValue; }, calledWith: function calledWith() { for (var i = 0, l = arguments.length; i < l; i += 1) { if (!sinon.deepEqual(arguments[i], this.args[i])) { return false; } } return true; }, calledWithMatch: function calledWithMatch() { for (var i = 0, l = arguments.length; i < l; i += 1) { var actual = this.args[i]; var expectation = arguments[i]; if (!sinon.match || !sinon.match(expectation).test(actual)) { return false; } } return true; }, calledWithExactly: function calledWithExactly() { return arguments.length == this.args.length && this.calledWith.apply(this, arguments); }, notCalledWith: function notCalledWith() { return !this.calledWith.apply(this, arguments); }, notCalledWithMatch: function notCalledWithMatch() { return !this.calledWithMatch.apply(this, arguments); }, returned: function returned(value) { return sinon.deepEqual(value, this.returnValue); }, threw: function threw(error) { if (typeof error == "undefined" || !this.exception) { return !!this.exception; } if (typeof error == "string") { return this.exception.name == error; } return this.exception === error; }, calledWithNew: function calledWithNew(thisValue) { return this.thisValue instanceof this.proxy; }, calledBefore: function (other) { return this.callId < other.callId; }, calledAfter: function (other) { return this.callId > other.callId; }, callArg: function (pos) { this.args[pos](); }, callArgWith: function (pos) { var args = slice.call(arguments, 1); this.args[pos].apply(null, args); }, "yield": function () { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (typeof args[i] === "function") { args[i].apply(null, slice.call(arguments)); return; } } throwYieldError(this.proxy, " cannot yield since no callback was passed.", args); }, yieldTo: function (prop) { var args = this.args; for (var i = 0, l = args.length; i < l; ++i) { if (args[i] && typeof args[i][prop] === "function") { args[i][prop].apply(null, slice.call(arguments, 1)); return; } } throwYieldError(this.proxy, " cannot yield to '" + prop + "' since no callback was passed.", args); }, toString: function () { var callStr = this.proxy.toString() + "("; var args = []; for (var i = 0, l = this.args.length; i < l; ++i) { push.call(args, sinon.format(this.args[i])); } callStr = callStr + args.join(", ") + ")"; if (typeof this.returnValue != "undefined") { callStr += " => " + sinon.format(this.returnValue); } if (this.exception) { callStr += " !" + this.exception.name; if (this.exception.message) { callStr += "(" + this.exception.message + ")"; } } return callStr; } }; }()); spy.spyCall = spyCall; // This steps outside the module sandbox and will be removed sinon.spyCall = spyCall; if (commonJSModule) { module.exports = spy; } else { sinon.spy = spy; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend spy.js */ /*jslint eqeqeq: false, onevar: false*/ /*global module, require, sinon*/ /** * Stub functions * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function stub(object, property, func) { if (!!func && typeof func != "function") { throw new TypeError("Custom stub should be function"); } var wrapper; if (func) { wrapper = sinon.spy && sinon.spy.create ? sinon.spy.create(func) : func; } else { wrapper = stub.create(); } if (!object && !property) { return sinon.stub.create(); } if (!property && !!object && typeof object == "object") { for (var prop in object) { if (typeof object[prop] === "function") { stub(object, prop); } } return object; } return sinon.wrapMethod(object, property, wrapper); } function getCallback(stub, args) { if (stub.callArgAt < 0) { for (var i = 0, l = args.length; i < l; ++i) { if (!stub.callArgProp && typeof args[i] == "function") { return args[i]; } if (stub.callArgProp && args[i] && typeof args[i][stub.callArgProp] == "function") { return args[i][stub.callArgProp]; } } return null; } return args[stub.callArgAt]; } var join = Array.prototype.join; function getCallbackError(stub, func, args) { if (stub.callArgAt < 0) { var msg; if (stub.callArgProp) { msg = sinon.functionName(stub) + " expected to yield to '" + stub.callArgProp + "', but no object with such a property was passed." } else { msg = sinon.functionName(stub) + " expected to yield, but no callback was passed." } if (args.length > 0) { msg += " Received [" + join.call(args, ", ") + "]"; } return msg; } return "argument at index " + stub.callArgAt + " is not a function: " + func; } var nextTick = (function () { if (typeof process === "object" && typeof process.nextTick === "function") { return process.nextTick; } else if (typeof msSetImmediate === "function") { return msSetImmediate.bind(window); } else if (typeof setImmediate === "function") { return setImmediate; } else { return function (callback) { setTimeout(callback, 0); }; } })(); function callCallback(stub, args) { if (typeof stub.callArgAt == "number") { var func = getCallback(stub, args); if (typeof func != "function") { throw new TypeError(getCallbackError(stub, func, args)); } if (stub.callbackAsync) { nextTick(function() { func.apply(stub.callbackContext, stub.callbackArguments); }); } else { func.apply(stub.callbackContext, stub.callbackArguments); } } } var uuid = 0; sinon.extend(stub, (function () { var slice = Array.prototype.slice, proto; function throwsException(error, message) { if (typeof error == "string") { this.exception = new Error(message || ""); this.exception.name = error; } else if (!error) { this.exception = new Error("Error"); } else { this.exception = error; } return this; } proto = { create: function create() { var functionStub = function () { callCallback(functionStub, arguments); if (functionStub.exception) { throw functionStub.exception; } else if (typeof functionStub.returnArgAt == 'number') { return arguments[functionStub.returnArgAt]; } else if (functionStub.returnThis) { return this; } return functionStub.returnValue; }; functionStub.id = "stub#" + uuid++; var orig = functionStub; functionStub = sinon.spy.create(functionStub); functionStub.func = orig; sinon.extend(functionStub, stub); functionStub._create = sinon.stub.create; functionStub.displayName = "stub"; functionStub.toString = sinon.functionToString; return functionStub; }, returns: function returns(value) { this.returnValue = value; return this; }, returnsArg: function returnsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.returnArgAt = pos; return this; }, returnsThis: function returnsThis() { this.returnThis = true; return this; }, "throws": throwsException, throwsException: throwsException, callsArg: function callsArg(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAt = pos; this.callbackArguments = []; return this; }, callsArgOn: function callsArgOn(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAt = pos; this.callbackArguments = []; this.callbackContext = context; return this; }, callsArgWith: function callsArgWith(pos) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } this.callArgAt = pos; this.callbackArguments = slice.call(arguments, 1); return this; }, callsArgOnWith: function callsArgWith(pos, context) { if (typeof pos != "number") { throw new TypeError("argument index is not number"); } if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAt = pos; this.callbackArguments = slice.call(arguments, 2); this.callbackContext = context; return this; }, yields: function () { this.callArgAt = -1; this.callbackArguments = slice.call(arguments, 0); return this; }, yieldsOn: function (context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAt = -1; this.callbackArguments = slice.call(arguments, 1); this.callbackContext = context; return this; }, yieldsTo: function (prop) { this.callArgAt = -1; this.callArgProp = prop; this.callbackArguments = slice.call(arguments, 1); return this; }, yieldsToOn: function (prop, context) { if (typeof context != "object") { throw new TypeError("argument context is not an object"); } this.callArgAt = -1; this.callArgProp = prop; this.callbackArguments = slice.call(arguments, 2); this.callbackContext = context; return this; } }; // create asynchronous versions of callsArg* and yields* methods for (var method in proto) { if (proto.hasOwnProperty(method) && method.match(/^(callsArg|yields)/)) { proto[method + 'Async'] = (function (syncFnName) { return function () { this.callbackAsync = true; return this[syncFnName].apply(this, arguments); }; })(method); } } return proto; }())); if (commonJSModule) { module.exports = stub; } else { sinon.stub = stub; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false*/ /*global module, require, sinon*/ /** * Mock functions. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = [].push; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function mock(object) { if (!object) { return sinon.expectation.create("Anonymous mock"); } return mock.create(object); } sinon.mock = mock; sinon.extend(mock, (function () { function each(collection, callback) { if (!collection) { return; } for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } return { create: function create(object) { if (!object) { throw new TypeError("object is null"); } var mockObject = sinon.extend({}, mock); mockObject.object = object; delete mockObject.create; return mockObject; }, expects: function expects(method) { if (!method) { throw new TypeError("method is falsy"); } if (!this.expectations) { this.expectations = {}; this.proxies = []; } if (!this.expectations[method]) { this.expectations[method] = []; var mockObject = this; sinon.wrapMethod(this.object, method, function () { return mockObject.invokeMethod(method, this, arguments); }); push.call(this.proxies, method); } var expectation = sinon.expectation.create(method); push.call(this.expectations[method], expectation); return expectation; }, restore: function restore() { var object = this.object; each(this.proxies, function (proxy) { if (typeof object[proxy].restore == "function") { object[proxy].restore(); } }); }, verify: function verify() { var expectations = this.expectations || {}; var messages = [], met = []; each(this.proxies, function (proxy) { each(expectations[proxy], function (expectation) { if (!expectation.met()) { push.call(messages, expectation.toString()); } else { push.call(met, expectation.toString()); } }); }); this.restore(); if (messages.length > 0) { sinon.expectation.fail(messages.concat(met).join("\n")); } else { sinon.expectation.pass(messages.concat(met).join("\n")); } return true; }, invokeMethod: function invokeMethod(method, thisValue, args) { var expectations = this.expectations && this.expectations[method]; var length = expectations && expectations.length || 0, i; for (i = 0; i < length; i += 1) { if (!expectations[i].met() && expectations[i].allowsCall(thisValue, args)) { return expectations[i].apply(thisValue, args); } } var messages = [], available, exhausted = 0; for (i = 0; i < length; i += 1) { if (expectations[i].allowsCall(thisValue, args)) { available = available || expectations[i]; } else { exhausted += 1; } push.call(messages, " " + expectations[i].toString()); } if (exhausted === 0) { return available.apply(thisValue, args); } messages.unshift("Unexpected call: " + sinon.spyCall.toString.call({ proxy: method, args: args })); sinon.expectation.fail(messages.join("\n")); } }; }())); var times = sinon.timesInWords; sinon.expectation = (function () { var slice = Array.prototype.slice; var _invoke = sinon.spy.invoke; function callCountInWords(callCount) { if (callCount == 0) { return "never called"; } else { return "called " + times(callCount); } } function expectedCallCountInWords(expectation) { var min = expectation.minCalls; var max = expectation.maxCalls; if (typeof min == "number" && typeof max == "number") { var str = times(min); if (min != max) { str = "at least " + str + " and at most " + times(max); } return str; } if (typeof min == "number") { return "at least " + times(min); } return "at most " + times(max); } function receivedMinCalls(expectation) { var hasMinLimit = typeof expectation.minCalls == "number"; return !hasMinLimit || expectation.callCount >= expectation.minCalls; } function receivedMaxCalls(expectation) { if (typeof expectation.maxCalls != "number") { return false; } return expectation.callCount == expectation.maxCalls; } return { minCalls: 1, maxCalls: 1, create: function create(methodName) { var expectation = sinon.extend(sinon.stub.create(), sinon.expectation); delete expectation.create; expectation.method = methodName; return expectation; }, invoke: function invoke(func, thisValue, args) { this.verifyCallAllowed(thisValue, args); return _invoke.apply(this, arguments); }, atLeast: function atLeast(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.maxCalls = null; this.limitsSet = true; } this.minCalls = num; return this; }, atMost: function atMost(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not number"); } if (!this.limitsSet) { this.minCalls = null; this.limitsSet = true; } this.maxCalls = num; return this; }, never: function never() { return this.exactly(0); }, once: function once() { return this.exactly(1); }, twice: function twice() { return this.exactly(2); }, thrice: function thrice() { return this.exactly(3); }, exactly: function exactly(num) { if (typeof num != "number") { throw new TypeError("'" + num + "' is not a number"); } this.atLeast(num); return this.atMost(num); }, met: function met() { return !this.failed && receivedMinCalls(this); }, verifyCallAllowed: function verifyCallAllowed(thisValue, args) { if (receivedMaxCalls(this)) { this.failed = true; sinon.expectation.fail(this.method + " already called " + times(this.maxCalls)); } if ("expectedThis" in this && this.expectedThis !== thisValue) { sinon.expectation.fail(this.method + " called with " + thisValue + " as thisValue, expected " + this.expectedThis); } if (!("expectedArguments" in this)) { return; } if (!args) { sinon.expectation.fail(this.method + " received no arguments, expected " + this.expectedArguments.join()); } if (args.length < this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too few arguments (" + args.join() + "), expected " + this.expectedArguments.join()); } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { sinon.expectation.fail(this.method + " received too many arguments (" + args.join() + "), expected " + this.expectedArguments.join()); } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { sinon.expectation.fail(this.method + " received wrong arguments (" + args.join() + "), expected " + this.expectedArguments.join()); } } }, allowsCall: function allowsCall(thisValue, args) { if (this.met() && receivedMaxCalls(this)) { return false; } if ("expectedThis" in this && this.expectedThis !== thisValue) { return false; } if (!("expectedArguments" in this)) { return true; } args = args || []; if (args.length < this.expectedArguments.length) { return false; } if (this.expectsExactArgCount && args.length != this.expectedArguments.length) { return false; } for (var i = 0, l = this.expectedArguments.length; i < l; i += 1) { if (!sinon.deepEqual(this.expectedArguments[i], args[i])) { return false; } } return true; }, withArgs: function withArgs() { this.expectedArguments = slice.call(arguments); return this; }, withExactArgs: function withExactArgs() { this.withArgs.apply(this, arguments); this.expectsExactArgCount = true; return this; }, on: function on(thisValue) { this.expectedThis = thisValue; return this; }, toString: function () { var args = (this.expectedArguments || []).slice(); if (!this.expectsExactArgCount) { push.call(args, "[...]"); } var callStr = sinon.spyCall.toString.call({ proxy: this.method, args: args }); var message = callStr.replace(", [...", "[, ...") + " " + expectedCallCountInWords(this); if (this.met()) { return "Expectation met: " + message; } return "Expected " + message + " (" + callCountInWords(this.callCount) + ")"; }, verify: function verify() { if (!this.met()) { sinon.expectation.fail(this.toString()); } else { sinon.expectation.pass(this.toString()); } return true; }, pass: function(message) { sinon.assert.pass(message); }, fail: function (message) { var exception = new Error(message); exception.name = "ExpectationError"; throw exception; } }; }()); if (commonJSModule) { module.exports = mock; } else { sinon.mock = mock; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js * @depend mock.js */ /*jslint eqeqeq: false, onevar: false, forin: true*/ /*global module, require, sinon*/ /** * Collections of stubs, spies and mocks. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; var push = [].push; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function getFakes(fakeCollection) { if (!fakeCollection.fakes) { fakeCollection.fakes = []; } return fakeCollection.fakes; } function each(fakeCollection, method) { var fakes = getFakes(fakeCollection); for (var i = 0, l = fakes.length; i < l; i += 1) { if (typeof fakes[i][method] == "function") { fakes[i][method](); } } } function compact(fakeCollection) { var fakes = getFakes(fakeCollection); var i = 0; while (i < fakes.length) { fakes.splice(i, 1); } } var collection = { verify: function resolve() { each(this, "verify"); }, restore: function restore() { each(this, "restore"); compact(this); }, verifyAndRestore: function verifyAndRestore() { var exception; try { this.verify(); } catch (e) { exception = e; } this.restore(); if (exception) { throw exception; } }, add: function add(fake) { push.call(getFakes(this), fake); return fake; }, spy: function spy() { return this.add(sinon.spy.apply(sinon, arguments)); }, stub: function stub(object, property, value) { if (property) { var original = object[property]; if (typeof original != "function") { if (!object.hasOwnProperty(property)) { throw new TypeError("Cannot stub non-existent own property " + property); } object[property] = value; return this.add({ restore: function () { object[property] = original; } }); } } if (!property && !!object && typeof object == "object") { var stubbedObj = sinon.stub.apply(sinon, arguments); for (var prop in stubbedObj) { if (typeof stubbedObj[prop] === "function") { this.add(stubbedObj[prop]); } } return stubbedObj; } return this.add(sinon.stub.apply(sinon, arguments)); }, mock: function mock() { return this.add(sinon.mock.apply(sinon, arguments)); }, inject: function inject(obj) { var col = this; obj.spy = function () { return col.spy.apply(col, arguments); }; obj.stub = function () { return col.stub.apply(col, arguments); }; obj.mock = function () { return col.mock.apply(col, arguments); }; return obj; } }; if (commonJSModule) { module.exports = collection; } else { sinon.collection = collection; } }(typeof sinon == "object" && sinon || null)); /*jslint eqeqeq: false, plusplus: false, evil: true, onevar: false, browser: true, forin: false*/ /*global module, require, window*/ /** * Fake timer API * setTimeout * setInterval * clearTimeout * clearInterval * tick * reset * Date * * Inspired by jsUnitMockTimeOut from JsUnit * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ if (typeof sinon == "undefined") { var sinon = {}; } (function (global) { var id = 1; function addTimer(args, recurring) { if (args.length === 0) { throw new Error("Function requires at least 1 parameter"); } var toId = id++; var delay = args[1] || 0; if (!this.timeouts) { this.timeouts = {}; } this.timeouts[toId] = { id: toId, func: args[0], callAt: this.now + delay, invokeArgs: Array.prototype.slice.call(args, 2) }; if (recurring === true) { this.timeouts[toId].interval = delay; } return toId; } function parseTime(str) { if (!str) { return 0; } var strings = str.split(":"); var l = strings.length, i = l; var ms = 0, parsed; if (l > 3 || !/^(\d\d:){0,2}\d\d?$/.test(str)) { throw new Error("tick only understands numbers and 'h:m:s'"); } while (i--) { parsed = parseInt(strings[i], 10); if (parsed >= 60) { throw new Error("Invalid time " + str); } ms += parsed * Math.pow(60, (l - i - 1)); } return ms * 1000; } function createObject(object) { var newObject; if (Object.create) { newObject = Object.create(object); } else { var F = function () {}; F.prototype = object; newObject = new F(); } newObject.Date.clock = newObject; return newObject; } sinon.clock = { now: 0, create: function create(now) { var clock = createObject(this); if (typeof now == "number") { clock.now = now; } if (!!now && typeof now == "object") { throw new TypeError("now should be milliseconds since UNIX epoch"); } return clock; }, setTimeout: function setTimeout(callback, timeout) { return addTimer.call(this, arguments, false); }, clearTimeout: function clearTimeout(timerId) { if (!this.timeouts) { this.timeouts = []; } if (timerId in this.timeouts) { delete this.timeouts[timerId]; } }, setInterval: function setInterval(callback, timeout) { return addTimer.call(this, arguments, true); }, clearInterval: function clearInterval(timerId) { this.clearTimeout(timerId); }, tick: function tick(ms) { ms = typeof ms == "number" ? ms : parseTime(ms); var tickFrom = this.now, tickTo = this.now + ms, previous = this.now; var timer = this.firstTimerInRange(tickFrom, tickTo); var firstException; while (timer && tickFrom <= tickTo) { if (this.timeouts[timer.id]) { tickFrom = this.now = timer.callAt; try { this.callTimer(timer); } catch (e) { firstException = firstException || e; } } timer = this.firstTimerInRange(previous, tickTo); previous = tickFrom; } this.now = tickTo; if (firstException) { throw firstException; } }, firstTimerInRange: function (from, to) { var timer, smallest, originalTimer; for (var id in this.timeouts) { if (this.timeouts.hasOwnProperty(id)) { if (this.timeouts[id].callAt < from || this.timeouts[id].callAt > to) { continue; } if (!smallest || this.timeouts[id].callAt < smallest) { originalTimer = this.timeouts[id]; smallest = this.timeouts[id].callAt; timer = { func: this.timeouts[id].func, callAt: this.timeouts[id].callAt, interval: this.timeouts[id].interval, id: this.timeouts[id].id, invokeArgs: this.timeouts[id].invokeArgs }; } } } return timer || null; }, callTimer: function (timer) { if (typeof timer.interval == "number") { this.timeouts[timer.id].callAt += timer.interval; } else { delete this.timeouts[timer.id]; } try { if (typeof timer.func == "function") { timer.func.apply(null, timer.invokeArgs); } else { eval(timer.func); } } catch (e) { var exception = e; } if (!this.timeouts[timer.id]) { if (exception) { throw exception; } return; } if (exception) { throw exception; } }, reset: function reset() { this.timeouts = {}; }, Date: (function () { var NativeDate = Date; function ClockDate(year, month, date, hour, minute, second, ms) { // Defensive and verbose to avoid potential harm in passing // explicit undefined when user does not pass argument switch (arguments.length) { case 0: return new NativeDate(ClockDate.clock.now); case 1: return new NativeDate(year); case 2: return new NativeDate(year, month); case 3: return new NativeDate(year, month, date); case 4: return new NativeDate(year, month, date, hour); case 5: return new NativeDate(year, month, date, hour, minute); case 6: return new NativeDate(year, month, date, hour, minute, second); default: return new NativeDate(year, month, date, hour, minute, second, ms); } } return mirrorDateProperties(ClockDate, NativeDate); }()) }; function mirrorDateProperties(target, source) { if (source.now) { target.now = function now() { return target.clock.now; }; } else { delete target.now; } if (source.toSource) { target.toSource = function toSource() { return source.toSource(); }; } else { delete target.toSource; } target.toString = function toString() { return source.toString(); }; target.prototype = source.prototype; target.parse = source.parse; target.UTC = source.UTC; target.prototype.toUTCString = source.prototype.toUTCString; return target; } var methods = ["Date", "setTimeout", "setInterval", "clearTimeout", "clearInterval"]; function restore() { var method; for (var i = 0, l = this.methods.length; i < l; i++) { method = this.methods[i]; if (global[method].hadOwnProperty) { global[method] = this["_" + method]; } else { delete global[method]; } } // Prevent multiple executions which will completely remove these props this.methods = []; } function stubGlobal(method, clock) { clock[method].hadOwnProperty = Object.prototype.hasOwnProperty.call(global, method); clock["_" + method] = global[method]; if (method == "Date") { var date = mirrorDateProperties(clock[method], global[method]); global[method] = date; } else { global[method] = function () { return clock[method].apply(clock, arguments); }; for (var prop in clock[method]) { if (clock[method].hasOwnProperty(prop)) { global[method][prop] = clock[method][prop]; } } } global[method].clock = clock; } sinon.useFakeTimers = function useFakeTimers(now) { var clock = sinon.clock.create(now); clock.restore = restore; clock.methods = Array.prototype.slice.call(arguments, typeof now == "number" ? 1 : 0); if (clock.methods.length === 0) { clock.methods = methods; } for (var i = 0, l = clock.methods.length; i < l; i++) { stubGlobal(clock.methods[i], clock); } return clock; }; }(typeof global != "undefined" && typeof global !== "function" ? global : this)); sinon.timers = { setTimeout: setTimeout, clearTimeout: clearTimeout, setInterval: setInterval, clearInterval: clearInterval, Date: Date }; if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Minimal Event interface implementation * * Original implementation by Sven Fuchs: https://gist.github.com/995028 * Modifications and tests by Christian Johansen. * * @author Sven Fuchs ([email protected]) * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2011 Sven Fuchs, Christian Johansen */ if (typeof sinon == "undefined") { this.sinon = {}; } (function () { var push = [].push; sinon.Event = function Event(type, bubbles, cancelable) { this.initEvent(type, bubbles, cancelable); }; sinon.Event.prototype = { initEvent: function(type, bubbles, cancelable) { this.type = type; this.bubbles = bubbles; this.cancelable = cancelable; }, stopPropagation: function () {}, preventDefault: function () { this.defaultPrevented = true; } }; sinon.EventTarget = { addEventListener: function addEventListener(event, listener, useCapture) { this.eventListeners = this.eventListeners || {}; this.eventListeners[event] = this.eventListeners[event] || []; push.call(this.eventListeners[event], listener); }, removeEventListener: function removeEventListener(event, listener, useCapture) { var listeners = this.eventListeners && this.eventListeners[event] || []; for (var i = 0, l = listeners.length; i < l; ++i) { if (listeners[i] == listener) { return listeners.splice(i, 1); } } }, dispatchEvent: function dispatchEvent(event) { var type = event.type; var listeners = this.eventListeners && this.eventListeners[type] || []; for (var i = 0; i < listeners.length; i++) { if (typeof listeners[i] == "function") { listeners[i].call(this, event); } else { listeners[i].handleEvent(event); } } return !!event.defaultPrevented; } }; }()); /** * @depend event.js */ /*jslint eqeqeq: false, onevar: false*/ /*global sinon, module, require, ActiveXObject, XMLHttpRequest, DOMParser*/ /** * Fake XMLHttpRequest object * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ if (typeof sinon == "undefined") { this.sinon = {}; } sinon.xhr = { XMLHttpRequest: this.XMLHttpRequest }; // wrapper for global (function(global) { var xhr = sinon.xhr; xhr.GlobalXMLHttpRequest = global.XMLHttpRequest; xhr.GlobalActiveXObject = global.ActiveXObject; xhr.supportsActiveX = typeof xhr.GlobalActiveXObject != "undefined"; xhr.supportsXHR = typeof xhr.GlobalXMLHttpRequest != "undefined"; xhr.workingXHR = xhr.supportsXHR ? xhr.GlobalXMLHttpRequest : xhr.supportsActiveX ? function() { return new xhr.GlobalActiveXObject("MSXML2.XMLHTTP.3.0") } : false; /*jsl:ignore*/ var unsafeHeaders = { "Accept-Charset": true, "Accept-Encoding": true, "Connection": true, "Content-Length": true, "Cookie": true, "Cookie2": true, "Content-Transfer-Encoding": true, "Date": true, "Expect": true, "Host": true, "Keep-Alive": true, "Referer": true, "TE": true, "Trailer": true, "Transfer-Encoding": true, "Upgrade": true, "User-Agent": true, "Via": true }; /*jsl:end*/ function FakeXMLHttpRequest() { this.readyState = FakeXMLHttpRequest.UNSENT; this.requestHeaders = {}; this.requestBody = null; this.status = 0; this.statusText = ""; if (typeof FakeXMLHttpRequest.onCreate == "function") { FakeXMLHttpRequest.onCreate(this); } } function verifyState(xhr) { if (xhr.readyState !== FakeXMLHttpRequest.OPENED) { throw new Error("INVALID_STATE_ERR"); } if (xhr.sendFlag) { throw new Error("INVALID_STATE_ERR"); } } // filtering to enable a white-list version of Sinon FakeXhr, // where whitelisted requests are passed through to real XHR function each(collection, callback) { if (!collection) return; for (var i = 0, l = collection.length; i < l; i += 1) { callback(collection[i]); } } function some(collection, callback) { for (var index = 0; index < collection.length; index++) { if(callback(collection[index]) === true) return true; }; return false; } // largest arity in XHR is 5 - XHR#open var apply = function(obj,method,args) { switch(args.length) { case 0: return obj[method](); case 1: return obj[method](args[0]); case 2: return obj[method](args[0],args[1]); case 3: return obj[method](args[0],args[1],args[2]); case 4: return obj[method](args[0],args[1],args[2],args[3]); case 5: return obj[method](args[0],args[1],args[2],args[3],args[4]); }; }; FakeXMLHttpRequest.filters = []; FakeXMLHttpRequest.addFilter = function(fn) { this.filters.push(fn) }; var IE6Re = /MSIE 6/; FakeXMLHttpRequest.defake = function(fakeXhr,xhrArgs) { var xhr = new sinon.xhr.workingXHR(); each(["open","setRequestHeader","send","abort","getResponseHeader", "getAllResponseHeaders","addEventListener","overrideMimeType","removeEventListener"], function(method) { fakeXhr[method] = function() { return apply(xhr,method,arguments); }; }); var copyAttrs = function(args) { each(args, function(attr) { try { fakeXhr[attr] = xhr[attr] } catch(e) { if(!IE6Re.test(navigator.userAgent)) throw e; } }); }; var stateChange = function() { fakeXhr.readyState = xhr.readyState; if(xhr.readyState >= FakeXMLHttpRequest.HEADERS_RECEIVED) { copyAttrs(["status","statusText"]); } if(xhr.readyState >= FakeXMLHttpRequest.LOADING) { copyAttrs(["responseText"]); } if(xhr.readyState === FakeXMLHttpRequest.DONE) { copyAttrs(["responseXML"]); } if(fakeXhr.onreadystatechange) fakeXhr.onreadystatechange.call(fakeXhr); }; if(xhr.addEventListener) { for(var event in fakeXhr.eventListeners) { if(fakeXhr.eventListeners.hasOwnProperty(event)) { each(fakeXhr.eventListeners[event],function(handler) { xhr.addEventListener(event, handler); }); } } xhr.addEventListener("readystatechange",stateChange); } else { xhr.onreadystatechange = stateChange; } apply(xhr,"open",xhrArgs); }; FakeXMLHttpRequest.useFilters = false; function verifyRequestSent(xhr) { if (xhr.readyState == FakeXMLHttpRequest.DONE) { throw new Error("Request done"); } } function verifyHeadersReceived(xhr) { if (xhr.async && xhr.readyState != FakeXMLHttpRequest.HEADERS_RECEIVED) { throw new Error("No headers received"); } } function verifyResponseBodyType(body) { if (typeof body != "string") { var error = new Error("Attempted to respond to fake XMLHttpRequest with " + body + ", which is not a string."); error.name = "InvalidBodyException"; throw error; } } sinon.extend(FakeXMLHttpRequest.prototype, sinon.EventTarget, { async: true, open: function open(method, url, async, username, password) { this.method = method; this.url = url; this.async = typeof async == "boolean" ? async : true; this.username = username; this.password = password; this.responseText = null; this.responseXML = null; this.requestHeaders = {}; this.sendFlag = false; if(sinon.FakeXMLHttpRequest.useFilters === true) { var xhrArgs = arguments; var defake = some(FakeXMLHttpRequest.filters,function(filter) { return filter.apply(this,xhrArgs) }); if (defake) { return sinon.FakeXMLHttpRequest.defake(this,arguments); } } this.readyStateChange(FakeXMLHttpRequest.OPENED); }, readyStateChange: function readyStateChange(state) { this.readyState = state; if (typeof this.onreadystatechange == "function") { try { this.onreadystatechange(); } catch (e) { sinon.logError("Fake XHR onreadystatechange handler", e); } } this.dispatchEvent(new sinon.Event("readystatechange")); }, setRequestHeader: function setRequestHeader(header, value) { verifyState(this); if (unsafeHeaders[header] || /^(Sec-|Proxy-)/.test(header)) { throw new Error("Refused to set unsafe header \"" + header + "\""); } if (this.requestHeaders[header]) { this.requestHeaders[header] += "," + value; } else { this.requestHeaders[header] = value; } }, // Helps testing setResponseHeaders: function setResponseHeaders(headers) { this.responseHeaders = {}; for (var header in headers) { if (headers.hasOwnProperty(header)) { this.responseHeaders[header] = headers[header]; } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.HEADERS_RECEIVED); } }, // Currently treats ALL data as a DOMString (i.e. no Document) send: function send(data) { verifyState(this); if (!/^(get|head)$/i.test(this.method)) { if (this.requestHeaders["Content-Type"]) { var value = this.requestHeaders["Content-Type"].split(";"); this.requestHeaders["Content-Type"] = value[0] + ";charset=utf-8"; } else { this.requestHeaders["Content-Type"] = "text/plain;charset=utf-8"; } this.requestBody = data; } this.errorFlag = false; this.sendFlag = this.async; this.readyStateChange(FakeXMLHttpRequest.OPENED); if (typeof this.onSend == "function") { this.onSend(this); } }, abort: function abort() { this.aborted = true; this.responseText = null; this.errorFlag = true; this.requestHeaders = {}; if (this.readyState > sinon.FakeXMLHttpRequest.UNSENT && this.sendFlag) { this.readyStateChange(sinon.FakeXMLHttpRequest.DONE); this.sendFlag = false; } this.readyState = sinon.FakeXMLHttpRequest.UNSENT; }, getResponseHeader: function getResponseHeader(header) { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return null; } if (/^Set-Cookie2?$/i.test(header)) { return null; } header = header.toLowerCase(); for (var h in this.responseHeaders) { if (h.toLowerCase() == header) { return this.responseHeaders[h]; } } return null; }, getAllResponseHeaders: function getAllResponseHeaders() { if (this.readyState < FakeXMLHttpRequest.HEADERS_RECEIVED) { return ""; } var headers = ""; for (var header in this.responseHeaders) { if (this.responseHeaders.hasOwnProperty(header) && !/^Set-Cookie2?$/i.test(header)) { headers += header + ": " + this.responseHeaders[header] + "\r\n"; } } return headers; }, setResponseBody: function setResponseBody(body) { verifyRequestSent(this); verifyHeadersReceived(this); verifyResponseBodyType(body); var chunkSize = this.chunkSize || 10; var index = 0; this.responseText = ""; do { if (this.async) { this.readyStateChange(FakeXMLHttpRequest.LOADING); } this.responseText += body.substring(index, index + chunkSize); index += chunkSize; } while (index < body.length); var type = this.getResponseHeader("Content-Type"); if (this.responseText && (!type || /(text\/xml)|(application\/xml)|(\+xml)/.test(type))) { try { this.responseXML = FakeXMLHttpRequest.parseXML(this.responseText); } catch (e) { // Unable to parse XML - no biggie } } if (this.async) { this.readyStateChange(FakeXMLHttpRequest.DONE); } else { this.readyState = FakeXMLHttpRequest.DONE; } }, respond: function respond(status, headers, body) { this.setResponseHeaders(headers || {}); this.status = typeof status == "number" ? status : 200; this.statusText = FakeXMLHttpRequest.statusCodes[this.status]; this.setResponseBody(body || ""); } }); sinon.extend(FakeXMLHttpRequest, { UNSENT: 0, OPENED: 1, HEADERS_RECEIVED: 2, LOADING: 3, DONE: 4 }); // Borrowed from JSpec FakeXMLHttpRequest.parseXML = function parseXML(text) { var xmlDoc; if (typeof DOMParser != "undefined") { var parser = new DOMParser(); xmlDoc = parser.parseFromString(text, "text/xml"); } else { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); xmlDoc.async = "false"; xmlDoc.loadXML(text); } return xmlDoc; }; FakeXMLHttpRequest.statusCodes = { 100: "Continue", 101: "Switching Protocols", 200: "OK", 201: "Created", 202: "Accepted", 203: "Non-Authoritative Information", 204: "No Content", 205: "Reset Content", 206: "Partial Content", 300: "Multiple Choice", 301: "Moved Permanently", 302: "Found", 303: "See Other", 304: "Not Modified", 305: "Use Proxy", 307: "Temporary Redirect", 400: "Bad Request", 401: "Unauthorized", 402: "Payment Required", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed", 406: "Not Acceptable", 407: "Proxy Authentication Required", 408: "Request Timeout", 409: "Conflict", 410: "Gone", 411: "Length Required", 412: "Precondition Failed", 413: "Request Entity Too Large", 414: "Request-URI Too Long", 415: "Unsupported Media Type", 416: "Requested Range Not Satisfiable", 417: "Expectation Failed", 422: "Unprocessable Entity", 500: "Internal Server Error", 501: "Not Implemented", 502: "Bad Gateway", 503: "Service Unavailable", 504: "Gateway Timeout", 505: "HTTP Version Not Supported" }; sinon.useFakeXMLHttpRequest = function () { sinon.FakeXMLHttpRequest.restore = function restore(keepOnCreate) { if (xhr.supportsXHR) { global.XMLHttpRequest = xhr.GlobalXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = xhr.GlobalActiveXObject; } delete sinon.FakeXMLHttpRequest.restore; if (keepOnCreate !== true) { delete sinon.FakeXMLHttpRequest.onCreate; } }; if (xhr.supportsXHR) { global.XMLHttpRequest = sinon.FakeXMLHttpRequest; } if (xhr.supportsActiveX) { global.ActiveXObject = function ActiveXObject(objId) { if (objId == "Microsoft.XMLHTTP" || /^Msxml2\.XMLHTTP/i.test(objId)) { return new sinon.FakeXMLHttpRequest(); } return new xhr.GlobalActiveXObject(objId); }; } return sinon.FakeXMLHttpRequest; }; sinon.FakeXMLHttpRequest = FakeXMLHttpRequest; })(this); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /** * @depend fake_xml_http_request.js */ /*jslint eqeqeq: false, onevar: false, regexp: false, plusplus: false*/ /*global module, require, window*/ /** * The Sinon "server" mimics a web server that receives requests from * sinon.FakeXMLHttpRequest and provides an API to respond to those requests, * both synchronously and asynchronously. To respond synchronuously, canned * answers have to be provided upfront. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ if (typeof sinon == "undefined") { var sinon = {}; } sinon.fakeServer = (function () { var push = [].push; function F() {} function create(proto) { F.prototype = proto; return new F(); } function responseArray(handler) { var response = handler; if (Object.prototype.toString.call(handler) != "[object Array]") { response = [200, {}, handler]; } if (typeof response[2] != "string") { throw new TypeError("Fake server response body should be string, but was " + typeof response[2]); } return response; } var wloc = typeof window !== "undefined" ? window.location : {}; var rCurrLoc = new RegExp("^" + wloc.protocol + "//" + wloc.host); function matchOne(response, reqMethod, reqUrl) { var rmeth = response.method; var matchMethod = !rmeth || rmeth.toLowerCase() == reqMethod.toLowerCase(); var url = response.url; var matchUrl = !url || url == reqUrl || (typeof url.test == "function" && url.test(reqUrl)); return matchMethod && matchUrl; } function match(response, request) { var requestMethod = this.getHTTPMethod(request); var requestUrl = request.url; if (!/^https?:\/\//.test(requestUrl) || rCurrLoc.test(requestUrl)) { requestUrl = requestUrl.replace(rCurrLoc, ""); } if (matchOne(response, this.getHTTPMethod(request), requestUrl)) { if (typeof response.response == "function") { var ru = response.url; var args = [request].concat(!ru ? [] : requestUrl.match(ru).slice(1)); return response.response.apply(response, args); } return true; } return false; } return { create: function () { var server = create(this); this.xhr = sinon.useFakeXMLHttpRequest(); server.requests = []; this.xhr.onCreate = function (xhrObj) { server.addRequest(xhrObj); }; return server; }, addRequest: function addRequest(xhrObj) { var server = this; push.call(this.requests, xhrObj); xhrObj.onSend = function () { server.handleRequest(this); }; if (this.autoRespond && !this.responding) { setTimeout(function () { server.responding = false; server.respond(); }, this.autoRespondAfter || 10); this.responding = true; } }, getHTTPMethod: function getHTTPMethod(request) { if (this.fakeHTTPMethods && /post/i.test(request.method)) { var matches = (request.requestBody || "").match(/_method=([^\b;]+)/); return !!matches ? matches[1] : request.method; } return request.method; }, handleRequest: function handleRequest(xhr) { if (xhr.async) { if (!this.queue) { this.queue = []; } push.call(this.queue, xhr); } else { this.processRequest(xhr); } }, respondWith: function respondWith(method, url, body) { if (arguments.length == 1 && typeof method != "function") { this.response = responseArray(method); return; } if (!this.responses) { this.responses = []; } if (arguments.length == 1) { body = method; url = method = null; } if (arguments.length == 2) { body = url; url = method; method = null; } push.call(this.responses, { method: method, url: url, response: typeof body == "function" ? body : responseArray(body) }); }, respond: function respond() { if (arguments.length > 0) this.respondWith.apply(this, arguments); var queue = this.queue || []; var request; while(request = queue.shift()) { this.processRequest(request); } }, processRequest: function processRequest(request) { try { if (request.aborted) { return; } var response = this.response || [404, {}, ""]; if (this.responses) { for (var i = 0, l = this.responses.length; i < l; i++) { if (match.call(this, this.responses[i], request)) { response = this.responses[i].response; break; } } } if (request.readyState != 4) { request.respond(response[0], response[1], response[2]); } } catch (e) { sinon.logError("Fake server request processing", e); } }, restore: function restore() { return this.xhr.restore && this.xhr.restore.apply(this.xhr, arguments); } }; }()); if (typeof module == "object" && typeof require == "function") { module.exports = sinon; } /** * @depend fake_server.js * @depend fake_timers.js */ /*jslint browser: true, eqeqeq: false, onevar: false*/ /*global sinon*/ /** * Add-on for sinon.fakeServer that automatically handles a fake timer along with * the FakeXMLHttpRequest. The direct inspiration for this add-on is jQuery * 1.3.x, which does not use xhr object's onreadystatehandler at all - instead, * it polls the object for completion with setInterval. Dispite the direct * motivation, there is nothing jQuery-specific in this file, so it can be used * in any environment where the ajax implementation depends on setInterval or * setTimeout. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ (function () { function Server() {} Server.prototype = sinon.fakeServer; sinon.fakeServerWithClock = new Server(); sinon.fakeServerWithClock.addRequest = function addRequest(xhr) { if (xhr.async) { if (typeof setTimeout.clock == "object") { this.clock = setTimeout.clock; } else { this.clock = sinon.useFakeTimers(); this.resetClock = true; } if (!this.longestTimeout) { var clockSetTimeout = this.clock.setTimeout; var clockSetInterval = this.clock.setInterval; var server = this; this.clock.setTimeout = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetTimeout.apply(this, arguments); }; this.clock.setInterval = function (fn, timeout) { server.longestTimeout = Math.max(timeout, server.longestTimeout || 0); return clockSetInterval.apply(this, arguments); }; } } return sinon.fakeServer.addRequest.call(this, xhr); }; sinon.fakeServerWithClock.respond = function respond() { var returnVal = sinon.fakeServer.respond.apply(this, arguments); if (this.clock) { this.clock.tick(this.longestTimeout || 0); this.longestTimeout = 0; if (this.resetClock) { this.clock.restore(); this.resetClock = false; } } return returnVal; }; sinon.fakeServerWithClock.restore = function restore() { if (this.clock) { this.clock.restore(); } return sinon.fakeServer.restore.apply(this, arguments); }; }()); /** * @depend ../sinon.js * @depend collection.js * @depend util/fake_timers.js * @depend util/fake_server_with_clock.js */ /*jslint eqeqeq: false, onevar: false, plusplus: false*/ /*global require, module*/ /** * Manages fake collections as well as fake utilities such as Sinon's * timers and fake XHR implementation in one convenient object. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ if (typeof module == "object" && typeof require == "function") { var sinon = require("../sinon"); sinon.extend(sinon, require("./util/fake_timers")); } (function () { var push = [].push; function exposeValue(sandbox, config, key, value) { if (!value) { return; } if (config.injectInto) { config.injectInto[key] = value; } else { push.call(sandbox.args, value); } } function prepareSandboxFromConfig(config) { var sandbox = sinon.create(sinon.sandbox); if (config.useFakeServer) { if (typeof config.useFakeServer == "object") { sandbox.serverPrototype = config.useFakeServer; } sandbox.useFakeServer(); } if (config.useFakeTimers) { if (typeof config.useFakeTimers == "object") { sandbox.useFakeTimers.apply(sandbox, config.useFakeTimers); } else { sandbox.useFakeTimers(); } } return sandbox; } sinon.sandbox = sinon.extend(sinon.create(sinon.collection), { useFakeTimers: function useFakeTimers() { this.clock = sinon.useFakeTimers.apply(sinon, arguments); return this.add(this.clock); }, serverPrototype: sinon.fakeServer, useFakeServer: function useFakeServer() { var proto = this.serverPrototype || sinon.fakeServer; if (!proto || !proto.create) { return null; } this.server = proto.create(); return this.add(this.server); }, inject: function (obj) { sinon.collection.inject.call(this, obj); if (this.clock) { obj.clock = this.clock; } if (this.server) { obj.server = this.server; obj.requests = this.server.requests; } return obj; }, create: function (config) { if (!config) { return sinon.create(sinon.sandbox); } var sandbox = prepareSandboxFromConfig(config); sandbox.args = sandbox.args || []; var prop, value, exposed = sandbox.inject({}); if (config.properties) { for (var i = 0, l = config.properties.length; i < l; i++) { prop = config.properties[i]; value = exposed[prop] || prop == "sandbox" && sandbox; exposeValue(sandbox, config, prop, value); } } else { exposeValue(sandbox, config, "sandbox", value); } return sandbox; } }); sinon.sandbox.useFakeXMLHttpRequest = sinon.sandbox.useFakeServer; if (typeof module == "object" && typeof require == "function") { module.exports = sinon.sandbox; } }()); /** * @depend ../sinon.js * @depend stub.js * @depend mock.js * @depend sandbox.js */ /*jslint eqeqeq: false, onevar: false, forin: true, plusplus: false*/ /*global module, require, sinon*/ /** * Test function, sandboxes fakes * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function test(callback) { var type = typeof callback; if (type != "function") { throw new TypeError("sinon.test needs to wrap a test function, got " + type); } return function () { var config = sinon.getConfig(sinon.config); config.injectInto = config.injectIntoThis && this || config.injectInto; var sandbox = sinon.sandbox.create(config); var exception, result; var args = Array.prototype.slice.call(arguments).concat(sandbox.args); try { result = callback.apply(this, args); } finally { sandbox.verifyAndRestore(); } return result; }; } test.config = { injectIntoThis: true, injectInto: null, properties: ["spy", "stub", "mock", "clock", "server", "requests"], useFakeTimers: true, useFakeServer: true }; if (commonJSModule) { module.exports = test; } else { sinon.test = test; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend test.js */ /*jslint eqeqeq: false, onevar: false, eqeqeq: false*/ /*global module, require, sinon*/ /** * Test case, sandboxes all test functions * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ (function (sinon) { var commonJSModule = typeof module == "object" && typeof require == "function"; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon || !Object.prototype.hasOwnProperty) { return; } function createTest(property, setUp, tearDown) { return function () { if (setUp) { setUp.apply(this, arguments); } var exception, result; try { result = property.apply(this, arguments); } catch (e) { exception = e; } if (tearDown) { tearDown.apply(this, arguments); } if (exception) { throw exception; } return result; }; } function testCase(tests, prefix) { /*jsl:ignore*/ if (!tests || typeof tests != "object") { throw new TypeError("sinon.testCase needs an object with test functions"); } /*jsl:end*/ prefix = prefix || "test"; var rPrefix = new RegExp("^" + prefix); var methods = {}, testName, property, method; var setUp = tests.setUp; var tearDown = tests.tearDown; for (testName in tests) { if (tests.hasOwnProperty(testName)) { property = tests[testName]; if (/^(setUp|tearDown)$/.test(testName)) { continue; } if (typeof property == "function" && rPrefix.test(testName)) { method = property; if (setUp || tearDown) { method = createTest(property, setUp, tearDown); } methods[testName] = sinon.test(method); } else { methods[testName] = tests[testName]; } } } return methods; } if (commonJSModule) { module.exports = testCase; } else { sinon.testCase = testCase; } }(typeof sinon == "object" && sinon || null)); /** * @depend ../sinon.js * @depend stub.js */ /*jslint eqeqeq: false, onevar: false, nomen: false, plusplus: false*/ /*global module, require, sinon*/ /** * Assertions matching the test spy retrieval interface. * * @author Christian Johansen ([email protected]) * @license BSD * * Copyright (c) 2010-2011 Christian Johansen */ (function (sinon, global) { var commonJSModule = typeof module == "object" && typeof require == "function"; var slice = Array.prototype.slice; var assert; if (!sinon && commonJSModule) { sinon = require("../sinon"); } if (!sinon) { return; } function verifyIsStub() { var method; for (var i = 0, l = arguments.length; i < l; ++i) { method = arguments[i]; if (!method) { assert.fail("fake is not a spy"); } if (typeof method != "function") { assert.fail(method + " is not a function"); } if (typeof method.getCall != "function") { assert.fail(method + " is not stubbed"); } } } function failAssertion(object, msg) { object = object || global; var failMethod = object.fail || assert.fail; failMethod.call(object, msg); } function mirrorPropAsAssertion(name, method, message) { if (arguments.length == 2) { message = method; method = name; } assert[name] = function (fake) { verifyIsStub(fake); var args = slice.call(arguments, 1); var failed = false; if (typeof method == "function") { failed = !method(fake); } else { failed = typeof fake[method] == "function" ? !fake[method].apply(fake, args) : !fake[method]; } if (failed) { failAssertion(this, fake.printf.apply(fake, [message].concat(args))); } else { assert.pass(name); } }; } function exposedName(prefix, prop) { return !prefix || /^fail/.test(prop) ? prop : prefix + prop.slice(0, 1).toUpperCase() + prop.slice(1); }; assert = { failException: "AssertError", fail: function fail(message) { var error = new Error(message); error.name = this.failException || assert.failException; throw error; }, pass: function pass(assertion) {}, callOrder: function assertCallOrder() { verifyIsStub.apply(null, arguments); var expected = "", actual = ""; if (!sinon.calledInOrder(arguments)) { try { expected = [].join.call(arguments, ", "); actual = sinon.orderByFirstCall(slice.call(arguments)).join(", "); } catch (e) { // If this fails, we'll just fall back to the blank string } failAssertion(this, "expected " + expected + " to be " + "called in order but were called as " + actual); } else { assert.pass("callOrder"); } }, callCount: function assertCallCount(method, count) { verifyIsStub(method); if (method.callCount != count) { var msg = "expected %n to be called " + sinon.timesInWords(count) + " but was called %c%C"; failAssertion(this, method.printf(msg)); } else { assert.pass("callCount"); } }, expose: function expose(target, options) { if (!target) { throw new TypeError("target is null or undefined"); } var o = options || {}; var prefix = typeof o.prefix == "undefined" && "assert" || o.prefix; var includeFail = typeof o.includeFail == "undefined" || !!o.includeFail; for (var method in this) { if (method != "export" && (includeFail || !/^(fail)/.test(method))) { target[exposedName(prefix, method)] = this[method]; } } return target; } }; mirrorPropAsAssertion("called", "expected %n to have been called at least once but was never called"); mirrorPropAsAssertion("notCalled", function (spy) { return !spy.called; }, "expected %n to not have been called but was called %c%C"); mirrorPropAsAssertion("calledOnce", "expected %n to be called once but was called %c%C"); mirrorPropAsAssertion("calledTwice", "expected %n to be called twice but was called %c%C"); mirrorPropAsAssertion("calledThrice", "expected %n to be called thrice but was called %c%C"); mirrorPropAsAssertion("calledOn", "expected %n to be called with %1 as this but was called with %t"); mirrorPropAsAssertion("alwaysCalledOn", "expected %n to always be called with %1 as this but was called with %t"); mirrorPropAsAssertion("calledWithNew", "expected %n to be called with new"); mirrorPropAsAssertion("alwaysCalledWithNew", "expected %n to always be called with new"); mirrorPropAsAssertion("calledWith", "expected %n to be called with arguments %*%C"); mirrorPropAsAssertion("calledWithMatch", "expected %n to be called with match %*%C"); mirrorPropAsAssertion("alwaysCalledWith", "expected %n to always be called with arguments %*%C"); mirrorPropAsAssertion("alwaysCalledWithMatch", "expected %n to always be called with match %*%C"); mirrorPropAsAssertion("calledWithExactly", "expected %n to be called with exact arguments %*%C"); mirrorPropAsAssertion("alwaysCalledWithExactly", "expected %n to always be called with exact arguments %*%C"); mirrorPropAsAssertion("neverCalledWith", "expected %n to never be called with arguments %*%C"); mirrorPropAsAssertion("neverCalledWithMatch", "expected %n to never be called with match %*%C"); mirrorPropAsAssertion("threw", "%n did not throw exception%C"); mirrorPropAsAssertion("alwaysThrew", "%n did not always throw exception%C"); if (commonJSModule) { module.exports = assert; } else { sinon.assert = assert; } }(typeof sinon == "object" && sinon || null, typeof window != "undefined" ? window : global)); return sinon;}.call(typeof window != 'undefined' && window || {}));
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/libs/pdfjs-1.3.91p1/pdf.js
9,534
/* Copyright 2012 Mozilla Foundation * * 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. */ /*jshint globalstrict: false */ /* globals PDFJS */ // Initializing PDFJS global object (if still undefined) if (typeof PDFJS === 'undefined') { (typeof window !== 'undefined' ? window : this).PDFJS = {}; } PDFJS.version = '1.3.91'; PDFJS.build = 'd1e83b5'; (function pdfjsWrapper() { // Use strict in our context only - users might not want it 'use strict'; var globalScope = (typeof window === 'undefined') ? this : window; var isWorker = (typeof window === 'undefined'); var FONT_IDENTITY_MATRIX = [0.001, 0, 0, 0.001, 0, 0]; var TextRenderingMode = { FILL: 0, STROKE: 1, FILL_STROKE: 2, INVISIBLE: 3, FILL_ADD_TO_PATH: 4, STROKE_ADD_TO_PATH: 5, FILL_STROKE_ADD_TO_PATH: 6, ADD_TO_PATH: 7, FILL_STROKE_MASK: 3, ADD_TO_PATH_FLAG: 4 }; var ImageKind = { GRAYSCALE_1BPP: 1, RGB_24BPP: 2, RGBA_32BPP: 3 }; var AnnotationType = { TEXT: 1, LINK: 2, FREETEXT: 3, LINE: 4, SQUARE: 5, CIRCLE: 6, POLYGON: 7, POLYLINE: 8, HIGHLIGHT: 9, UNDERLINE: 10, SQUIGGLY: 11, STRIKEOUT: 12, STAMP: 13, CARET: 14, INK: 15, POPUP: 16, FILEATTACHMENT: 17, SOUND: 18, MOVIE: 19, WIDGET: 20, SCREEN: 21, PRINTERMARK: 22, TRAPNET: 23, WATERMARK: 24, THREED: 25, REDACT: 26 }; var AnnotationFlag = { INVISIBLE: 0x01, HIDDEN: 0x02, PRINT: 0x04, NOZOOM: 0x08, NOROTATE: 0x10, NOVIEW: 0x20, READONLY: 0x40, LOCKED: 0x80, TOGGLENOVIEW: 0x100, LOCKEDCONTENTS: 0x200 }; var AnnotationBorderStyleType = { SOLID: 1, DASHED: 2, BEVELED: 3, INSET: 4, UNDERLINE: 5 }; var StreamType = { UNKNOWN: 0, FLATE: 1, LZW: 2, DCT: 3, JPX: 4, JBIG: 5, A85: 6, AHX: 7, CCF: 8, RL: 9 }; var FontType = { UNKNOWN: 0, TYPE1: 1, TYPE1C: 2, CIDFONTTYPE0: 3, CIDFONTTYPE0C: 4, TRUETYPE: 5, CIDFONTTYPE2: 6, TYPE3: 7, OPENTYPE: 8, TYPE0: 9, MMTYPE1: 10 }; // The global PDFJS object exposes the API // In production, it will be declared outside a global wrapper // In development, it will be declared here if (!globalScope.PDFJS) { globalScope.PDFJS = {}; } globalScope.PDFJS.pdfBug = false; PDFJS.VERBOSITY_LEVELS = { errors: 0, warnings: 1, infos: 5 }; // All the possible operations for an operator list. var OPS = PDFJS.OPS = { // Intentionally start from 1 so it is easy to spot bad operators that will be // 0's. dependency: 1, setLineWidth: 2, setLineCap: 3, setLineJoin: 4, setMiterLimit: 5, setDash: 6, setRenderingIntent: 7, setFlatness: 8, setGState: 9, save: 10, restore: 11, transform: 12, moveTo: 13, lineTo: 14, curveTo: 15, curveTo2: 16, curveTo3: 17, closePath: 18, rectangle: 19, stroke: 20, closeStroke: 21, fill: 22, eoFill: 23, fillStroke: 24, eoFillStroke: 25, closeFillStroke: 26, closeEOFillStroke: 27, endPath: 28, clip: 29, eoClip: 30, beginText: 31, endText: 32, setCharSpacing: 33, setWordSpacing: 34, setHScale: 35, setLeading: 36, setFont: 37, setTextRenderingMode: 38, setTextRise: 39, moveText: 40, setLeadingMoveText: 41, setTextMatrix: 42, nextLine: 43, showText: 44, showSpacedText: 45, nextLineShowText: 46, nextLineSetSpacingShowText: 47, setCharWidth: 48, setCharWidthAndBounds: 49, setStrokeColorSpace: 50, setFillColorSpace: 51, setStrokeColor: 52, setStrokeColorN: 53, setFillColor: 54, setFillColorN: 55, setStrokeGray: 56, setFillGray: 57, setStrokeRGBColor: 58, setFillRGBColor: 59, setStrokeCMYKColor: 60, setFillCMYKColor: 61, shadingFill: 62, beginInlineImage: 63, beginImageData: 64, endInlineImage: 65, paintXObject: 66, markPoint: 67, markPointProps: 68, beginMarkedContent: 69, beginMarkedContentProps: 70, endMarkedContent: 71, beginCompat: 72, endCompat: 73, paintFormXObjectBegin: 74, paintFormXObjectEnd: 75, beginGroup: 76, endGroup: 77, beginAnnotations: 78, endAnnotations: 79, beginAnnotation: 80, endAnnotation: 81, paintJpegXObject: 82, paintImageMaskXObject: 83, paintImageMaskXObjectGroup: 84, paintImageXObject: 85, paintInlineImageXObject: 86, paintInlineImageXObjectGroup: 87, paintImageXObjectRepeat: 88, paintImageMaskXObjectRepeat: 89, paintSolidColorImageMask: 90, constructPath: 91 }; // A notice for devs. These are good for things that are helpful to devs, such // as warning that Workers were disabled, which is important to devs but not // end users. function info(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.infos) { console.log('Info: ' + msg); } } // Non-fatal warnings. function warn(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.warnings) { console.log('Warning: ' + msg); } } // Deprecated API function -- treated as warnings. function deprecated(details) { warn('Deprecated API usage: ' + details); } // Fatal errors that should trigger the fallback UI and halt execution by // throwing an exception. function error(msg) { if (PDFJS.verbosity >= PDFJS.VERBOSITY_LEVELS.errors) { console.log('Error: ' + msg); console.log(backtrace()); } throw new Error(msg); } function backtrace() { try { throw new Error(); } catch (e) { return e.stack ? e.stack.split('\n').slice(2).join('\n') : ''; } } function assert(cond, msg) { if (!cond) { error(msg); } } var UNSUPPORTED_FEATURES = PDFJS.UNSUPPORTED_FEATURES = { unknown: 'unknown', forms: 'forms', javaScript: 'javaScript', smask: 'smask', shadingPattern: 'shadingPattern', font: 'font' }; // Combines two URLs. The baseUrl shall be absolute URL. If the url is an // absolute URL, it will be returned as is. function combineUrl(baseUrl, url) { if (!url) { return baseUrl; } return new URL(url, baseUrl).href; } // Validates if URL is safe and allowed, e.g. to avoid XSS. function isValidUrl(url, allowRelative) { if (!url) { return false; } // RFC 3986 (http://tools.ietf.org/html/rfc3986#section-3.1) // scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." ) var protocol = /^[a-z][a-z0-9+\-.]*(?=:)/i.exec(url); if (!protocol) { return allowRelative; } protocol = protocol[0].toLowerCase(); switch (protocol) { case 'http': case 'https': case 'ftp': case 'mailto': case 'tel': return true; default: return false; } } PDFJS.isValidUrl = isValidUrl; function shadow(obj, prop, value) { Object.defineProperty(obj, prop, { value: value, enumerable: true, configurable: true, writable: false }); return value; } PDFJS.shadow = shadow; var LinkTarget = PDFJS.LinkTarget = { NONE: 0, // Default value. SELF: 1, BLANK: 2, PARENT: 3, TOP: 4, }; var LinkTargetStringMap = [ '', '_self', '_blank', '_parent', '_top' ]; function isExternalLinkTargetSet() { if (PDFJS.openExternalLinksInNewWindow) { deprecated('PDFJS.openExternalLinksInNewWindow, please use ' + '"PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK" instead.'); if (PDFJS.externalLinkTarget === LinkTarget.NONE) { PDFJS.externalLinkTarget = LinkTarget.BLANK; } // Reset the deprecated parameter, to suppress further warnings. PDFJS.openExternalLinksInNewWindow = false; } switch (PDFJS.externalLinkTarget) { case LinkTarget.NONE: return false; case LinkTarget.SELF: case LinkTarget.BLANK: case LinkTarget.PARENT: case LinkTarget.TOP: return true; } warn('PDFJS.externalLinkTarget is invalid: ' + PDFJS.externalLinkTarget); // Reset the external link target, to suppress further warnings. PDFJS.externalLinkTarget = LinkTarget.NONE; return false; } PDFJS.isExternalLinkTargetSet = isExternalLinkTargetSet; var PasswordResponses = PDFJS.PasswordResponses = { NEED_PASSWORD: 1, INCORRECT_PASSWORD: 2 }; var PasswordException = (function PasswordExceptionClosure() { function PasswordException(msg, code) { this.name = 'PasswordException'; this.message = msg; this.code = code; } PasswordException.prototype = new Error(); PasswordException.constructor = PasswordException; return PasswordException; })(); PDFJS.PasswordException = PasswordException; var UnknownErrorException = (function UnknownErrorExceptionClosure() { function UnknownErrorException(msg, details) { this.name = 'UnknownErrorException'; this.message = msg; this.details = details; } UnknownErrorException.prototype = new Error(); UnknownErrorException.constructor = UnknownErrorException; return UnknownErrorException; })(); PDFJS.UnknownErrorException = UnknownErrorException; var InvalidPDFException = (function InvalidPDFExceptionClosure() { function InvalidPDFException(msg) { this.name = 'InvalidPDFException'; this.message = msg; } InvalidPDFException.prototype = new Error(); InvalidPDFException.constructor = InvalidPDFException; return InvalidPDFException; })(); PDFJS.InvalidPDFException = InvalidPDFException; var MissingPDFException = (function MissingPDFExceptionClosure() { function MissingPDFException(msg) { this.name = 'MissingPDFException'; this.message = msg; } MissingPDFException.prototype = new Error(); MissingPDFException.constructor = MissingPDFException; return MissingPDFException; })(); PDFJS.MissingPDFException = MissingPDFException; var UnexpectedResponseException = (function UnexpectedResponseExceptionClosure() { function UnexpectedResponseException(msg, status) { this.name = 'UnexpectedResponseException'; this.message = msg; this.status = status; } UnexpectedResponseException.prototype = new Error(); UnexpectedResponseException.constructor = UnexpectedResponseException; return UnexpectedResponseException; })(); PDFJS.UnexpectedResponseException = UnexpectedResponseException; var NotImplementedException = (function NotImplementedExceptionClosure() { function NotImplementedException(msg) { this.message = msg; } NotImplementedException.prototype = new Error(); NotImplementedException.prototype.name = 'NotImplementedException'; NotImplementedException.constructor = NotImplementedException; return NotImplementedException; })(); var MissingDataException = (function MissingDataExceptionClosure() { function MissingDataException(begin, end) { this.begin = begin; this.end = end; this.message = 'Missing data [' + begin + ', ' + end + ')'; } MissingDataException.prototype = new Error(); MissingDataException.prototype.name = 'MissingDataException'; MissingDataException.constructor = MissingDataException; return MissingDataException; })(); var XRefParseException = (function XRefParseExceptionClosure() { function XRefParseException(msg) { this.message = msg; } XRefParseException.prototype = new Error(); XRefParseException.prototype.name = 'XRefParseException'; XRefParseException.constructor = XRefParseException; return XRefParseException; })(); function bytesToString(bytes) { assert(bytes !== null && typeof bytes === 'object' && bytes.length !== undefined, 'Invalid argument for bytesToString'); var length = bytes.length; var MAX_ARGUMENT_COUNT = 8192; if (length < MAX_ARGUMENT_COUNT) { return String.fromCharCode.apply(null, bytes); } var strBuf = []; for (var i = 0; i < length; i += MAX_ARGUMENT_COUNT) { var chunkEnd = Math.min(i + MAX_ARGUMENT_COUNT, length); var chunk = bytes.subarray(i, chunkEnd); strBuf.push(String.fromCharCode.apply(null, chunk)); } return strBuf.join(''); } function stringToBytes(str) { assert(typeof str === 'string', 'Invalid argument for stringToBytes'); var length = str.length; var bytes = new Uint8Array(length); for (var i = 0; i < length; ++i) { bytes[i] = str.charCodeAt(i) & 0xFF; } return bytes; } function string32(value) { return String.fromCharCode((value >> 24) & 0xff, (value >> 16) & 0xff, (value >> 8) & 0xff, value & 0xff); } function log2(x) { var n = 1, i = 0; while (x > n) { n <<= 1; i++; } return i; } function readInt8(data, start) { return (data[start] << 24) >> 24; } function readUint16(data, offset) { return (data[offset] << 8) | data[offset + 1]; } function readUint32(data, offset) { return ((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]) >>> 0; } // Lazy test the endianness of the platform // NOTE: This will be 'true' for simulated TypedArrays function isLittleEndian() { var buffer8 = new Uint8Array(2); buffer8[0] = 1; var buffer16 = new Uint16Array(buffer8.buffer); return (buffer16[0] === 1); } Object.defineProperty(PDFJS, 'isLittleEndian', { configurable: true, get: function PDFJS_isLittleEndian() { return shadow(PDFJS, 'isLittleEndian', isLittleEndian()); } }); // Lazy test if the userAgent support CanvasTypedArrays function hasCanvasTypedArrays() { var canvas = document.createElement('canvas'); canvas.width = canvas.height = 1; var ctx = canvas.getContext('2d'); var imageData = ctx.createImageData(1, 1); return (typeof imageData.data.buffer !== 'undefined'); } Object.defineProperty(PDFJS, 'hasCanvasTypedArrays', { configurable: true, get: function PDFJS_hasCanvasTypedArrays() { return shadow(PDFJS, 'hasCanvasTypedArrays', hasCanvasTypedArrays()); } }); var Uint32ArrayView = (function Uint32ArrayViewClosure() { function Uint32ArrayView(buffer, length) { this.buffer = buffer; this.byteLength = buffer.length; this.length = length === undefined ? (this.byteLength >> 2) : length; ensureUint32ArrayViewProps(this.length); } Uint32ArrayView.prototype = Object.create(null); var uint32ArrayViewSetters = 0; function createUint32ArrayProp(index) { return { get: function () { var buffer = this.buffer, offset = index << 2; return (buffer[offset] | (buffer[offset + 1] << 8) | (buffer[offset + 2] << 16) | (buffer[offset + 3] << 24)) >>> 0; }, set: function (value) { var buffer = this.buffer, offset = index << 2; buffer[offset] = value & 255; buffer[offset + 1] = (value >> 8) & 255; buffer[offset + 2] = (value >> 16) & 255; buffer[offset + 3] = (value >>> 24) & 255; } }; } function ensureUint32ArrayViewProps(length) { while (uint32ArrayViewSetters < length) { Object.defineProperty(Uint32ArrayView.prototype, uint32ArrayViewSetters, createUint32ArrayProp(uint32ArrayViewSetters)); uint32ArrayViewSetters++; } } return Uint32ArrayView; })(); var IDENTITY_MATRIX = [1, 0, 0, 1, 0, 0]; var Util = PDFJS.Util = (function UtilClosure() { function Util() {} var rgbBuf = ['rgb(', 0, ',', 0, ',', 0, ')']; // makeCssRgb() can be called thousands of times. Using |rgbBuf| avoids // creating many intermediate strings. Util.makeCssRgb = function Util_makeCssRgb(r, g, b) { rgbBuf[1] = r; rgbBuf[3] = g; rgbBuf[5] = b; return rgbBuf.join(''); }; // Concatenates two transformation matrices together and returns the result. Util.transform = function Util_transform(m1, m2) { return [ m1[0] * m2[0] + m1[2] * m2[1], m1[1] * m2[0] + m1[3] * m2[1], m1[0] * m2[2] + m1[2] * m2[3], m1[1] * m2[2] + m1[3] * m2[3], m1[0] * m2[4] + m1[2] * m2[5] + m1[4], m1[1] * m2[4] + m1[3] * m2[5] + m1[5] ]; }; // For 2d affine transforms Util.applyTransform = function Util_applyTransform(p, m) { var xt = p[0] * m[0] + p[1] * m[2] + m[4]; var yt = p[0] * m[1] + p[1] * m[3] + m[5]; return [xt, yt]; }; Util.applyInverseTransform = function Util_applyInverseTransform(p, m) { var d = m[0] * m[3] - m[1] * m[2]; var xt = (p[0] * m[3] - p[1] * m[2] + m[2] * m[5] - m[4] * m[3]) / d; var yt = (-p[0] * m[1] + p[1] * m[0] + m[4] * m[1] - m[5] * m[0]) / d; return [xt, yt]; }; // Applies the transform to the rectangle and finds the minimum axially // aligned bounding box. Util.getAxialAlignedBoundingBox = function Util_getAxialAlignedBoundingBox(r, m) { var p1 = Util.applyTransform(r, m); var p2 = Util.applyTransform(r.slice(2, 4), m); var p3 = Util.applyTransform([r[0], r[3]], m); var p4 = Util.applyTransform([r[2], r[1]], m); return [ Math.min(p1[0], p2[0], p3[0], p4[0]), Math.min(p1[1], p2[1], p3[1], p4[1]), Math.max(p1[0], p2[0], p3[0], p4[0]), Math.max(p1[1], p2[1], p3[1], p4[1]) ]; }; Util.inverseTransform = function Util_inverseTransform(m) { var d = m[0] * m[3] - m[1] * m[2]; return [m[3] / d, -m[1] / d, -m[2] / d, m[0] / d, (m[2] * m[5] - m[4] * m[3]) / d, (m[4] * m[1] - m[5] * m[0]) / d]; }; // Apply a generic 3d matrix M on a 3-vector v: // | a b c | | X | // | d e f | x | Y | // | g h i | | Z | // M is assumed to be serialized as [a,b,c,d,e,f,g,h,i], // with v as [X,Y,Z] Util.apply3dTransform = function Util_apply3dTransform(m, v) { return [ m[0] * v[0] + m[1] * v[1] + m[2] * v[2], m[3] * v[0] + m[4] * v[1] + m[5] * v[2], m[6] * v[0] + m[7] * v[1] + m[8] * v[2] ]; }; // This calculation uses Singular Value Decomposition. // The SVD can be represented with formula A = USV. We are interested in the // matrix S here because it represents the scale values. Util.singularValueDecompose2dScale = function Util_singularValueDecompose2dScale(m) { var transpose = [m[0], m[2], m[1], m[3]]; // Multiply matrix m with its transpose. var a = m[0] * transpose[0] + m[1] * transpose[2]; var b = m[0] * transpose[1] + m[1] * transpose[3]; var c = m[2] * transpose[0] + m[3] * transpose[2]; var d = m[2] * transpose[1] + m[3] * transpose[3]; // Solve the second degree polynomial to get roots. var first = (a + d) / 2; var second = Math.sqrt((a + d) * (a + d) - 4 * (a * d - c * b)) / 2; var sx = first + second || 1; var sy = first - second || 1; // Scale values are the square roots of the eigenvalues. return [Math.sqrt(sx), Math.sqrt(sy)]; }; // Normalize rectangle rect=[x1, y1, x2, y2] so that (x1,y1) < (x2,y2) // For coordinate systems whose origin lies in the bottom-left, this // means normalization to (BL,TR) ordering. For systems with origin in the // top-left, this means (TL,BR) ordering. Util.normalizeRect = function Util_normalizeRect(rect) { var r = rect.slice(0); // clone rect if (rect[0] > rect[2]) { r[0] = rect[2]; r[2] = rect[0]; } if (rect[1] > rect[3]) { r[1] = rect[3]; r[3] = rect[1]; } return r; }; // Returns a rectangle [x1, y1, x2, y2] corresponding to the // intersection of rect1 and rect2. If no intersection, returns 'false' // The rectangle coordinates of rect1, rect2 should be [x1, y1, x2, y2] Util.intersect = function Util_intersect(rect1, rect2) { function compare(a, b) { return a - b; } // Order points along the axes var orderedX = [rect1[0], rect1[2], rect2[0], rect2[2]].sort(compare), orderedY = [rect1[1], rect1[3], rect2[1], rect2[3]].sort(compare), result = []; rect1 = Util.normalizeRect(rect1); rect2 = Util.normalizeRect(rect2); // X: first and second points belong to different rectangles? if ((orderedX[0] === rect1[0] && orderedX[1] === rect2[0]) || (orderedX[0] === rect2[0] && orderedX[1] === rect1[0])) { // Intersection must be between second and third points result[0] = orderedX[1]; result[2] = orderedX[2]; } else { return false; } // Y: first and second points belong to different rectangles? if ((orderedY[0] === rect1[1] && orderedY[1] === rect2[1]) || (orderedY[0] === rect2[1] && orderedY[1] === rect1[1])) { // Intersection must be between second and third points result[1] = orderedY[1]; result[3] = orderedY[2]; } else { return false; } return result; }; Util.sign = function Util_sign(num) { return num < 0 ? -1 : 1; }; Util.appendToArray = function Util_appendToArray(arr1, arr2) { Array.prototype.push.apply(arr1, arr2); }; Util.prependToArray = function Util_prependToArray(arr1, arr2) { Array.prototype.unshift.apply(arr1, arr2); }; Util.extendObj = function extendObj(obj1, obj2) { for (var key in obj2) { obj1[key] = obj2[key]; } }; Util.getInheritableProperty = function Util_getInheritableProperty(dict, name) { while (dict && !dict.has(name)) { dict = dict.get('Parent'); } if (!dict) { return null; } return dict.get(name); }; Util.inherit = function Util_inherit(sub, base, prototype) { sub.prototype = Object.create(base.prototype); sub.prototype.constructor = sub; for (var prop in prototype) { sub.prototype[prop] = prototype[prop]; } }; Util.loadScript = function Util_loadScript(src, callback) { var script = document.createElement('script'); var loaded = false; script.setAttribute('src', src); if (callback) { script.onload = function() { if (!loaded) { callback(); } loaded = true; }; } document.getElementsByTagName('head')[0].appendChild(script); }; return Util; })(); /** * PDF page viewport created based on scale, rotation and offset. * @class * @alias PDFJS.PageViewport */ var PageViewport = PDFJS.PageViewport = (function PageViewportClosure() { /** * @constructor * @private * @param viewBox {Array} xMin, yMin, xMax and yMax coordinates. * @param scale {number} scale of the viewport. * @param rotation {number} rotations of the viewport in degrees. * @param offsetX {number} offset X * @param offsetY {number} offset Y * @param dontFlip {boolean} if true, axis Y will not be flipped. */ function PageViewport(viewBox, scale, rotation, offsetX, offsetY, dontFlip) { this.viewBox = viewBox; this.scale = scale; this.rotation = rotation; this.offsetX = offsetX; this.offsetY = offsetY; // creating transform to convert pdf coordinate system to the normal // canvas like coordinates taking in account scale and rotation var centerX = (viewBox[2] + viewBox[0]) / 2; var centerY = (viewBox[3] + viewBox[1]) / 2; var rotateA, rotateB, rotateC, rotateD; rotation = rotation % 360; rotation = rotation < 0 ? rotation + 360 : rotation; switch (rotation) { case 180: rotateA = -1; rotateB = 0; rotateC = 0; rotateD = 1; break; case 90: rotateA = 0; rotateB = 1; rotateC = 1; rotateD = 0; break; case 270: rotateA = 0; rotateB = -1; rotateC = -1; rotateD = 0; break; //case 0: default: rotateA = 1; rotateB = 0; rotateC = 0; rotateD = -1; break; } if (dontFlip) { rotateC = -rotateC; rotateD = -rotateD; } var offsetCanvasX, offsetCanvasY; var width, height; if (rotateA === 0) { offsetCanvasX = Math.abs(centerY - viewBox[1]) * scale + offsetX; offsetCanvasY = Math.abs(centerX - viewBox[0]) * scale + offsetY; width = Math.abs(viewBox[3] - viewBox[1]) * scale; height = Math.abs(viewBox[2] - viewBox[0]) * scale; } else { offsetCanvasX = Math.abs(centerX - viewBox[0]) * scale + offsetX; offsetCanvasY = Math.abs(centerY - viewBox[1]) * scale + offsetY; width = Math.abs(viewBox[2] - viewBox[0]) * scale; height = Math.abs(viewBox[3] - viewBox[1]) * scale; } // creating transform for the following operations: // translate(-centerX, -centerY), rotate and flip vertically, // scale, and translate(offsetCanvasX, offsetCanvasY) this.transform = [ rotateA * scale, rotateB * scale, rotateC * scale, rotateD * scale, offsetCanvasX - rotateA * scale * centerX - rotateC * scale * centerY, offsetCanvasY - rotateB * scale * centerX - rotateD * scale * centerY ]; this.width = width; this.height = height; this.fontScale = scale; } PageViewport.prototype = /** @lends PDFJS.PageViewport.prototype */ { /** * Clones viewport with additional properties. * @param args {Object} (optional) If specified, may contain the 'scale' or * 'rotation' properties to override the corresponding properties in * the cloned viewport. * @returns {PDFJS.PageViewport} Cloned viewport. */ clone: function PageViewPort_clone(args) { args = args || {}; var scale = 'scale' in args ? args.scale : this.scale; var rotation = 'rotation' in args ? args.rotation : this.rotation; return new PageViewport(this.viewBox.slice(), scale, rotation, this.offsetX, this.offsetY, args.dontFlip); }, /** * Converts PDF point to the viewport coordinates. For examples, useful for * converting PDF location into canvas pixel coordinates. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the viewport coordinate space. * @see {@link convertToPdfPoint} * @see {@link convertToViewportRectangle} */ convertToViewportPoint: function PageViewport_convertToViewportPoint(x, y) { return Util.applyTransform([x, y], this.transform); }, /** * Converts PDF rectangle to the viewport coordinates. * @param rect {Array} xMin, yMin, xMax and yMax coordinates. * @returns {Array} Contains corresponding coordinates of the rectangle * in the viewport coordinate space. * @see {@link convertToViewportPoint} */ convertToViewportRectangle: function PageViewport_convertToViewportRectangle(rect) { var tl = Util.applyTransform([rect[0], rect[1]], this.transform); var br = Util.applyTransform([rect[2], rect[3]], this.transform); return [tl[0], tl[1], br[0], br[1]]; }, /** * Converts viewport coordinates to the PDF location. For examples, useful * for converting canvas pixel location into PDF one. * @param x {number} X coordinate. * @param y {number} Y coordinate. * @returns {Object} Object that contains 'x' and 'y' properties of the * point in the PDF coordinate space. * @see {@link convertToViewportPoint} */ convertToPdfPoint: function PageViewport_convertToPdfPoint(x, y) { return Util.applyInverseTransform([x, y], this.transform); } }; return PageViewport; })(); var PDFStringTranslateTable = [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2D8, 0x2C7, 0x2C6, 0x2D9, 0x2DD, 0x2DB, 0x2DA, 0x2DC, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x2022, 0x2020, 0x2021, 0x2026, 0x2014, 0x2013, 0x192, 0x2044, 0x2039, 0x203A, 0x2212, 0x2030, 0x201E, 0x201C, 0x201D, 0x2018, 0x2019, 0x201A, 0x2122, 0xFB01, 0xFB02, 0x141, 0x152, 0x160, 0x178, 0x17D, 0x131, 0x142, 0x153, 0x161, 0x17E, 0, 0x20AC ]; function stringToPDFString(str) { var i, n = str.length, strBuf = []; if (str[0] === '\xFE' && str[1] === '\xFF') { // UTF16BE BOM for (i = 2; i < n; i += 2) { strBuf.push(String.fromCharCode( (str.charCodeAt(i) << 8) | str.charCodeAt(i + 1))); } } else { for (i = 0; i < n; ++i) { var code = PDFStringTranslateTable[str.charCodeAt(i)]; strBuf.push(code ? String.fromCharCode(code) : str.charAt(i)); } } return strBuf.join(''); } function stringToUTF8String(str) { return decodeURIComponent(escape(str)); } function utf8StringToString(str) { return unescape(encodeURIComponent(str)); } function isEmptyObj(obj) { for (var key in obj) { return false; } return true; } function isBool(v) { return typeof v === 'boolean'; } function isInt(v) { return typeof v === 'number' && ((v | 0) === v); } function isNum(v) { return typeof v === 'number'; } function isString(v) { return typeof v === 'string'; } function isName(v) { return v instanceof Name; } function isCmd(v, cmd) { return v instanceof Cmd && (cmd === undefined || v.cmd === cmd); } function isDict(v, type) { if (!(v instanceof Dict)) { return false; } if (!type) { return true; } var dictType = v.get('Type'); return isName(dictType) && dictType.name === type; } function isArray(v) { return v instanceof Array; } function isStream(v) { return typeof v === 'object' && v !== null && v.getBytes !== undefined; } function isArrayBuffer(v) { return typeof v === 'object' && v !== null && v.byteLength !== undefined; } function isRef(v) { return v instanceof Ref; } /** * Promise Capability object. * * @typedef {Object} PromiseCapability * @property {Promise} promise - A promise object. * @property {function} resolve - Fullfills the promise. * @property {function} reject - Rejects the promise. */ /** * Creates a promise capability object. * @alias PDFJS.createPromiseCapability * * @return {PromiseCapability} A capability object contains: * - a Promise, resolve and reject methods. */ function createPromiseCapability() { var capability = {}; capability.promise = new Promise(function (resolve, reject) { capability.resolve = resolve; capability.reject = reject; }); return capability; } PDFJS.createPromiseCapability = createPromiseCapability; /** * Polyfill for Promises: * The following promise implementation tries to generally implement the * Promise/A+ spec. Some notable differences from other promise libaries are: * - There currently isn't a seperate deferred and promise object. * - Unhandled rejections eventually show an error if they aren't handled. * * Based off of the work in: * https://bugzilla.mozilla.org/show_bug.cgi?id=810490 */ (function PromiseClosure() { if (globalScope.Promise) { // Promises existing in the DOM/Worker, checking presence of all/resolve if (typeof globalScope.Promise.all !== 'function') { globalScope.Promise.all = function (iterable) { var count = 0, results = [], resolve, reject; var promise = new globalScope.Promise(function (resolve_, reject_) { resolve = resolve_; reject = reject_; }); iterable.forEach(function (p, i) { count++; p.then(function (result) { results[i] = result; count--; if (count === 0) { resolve(results); } }, reject); }); if (count === 0) { resolve(results); } return promise; }; } if (typeof globalScope.Promise.resolve !== 'function') { globalScope.Promise.resolve = function (value) { return new globalScope.Promise(function (resolve) { resolve(value); }); }; } if (typeof globalScope.Promise.reject !== 'function') { globalScope.Promise.reject = function (reason) { return new globalScope.Promise(function (resolve, reject) { reject(reason); }); }; } if (typeof globalScope.Promise.prototype.catch !== 'function') { globalScope.Promise.prototype.catch = function (onReject) { return globalScope.Promise.prototype.then(undefined, onReject); }; } return; } var STATUS_PENDING = 0; var STATUS_RESOLVED = 1; var STATUS_REJECTED = 2; // In an attempt to avoid silent exceptions, unhandled rejections are // tracked and if they aren't handled in a certain amount of time an // error is logged. var REJECTION_TIMEOUT = 500; var HandlerManager = { handlers: [], running: false, unhandledRejections: [], pendingRejectionCheck: false, scheduleHandlers: function scheduleHandlers(promise) { if (promise._status === STATUS_PENDING) { return; } this.handlers = this.handlers.concat(promise._handlers); promise._handlers = []; if (this.running) { return; } this.running = true; setTimeout(this.runHandlers.bind(this), 0); }, runHandlers: function runHandlers() { var RUN_TIMEOUT = 1; // ms var timeoutAt = Date.now() + RUN_TIMEOUT; while (this.handlers.length > 0) { var handler = this.handlers.shift(); var nextStatus = handler.thisPromise._status; var nextValue = handler.thisPromise._value; try { if (nextStatus === STATUS_RESOLVED) { if (typeof handler.onResolve === 'function') { nextValue = handler.onResolve(nextValue); } } else if (typeof handler.onReject === 'function') { nextValue = handler.onReject(nextValue); nextStatus = STATUS_RESOLVED; if (handler.thisPromise._unhandledRejection) { this.removeUnhandeledRejection(handler.thisPromise); } } } catch (ex) { nextStatus = STATUS_REJECTED; nextValue = ex; } handler.nextPromise._updateStatus(nextStatus, nextValue); if (Date.now() >= timeoutAt) { break; } } if (this.handlers.length > 0) { setTimeout(this.runHandlers.bind(this), 0); return; } this.running = false; }, addUnhandledRejection: function addUnhandledRejection(promise) { this.unhandledRejections.push({ promise: promise, time: Date.now() }); this.scheduleRejectionCheck(); }, removeUnhandeledRejection: function removeUnhandeledRejection(promise) { promise._unhandledRejection = false; for (var i = 0; i < this.unhandledRejections.length; i++) { if (this.unhandledRejections[i].promise === promise) { this.unhandledRejections.splice(i); i--; } } }, scheduleRejectionCheck: function scheduleRejectionCheck() { if (this.pendingRejectionCheck) { return; } this.pendingRejectionCheck = true; setTimeout(function rejectionCheck() { this.pendingRejectionCheck = false; var now = Date.now(); for (var i = 0; i < this.unhandledRejections.length; i++) { if (now - this.unhandledRejections[i].time > REJECTION_TIMEOUT) { var unhandled = this.unhandledRejections[i].promise._value; var msg = 'Unhandled rejection: ' + unhandled; if (unhandled.stack) { msg += '\n' + unhandled.stack; } warn(msg); this.unhandledRejections.splice(i); i--; } } if (this.unhandledRejections.length) { this.scheduleRejectionCheck(); } }.bind(this), REJECTION_TIMEOUT); } }; function Promise(resolver) { this._status = STATUS_PENDING; this._handlers = []; try { resolver.call(this, this._resolve.bind(this), this._reject.bind(this)); } catch (e) { this._reject(e); } } /** * Builds a promise that is resolved when all the passed in promises are * resolved. * @param {array} array of data and/or promises to wait for. * @return {Promise} New dependant promise. */ Promise.all = function Promise_all(promises) { var resolveAll, rejectAll; var deferred = new Promise(function (resolve, reject) { resolveAll = resolve; rejectAll = reject; }); var unresolved = promises.length; var results = []; if (unresolved === 0) { resolveAll(results); return deferred; } function reject(reason) { if (deferred._status === STATUS_REJECTED) { return; } results = []; rejectAll(reason); } for (var i = 0, ii = promises.length; i < ii; ++i) { var promise = promises[i]; var resolve = (function(i) { return function(value) { if (deferred._status === STATUS_REJECTED) { return; } results[i] = value; unresolved--; if (unresolved === 0) { resolveAll(results); } }; })(i); if (Promise.isPromise(promise)) { promise.then(resolve, reject); } else { resolve(promise); } } return deferred; }; /** * Checks if the value is likely a promise (has a 'then' function). * @return {boolean} true if value is thenable */ Promise.isPromise = function Promise_isPromise(value) { return value && typeof value.then === 'function'; }; /** * Creates resolved promise * @param value resolve value * @returns {Promise} */ Promise.resolve = function Promise_resolve(value) { return new Promise(function (resolve) { resolve(value); }); }; /** * Creates rejected promise * @param reason rejection value * @returns {Promise} */ Promise.reject = function Promise_reject(reason) { return new Promise(function (resolve, reject) { reject(reason); }); }; Promise.prototype = { _status: null, _value: null, _handlers: null, _unhandledRejection: null, _updateStatus: function Promise__updateStatus(status, value) { if (this._status === STATUS_RESOLVED || this._status === STATUS_REJECTED) { return; } if (status === STATUS_RESOLVED && Promise.isPromise(value)) { value.then(this._updateStatus.bind(this, STATUS_RESOLVED), this._updateStatus.bind(this, STATUS_REJECTED)); return; } this._status = status; this._value = value; if (status === STATUS_REJECTED && this._handlers.length === 0) { this._unhandledRejection = true; HandlerManager.addUnhandledRejection(this); } HandlerManager.scheduleHandlers(this); }, _resolve: function Promise_resolve(value) { this._updateStatus(STATUS_RESOLVED, value); }, _reject: function Promise_reject(reason) { this._updateStatus(STATUS_REJECTED, reason); }, then: function Promise_then(onResolve, onReject) { var nextPromise = new Promise(function (resolve, reject) { this.resolve = resolve; this.reject = reject; }); this._handlers.push({ thisPromise: this, onResolve: onResolve, onReject: onReject, nextPromise: nextPromise }); HandlerManager.scheduleHandlers(this); return nextPromise; }, catch: function Promise_catch(onReject) { return this.then(undefined, onReject); } }; globalScope.Promise = Promise; })(); var StatTimer = (function StatTimerClosure() { function rpad(str, pad, length) { while (str.length < length) { str += pad; } return str; } function StatTimer() { this.started = {}; this.times = []; this.enabled = true; } StatTimer.prototype = { time: function StatTimer_time(name) { if (!this.enabled) { return; } if (name in this.started) { warn('Timer is already running for ' + name); } this.started[name] = Date.now(); }, timeEnd: function StatTimer_timeEnd(name) { if (!this.enabled) { return; } if (!(name in this.started)) { warn('Timer has not been started for ' + name); } this.times.push({ 'name': name, 'start': this.started[name], 'end': Date.now() }); // Remove timer from started so it can be called again. delete this.started[name]; }, toString: function StatTimer_toString() { var i, ii; var times = this.times; var out = ''; // Find the longest name for padding purposes. var longest = 0; for (i = 0, ii = times.length; i < ii; ++i) { var name = times[i]['name']; if (name.length > longest) { longest = name.length; } } for (i = 0, ii = times.length; i < ii; ++i) { var span = times[i]; var duration = span.end - span.start; out += rpad(span['name'], ' ', longest) + ' ' + duration + 'ms\n'; } return out; } }; return StatTimer; })(); PDFJS.createBlob = function createBlob(data, contentType) { if (typeof Blob !== 'undefined') { return new Blob([data], { type: contentType }); } // Blob builder is deprecated in FF14 and removed in FF18. var bb = new MozBlobBuilder(); bb.append(data); return bb.getBlob(contentType); }; PDFJS.createObjectURL = (function createObjectURLClosure() { // Blob/createObjectURL is not available, falling back to data schema. var digits = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; return function createObjectURL(data, contentType) { if (!PDFJS.disableCreateObjectURL && typeof URL !== 'undefined' && URL.createObjectURL) { var blob = PDFJS.createBlob(data, contentType); return URL.createObjectURL(blob); } var buffer = 'data:' + contentType + ';base64,'; for (var i = 0, ii = data.length; i < ii; i += 3) { var b1 = data[i] & 0xFF; var b2 = data[i + 1] & 0xFF; var b3 = data[i + 2] & 0xFF; var d1 = b1 >> 2, d2 = ((b1 & 3) << 4) | (b2 >> 4); var d3 = i + 1 < ii ? ((b2 & 0xF) << 2) | (b3 >> 6) : 64; var d4 = i + 2 < ii ? (b3 & 0x3F) : 64; buffer += digits[d1] + digits[d2] + digits[d3] + digits[d4]; } return buffer; }; })(); function MessageHandler(sourceName, targetName, comObj) { this.sourceName = sourceName; this.targetName = targetName; this.comObj = comObj; this.callbackIndex = 1; this.postMessageTransfers = true; var callbacksCapabilities = this.callbacksCapabilities = {}; var ah = this.actionHandler = {}; this._onComObjOnMessage = function messageHandlerComObjOnMessage(event) { var data = event.data; if (data.targetName !== this.sourceName) { return; } if (data.isReply) { var callbackId = data.callbackId; if (data.callbackId in callbacksCapabilities) { var callback = callbacksCapabilities[callbackId]; delete callbacksCapabilities[callbackId]; if ('error' in data) { callback.reject(data.error); } else { callback.resolve(data.data); } } else { error('Cannot resolve callback ' + callbackId); } } else if (data.action in ah) { var action = ah[data.action]; if (data.callbackId) { var sourceName = this.sourceName; var targetName = data.sourceName; Promise.resolve().then(function () { return action[0].call(action[1], data.data); }).then(function (result) { comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, data: result }); }, function (reason) { if (reason instanceof Error) { // Serialize error to avoid "DataCloneError" reason = reason + ''; } comObj.postMessage({ sourceName: sourceName, targetName: targetName, isReply: true, callbackId: data.callbackId, error: reason }); }); } else { action[0].call(action[1], data.data); } } else { error('Unknown action from worker: ' + data.action); } }.bind(this); comObj.addEventListener('message', this._onComObjOnMessage); } MessageHandler.prototype = { on: function messageHandlerOn(actionName, handler, scope) { var ah = this.actionHandler; if (ah[actionName]) { error('There is already an actionName called "' + actionName + '"'); } ah[actionName] = [handler, scope]; }, /** * Sends a message to the comObj to invoke the action with the supplied data. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers */ send: function messageHandlerSend(actionName, data, transfers) { var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data }; this.postMessage(message, transfers); }, /** * Sends a message to the comObj to invoke the action with the supplied data. * Expects that other side will callback with the response. * @param {String} actionName Action to call. * @param {JSON} data JSON data to send. * @param {Array} [transfers] Optional list of transfers/ArrayBuffers. * @returns {Promise} Promise to be resolved with response data. */ sendWithPromise: function messageHandlerSendWithPromise(actionName, data, transfers) { var callbackId = this.callbackIndex++; var message = { sourceName: this.sourceName, targetName: this.targetName, action: actionName, data: data, callbackId: callbackId }; var capability = createPromiseCapability(); this.callbacksCapabilities[callbackId] = capability; try { this.postMessage(message, transfers); } catch (e) { capability.reject(e); } return capability.promise; }, /** * Sends raw message to the comObj. * @private * @param message {Object} Raw message. * @param transfers List of transfers/ArrayBuffers, or undefined. */ postMessage: function (message, transfers) { if (transfers && this.postMessageTransfers) { this.comObj.postMessage(message, transfers); } else { this.comObj.postMessage(message); } }, destroy: function () { this.comObj.removeEventListener('message', this._onComObjOnMessage); } }; function loadJpegStream(id, imageUrl, objs) { var img = new Image(); img.onload = (function loadJpegStream_onloadClosure() { objs.resolve(id, img); }); img.onerror = (function loadJpegStream_onerrorClosure() { objs.resolve(id, null); warn('Error during JPEG image loading'); }); img.src = imageUrl; } // Polyfill from https://github.com/Polymer/URL /* Any copyright is dedicated to the Public Domain. * http://creativecommons.org/publicdomain/zero/1.0/ */ (function checkURLConstructor(scope) { /* jshint ignore:start */ // feature detect for URL constructor var hasWorkingUrl = false; if (typeof URL === 'function' && ('origin' in URL.prototype)) { try { var u = new URL('b', 'http://a'); u.pathname = 'c%20d'; hasWorkingUrl = u.href === 'http://a/c%20d'; } catch(e) {} } if (hasWorkingUrl) return; var relative = Object.create(null); relative['ftp'] = 21; relative['file'] = 0; relative['gopher'] = 70; relative['http'] = 80; relative['https'] = 443; relative['ws'] = 80; relative['wss'] = 443; var relativePathDotMapping = Object.create(null); relativePathDotMapping['%2e'] = '.'; relativePathDotMapping['.%2e'] = '..'; relativePathDotMapping['%2e.'] = '..'; relativePathDotMapping['%2e%2e'] = '..'; function isRelativeScheme(scheme) { return relative[scheme] !== undefined; } function invalid() { clear.call(this); this._isInvalid = true; } function IDNAToASCII(h) { if ('' == h) { invalid.call(this) } // XXX return h.toLowerCase() } function percentEscape(c) { var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ? ` [0x22, 0x23, 0x3C, 0x3E, 0x3F, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } function percentEscapeQuery(c) { // XXX This actually needs to encode c using encoding and then // convert the bytes one-by-one. var unicode = c.charCodeAt(0); if (unicode > 0x20 && unicode < 0x7F && // " # < > ` (do not escape '?') [0x22, 0x23, 0x3C, 0x3E, 0x60].indexOf(unicode) == -1 ) { return c; } return encodeURIComponent(c); } var EOF = undefined, ALPHA = /[a-zA-Z]/, ALPHANUMERIC = /[a-zA-Z0-9\+\-\.]/; function parse(input, stateOverride, base) { function err(message) { errors.push(message) } var state = stateOverride || 'scheme start', cursor = 0, buffer = '', seenAt = false, seenBracket = false, errors = []; loop: while ((input[cursor - 1] != EOF || cursor == 0) && !this._isInvalid) { var c = input[cursor]; switch (state) { case 'scheme start': if (c && ALPHA.test(c)) { buffer += c.toLowerCase(); // ASCII-safe state = 'scheme'; } else if (!stateOverride) { buffer = ''; state = 'no scheme'; continue; } else { err('Invalid scheme.'); break loop; } break; case 'scheme': if (c && ALPHANUMERIC.test(c)) { buffer += c.toLowerCase(); // ASCII-safe } else if (':' == c) { this._scheme = buffer; buffer = ''; if (stateOverride) { break loop; } if (isRelativeScheme(this._scheme)) { this._isRelative = true; } if ('file' == this._scheme) { state = 'relative'; } else if (this._isRelative && base && base._scheme == this._scheme) { state = 'relative or authority'; } else if (this._isRelative) { state = 'authority first slash'; } else { state = 'scheme data'; } } else if (!stateOverride) { buffer = ''; cursor = 0; state = 'no scheme'; continue; } else if (EOF == c) { break loop; } else { err('Code point not allowed in scheme: ' + c) break loop; } break; case 'scheme data': if ('?' == c) { this._query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } else { // XXX error handling if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._schemeData += percentEscape(c); } } break; case 'no scheme': if (!base || !(isRelativeScheme(base._scheme))) { err('Missing scheme.'); invalid.call(this); } else { state = 'relative'; continue; } break; case 'relative or authority': if ('/' == c && '/' == input[cursor+1]) { state = 'authority ignore slashes'; } else { err('Expected /, got: ' + c); state = 'relative'; continue } break; case 'relative': this._isRelative = true; if ('file' != this._scheme) this._scheme = base._scheme; if (EOF == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._username = base._username; this._password = base._password; break loop; } else if ('/' == c || '\\' == c) { if ('\\' == c) err('\\ is an invalid code point.'); state = 'relative slash'; } else if ('?' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = '?'; this._username = base._username; this._password = base._password; state = 'query'; } else if ('#' == c) { this._host = base._host; this._port = base._port; this._path = base._path.slice(); this._query = base._query; this._fragment = '#'; this._username = base._username; this._password = base._password; state = 'fragment'; } else { var nextC = input[cursor+1] var nextNextC = input[cursor+2] if ( 'file' != this._scheme || !ALPHA.test(c) || (nextC != ':' && nextC != '|') || (EOF != nextNextC && '/' != nextNextC && '\\' != nextNextC && '?' != nextNextC && '#' != nextNextC)) { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; this._path = base._path.slice(); this._path.pop(); } state = 'relative path'; continue; } break; case 'relative slash': if ('/' == c || '\\' == c) { if ('\\' == c) { err('\\ is an invalid code point.'); } if ('file' == this._scheme) { state = 'file host'; } else { state = 'authority ignore slashes'; } } else { if ('file' != this._scheme) { this._host = base._host; this._port = base._port; this._username = base._username; this._password = base._password; } state = 'relative path'; continue; } break; case 'authority first slash': if ('/' == c) { state = 'authority second slash'; } else { err("Expected '/', got: " + c); state = 'authority ignore slashes'; continue; } break; case 'authority second slash': state = 'authority ignore slashes'; if ('/' != c) { err("Expected '/', got: " + c); continue; } break; case 'authority ignore slashes': if ('/' != c && '\\' != c) { state = 'authority'; continue; } else { err('Expected authority, got: ' + c); } break; case 'authority': if ('@' == c) { if (seenAt) { err('@ already seen.'); buffer += '%40'; } seenAt = true; for (var i = 0; i < buffer.length; i++) { var cp = buffer[i]; if ('\t' == cp || '\n' == cp || '\r' == cp) { err('Invalid whitespace in authority.'); continue; } // XXX check URL code points if (':' == cp && null === this._password) { this._password = ''; continue; } var tempC = percentEscape(cp); (null !== this._password) ? this._password += tempC : this._username += tempC; } buffer = ''; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { cursor -= buffer.length; buffer = ''; state = 'host'; continue; } else { buffer += c; } break; case 'file host': if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { if (buffer.length == 2 && ALPHA.test(buffer[0]) && (buffer[1] == ':' || buffer[1] == '|')) { state = 'relative path'; } else if (buffer.length == 0) { state = 'relative path start'; } else { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; } continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid whitespace in file host.'); } else { buffer += c; } break; case 'host': case 'hostname': if (':' == c && !seenBracket) { // XXX host parsing this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'port'; if ('hostname' == stateOverride) { break loop; } } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c) { this._host = IDNAToASCII.call(this, buffer); buffer = ''; state = 'relative path start'; if (stateOverride) { break loop; } continue; } else if ('\t' != c && '\n' != c && '\r' != c) { if ('[' == c) { seenBracket = true; } else if (']' == c) { seenBracket = false; } buffer += c; } else { err('Invalid code point in host/hostname: ' + c); } break; case 'port': if (/[0-9]/.test(c)) { buffer += c; } else if (EOF == c || '/' == c || '\\' == c || '?' == c || '#' == c || stateOverride) { if ('' != buffer) { var temp = parseInt(buffer, 10); if (temp != relative[this._scheme]) { this._port = temp + ''; } buffer = ''; } if (stateOverride) { break loop; } state = 'relative path start'; continue; } else if ('\t' == c || '\n' == c || '\r' == c) { err('Invalid code point in port: ' + c); } else { invalid.call(this); } break; case 'relative path start': if ('\\' == c) err("'\\' not allowed in path."); state = 'relative path'; if ('/' != c && '\\' != c) { continue; } break; case 'relative path': if (EOF == c || '/' == c || '\\' == c || (!stateOverride && ('?' == c || '#' == c))) { if ('\\' == c) { err('\\ not allowed in relative path.'); } var tmp; if (tmp = relativePathDotMapping[buffer.toLowerCase()]) { buffer = tmp; } if ('..' == buffer) { this._path.pop(); if ('/' != c && '\\' != c) { this._path.push(''); } } else if ('.' == buffer && '/' != c && '\\' != c) { this._path.push(''); } else if ('.' != buffer) { if ('file' == this._scheme && this._path.length == 0 && buffer.length == 2 && ALPHA.test(buffer[0]) && buffer[1] == '|') { buffer = buffer[0] + ':'; } this._path.push(buffer); } buffer = ''; if ('?' == c) { this._query = '?'; state = 'query'; } else if ('#' == c) { this._fragment = '#'; state = 'fragment'; } } else if ('\t' != c && '\n' != c && '\r' != c) { buffer += percentEscape(c); } break; case 'query': if (!stateOverride && '#' == c) { this._fragment = '#'; state = 'fragment'; } else if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._query += percentEscapeQuery(c); } break; case 'fragment': if (EOF != c && '\t' != c && '\n' != c && '\r' != c) { this._fragment += c; } break; } cursor++; } } function clear() { this._scheme = ''; this._schemeData = ''; this._username = ''; this._password = null; this._host = ''; this._port = ''; this._path = []; this._query = ''; this._fragment = ''; this._isInvalid = false; this._isRelative = false; } // Does not process domain names or IP addresses. // Does not handle encoding for the query parameter. function jURL(url, base /* , encoding */) { if (base !== undefined && !(base instanceof jURL)) base = new jURL(String(base)); this._url = url; clear.call(this); var input = url.replace(/^[ \t\r\n\f]+|[ \t\r\n\f]+$/g, ''); // encoding = encoding || 'utf-8' parse.call(this, input, null, base); } jURL.prototype = { toString: function() { return this.href; }, get href() { if (this._isInvalid) return this._url; var authority = ''; if ('' != this._username || null != this._password) { authority = this._username + (null != this._password ? ':' + this._password : '') + '@'; } return this.protocol + (this._isRelative ? '//' + authority + this.host : '') + this.pathname + this._query + this._fragment; }, set href(href) { clear.call(this); parse.call(this, href); }, get protocol() { return this._scheme + ':'; }, set protocol(protocol) { if (this._isInvalid) return; parse.call(this, protocol + ':', 'scheme start'); }, get host() { return this._isInvalid ? '' : this._port ? this._host + ':' + this._port : this._host; }, set host(host) { if (this._isInvalid || !this._isRelative) return; parse.call(this, host, 'host'); }, get hostname() { return this._host; }, set hostname(hostname) { if (this._isInvalid || !this._isRelative) return; parse.call(this, hostname, 'hostname'); }, get port() { return this._port; }, set port(port) { if (this._isInvalid || !this._isRelative) return; parse.call(this, port, 'port'); }, get pathname() { return this._isInvalid ? '' : this._isRelative ? '/' + this._path.join('/') : this._schemeData; }, set pathname(pathname) { if (this._isInvalid || !this._isRelative) return; this._path = []; parse.call(this, pathname, 'relative path start'); }, get search() { return this._isInvalid || !this._query || '?' == this._query ? '' : this._query; }, set search(search) { if (this._isInvalid || !this._isRelative) return; this._query = '?'; if ('?' == search[0]) search = search.slice(1); parse.call(this, search, 'query'); }, get hash() { return this._isInvalid || !this._fragment || '#' == this._fragment ? '' : this._fragment; }, set hash(hash) { if (this._isInvalid) return; this._fragment = '#'; if ('#' == hash[0]) hash = hash.slice(1); parse.call(this, hash, 'fragment'); }, get origin() { var host; if (this._isInvalid || !this._scheme) { return ''; } // javascript: Gecko returns String(""), WebKit/Blink String("null") // Gecko throws error for "data://" // data: Gecko returns "", Blink returns "data://", WebKit returns "null" // Gecko returns String("") for file: mailto: // WebKit/Blink returns String("SCHEME://") for file: mailto: switch (this._scheme) { case 'data': case 'file': case 'javascript': case 'mailto': return 'null'; } host = this.host; if (!host) { return ''; } return this._scheme + '://' + host; } }; // Copy over the static methods var OriginalURL = scope.URL; if (OriginalURL) { jURL.createObjectURL = function(blob) { // IE extension allows a second optional options argument. // http://msdn.microsoft.com/en-us/library/ie/hh772302(v=vs.85).aspx return OriginalURL.createObjectURL.apply(OriginalURL, arguments); }; jURL.revokeObjectURL = function(url) { OriginalURL.revokeObjectURL(url); }; } scope.URL = jURL; /* jshint ignore:end */ })(globalScope); var DEFAULT_RANGE_CHUNK_SIZE = 65536; // 2^16 = 65536 /** * The maximum allowed image size in total pixels e.g. width * height. Images * above this value will not be drawn. Use -1 for no limit. * @var {number} */ PDFJS.maxImageSize = (PDFJS.maxImageSize === undefined ? -1 : PDFJS.maxImageSize); /** * The url of where the predefined Adobe CMaps are located. Include trailing * slash. * @var {string} */ PDFJS.cMapUrl = (PDFJS.cMapUrl === undefined ? null : PDFJS.cMapUrl); /** * Specifies if CMaps are binary packed. * @var {boolean} */ PDFJS.cMapPacked = PDFJS.cMapPacked === undefined ? false : PDFJS.cMapPacked; /** * By default fonts are converted to OpenType fonts and loaded via font face * rules. If disabled, the font will be rendered using a built in font renderer * that constructs the glyphs with primitive path commands. * @var {boolean} */ PDFJS.disableFontFace = (PDFJS.disableFontFace === undefined ? false : PDFJS.disableFontFace); /** * Path for image resources, mainly for annotation icons. Include trailing * slash. * @var {string} */ PDFJS.imageResourcesPath = (PDFJS.imageResourcesPath === undefined ? '' : PDFJS.imageResourcesPath); /** * Disable the web worker and run all code on the main thread. This will happen * automatically if the browser doesn't support workers or sending typed arrays * to workers. * @var {boolean} */ PDFJS.disableWorker = (PDFJS.disableWorker === undefined ? false : PDFJS.disableWorker); /** * Path and filename of the worker file. Required when the worker is enabled in * development mode. If unspecified in the production build, the worker will be * loaded based on the location of the pdf.js file. It is recommended that * the workerSrc is set in a custom application to prevent issues caused by * third-party frameworks and libraries. * @var {string} */ PDFJS.workerSrc = (PDFJS.workerSrc === undefined ? null : PDFJS.workerSrc); /** * Disable range request loading of PDF files. When enabled and if the server * supports partial content requests then the PDF will be fetched in chunks. * Enabled (false) by default. * @var {boolean} */ PDFJS.disableRange = (PDFJS.disableRange === undefined ? false : PDFJS.disableRange); /** * Disable streaming of PDF file data. By default PDF.js attempts to load PDF * in chunks. This default behavior can be disabled. * @var {boolean} */ PDFJS.disableStream = (PDFJS.disableStream === undefined ? false : PDFJS.disableStream); /** * Disable pre-fetching of PDF file data. When range requests are enabled PDF.js * will automatically keep fetching more data even if it isn't needed to display * the current page. This default behavior can be disabled. * * NOTE: It is also necessary to disable streaming, see above, * in order for disabling of pre-fetching to work correctly. * @var {boolean} */ PDFJS.disableAutoFetch = (PDFJS.disableAutoFetch === undefined ? false : PDFJS.disableAutoFetch); /** * Enables special hooks for debugging PDF.js. * @var {boolean} */ PDFJS.pdfBug = (PDFJS.pdfBug === undefined ? false : PDFJS.pdfBug); /** * Enables transfer usage in postMessage for ArrayBuffers. * @var {boolean} */ PDFJS.postMessageTransfers = (PDFJS.postMessageTransfers === undefined ? true : PDFJS.postMessageTransfers); /** * Disables URL.createObjectURL usage. * @var {boolean} */ PDFJS.disableCreateObjectURL = (PDFJS.disableCreateObjectURL === undefined ? false : PDFJS.disableCreateObjectURL); /** * Disables WebGL usage. * @var {boolean} */ PDFJS.disableWebGL = (PDFJS.disableWebGL === undefined ? true : PDFJS.disableWebGL); /** * Disables fullscreen support, and by extension Presentation Mode, * in browsers which support the fullscreen API. * @var {boolean} */ PDFJS.disableFullscreen = (PDFJS.disableFullscreen === undefined ? false : PDFJS.disableFullscreen); /** * Enables CSS only zooming. * @var {boolean} */ PDFJS.useOnlyCssZoom = (PDFJS.useOnlyCssZoom === undefined ? false : PDFJS.useOnlyCssZoom); /** * Controls the logging level. * The constants from PDFJS.VERBOSITY_LEVELS should be used: * - errors * - warnings [default] * - infos * @var {number} */ PDFJS.verbosity = (PDFJS.verbosity === undefined ? PDFJS.VERBOSITY_LEVELS.warnings : PDFJS.verbosity); /** * The maximum supported canvas size in total pixels e.g. width * height. * The default value is 4096 * 4096. Use -1 for no limit. * @var {number} */ PDFJS.maxCanvasPixels = (PDFJS.maxCanvasPixels === undefined ? 16777216 : PDFJS.maxCanvasPixels); /** * (Deprecated) Opens external links in a new window if enabled. * The default behavior opens external links in the PDF.js window. * * NOTE: This property has been deprecated, please use * `PDFJS.externalLinkTarget = PDFJS.LinkTarget.BLANK` instead. * @var {boolean} */ PDFJS.openExternalLinksInNewWindow = ( PDFJS.openExternalLinksInNewWindow === undefined ? false : PDFJS.openExternalLinksInNewWindow); /** * Specifies the |target| attribute for external links. * The constants from PDFJS.LinkTarget should be used: * - NONE [default] * - SELF * - BLANK * - PARENT * - TOP * @var {number} */ PDFJS.externalLinkTarget = (PDFJS.externalLinkTarget === undefined ? PDFJS.LinkTarget.NONE : PDFJS.externalLinkTarget); /** * Determines if we can eval strings as JS. Primarily used to improve * performance for font rendering. * @var {boolean} */ PDFJS.isEvalSupported = (PDFJS.isEvalSupported === undefined ? true : PDFJS.isEvalSupported); /** * Document initialization / loading parameters object. * * @typedef {Object} DocumentInitParameters * @property {string} url - The URL of the PDF. * @property {TypedArray|Array|string} data - Binary PDF data. Use typed arrays * (Uint8Array) to improve the memory usage. If PDF data is BASE64-encoded, * use atob() to convert it to a binary string first. * @property {Object} httpHeaders - Basic authentication headers. * @property {boolean} withCredentials - Indicates whether or not cross-site * Access-Control requests should be made using credentials such as cookies * or authorization headers. The default is false. * @property {string} password - For decrypting password-protected PDFs. * @property {TypedArray} initialData - A typed array with the first portion or * all of the pdf data. Used by the extension since some data is already * loaded before the switch to range requests. * @property {number} length - The PDF file length. It's used for progress * reports and range requests operations. * @property {PDFDataRangeTransport} range * @property {number} rangeChunkSize - Optional parameter to specify * maximum number of bytes fetched per range request. The default value is * 2^16 = 65536. * @property {PDFWorker} worker - The worker that will be used for the loading * and parsing of the PDF data. */ /** * @typedef {Object} PDFDocumentStats * @property {Array} streamTypes - Used stream types in the document (an item * is set to true if specific stream ID was used in the document). * @property {Array} fontTypes - Used font type in the document (an item is set * to true if specific font ID was used in the document). */ /** * This is the main entry point for loading a PDF and interacting with it. * NOTE: If a URL is used to fetch the PDF data a standard XMLHttpRequest(XHR) * is used, which means it must follow the same origin rules that any XHR does * e.g. No cross domain requests without CORS. * * @param {string|TypedArray|DocumentInitParameters|PDFDataRangeTransport} src * Can be a url to where a PDF is located, a typed array (Uint8Array) * already populated with data or parameter object. * * @param {PDFDataRangeTransport} pdfDataRangeTransport (deprecated) It is used * if you want to manually serve range requests for data in the PDF. * * @param {function} passwordCallback (deprecated) It is used to request a * password if wrong or no password was provided. The callback receives two * parameters: function that needs to be called with new password and reason * (see {PasswordResponses}). * * @param {function} progressCallback (deprecated) It is used to be able to * monitor the loading progress of the PDF file (necessary to implement e.g. * a loading bar). The callback receives an {Object} with the properties: * {number} loaded and {number} total. * * @return {PDFDocumentLoadingTask} */ PDFJS.getDocument = function getDocument(src, pdfDataRangeTransport, passwordCallback, progressCallback) { var task = new PDFDocumentLoadingTask(); // Support of the obsolete arguments (for compatibility with API v1.0) if (arguments.length > 1) { deprecated('getDocument is called with pdfDataRangeTransport, ' + 'passwordCallback or progressCallback argument'); } if (pdfDataRangeTransport) { if (!(pdfDataRangeTransport instanceof PDFDataRangeTransport)) { // Not a PDFDataRangeTransport instance, trying to add missing properties. pdfDataRangeTransport = Object.create(pdfDataRangeTransport); pdfDataRangeTransport.length = src.length; pdfDataRangeTransport.initialData = src.initialData; if (!pdfDataRangeTransport.abort) { pdfDataRangeTransport.abort = function () {}; } } src = Object.create(src); src.range = pdfDataRangeTransport; } task.onPassword = passwordCallback || null; task.onProgress = progressCallback || null; var source; if (typeof src === 'string') { source = { url: src }; } else if (isArrayBuffer(src)) { source = { data: src }; } else if (src instanceof PDFDataRangeTransport) { source = { range: src }; } else { if (typeof src !== 'object') { error('Invalid parameter in getDocument, need either Uint8Array, ' + 'string or a parameter object'); } if (!src.url && !src.data && !src.range) { error('Invalid parameter object: need either .data, .range or .url'); } source = src; } var params = {}; var rangeTransport = null; var worker = null; for (var key in source) { if (key === 'url' && typeof window !== 'undefined') { // The full path is required in the 'url' field. params[key] = combineUrl(window.location.href, source[key]); continue; } else if (key === 'range') { rangeTransport = source[key]; continue; } else if (key === 'worker') { worker = source[key]; continue; } else if (key === 'data' && !(source[key] instanceof Uint8Array)) { // Converting string or array-like data to Uint8Array. var pdfBytes = source[key]; if (typeof pdfBytes === 'string') { params[key] = stringToBytes(pdfBytes); } else if (typeof pdfBytes === 'object' && pdfBytes !== null && !isNaN(pdfBytes.length)) { params[key] = new Uint8Array(pdfBytes); } else if (isArrayBuffer(pdfBytes)) { params[key] = new Uint8Array(pdfBytes); } else { error('Invalid PDF binary data: either typed array, string or ' + 'array-like object is expected in the data property.'); } continue; } params[key] = source[key]; } params.rangeChunkSize = params.rangeChunkSize || DEFAULT_RANGE_CHUNK_SIZE; if (!worker) { // Worker was not provided -- creating and owning our own. worker = new PDFWorker(); task._worker = worker; } var docId = task.docId; worker.promise.then(function () { if (task.destroyed) { throw new Error('Loading aborted'); } return _fetchDocument(worker, params, rangeTransport, docId).then( function (workerId) { if (task.destroyed) { throw new Error('Loading aborted'); } var messageHandler = new MessageHandler(docId, workerId, worker.port); messageHandler.send('Ready', null); var transport = new WorkerTransport(messageHandler, task, rangeTransport); task._transport = transport; }); }, task._capability.reject); return task; }; /** * Starts fetching of specified PDF document/data. * @param {PDFWorker} worker * @param {Object} source * @param {PDFDataRangeTransport} pdfDataRangeTransport * @param {string} docId Unique document id, used as MessageHandler id. * @returns {Promise} The promise, which is resolved when worker id of * MessageHandler is known. * @private */ function _fetchDocument(worker, source, pdfDataRangeTransport, docId) { if (worker.destroyed) { return Promise.reject(new Error('Worker was destroyed')); } source.disableAutoFetch = PDFJS.disableAutoFetch; source.disableStream = PDFJS.disableStream; source.chunkedViewerLoading = !!pdfDataRangeTransport; if (pdfDataRangeTransport) { source.length = pdfDataRangeTransport.length; source.initialData = pdfDataRangeTransport.initialData; } return worker.messageHandler.sendWithPromise('GetDocRequest', { docId: docId, source: source, disableRange: PDFJS.disableRange, maxImageSize: PDFJS.maxImageSize, cMapUrl: PDFJS.cMapUrl, cMapPacked: PDFJS.cMapPacked, disableFontFace: PDFJS.disableFontFace, disableCreateObjectURL: PDFJS.disableCreateObjectURL, verbosity: PDFJS.verbosity }).then(function (workerId) { if (worker.destroyed) { throw new Error('Worker was destroyed'); } return workerId; }); } /** * PDF document loading operation. * @class * @alias PDFDocumentLoadingTask */ var PDFDocumentLoadingTask = (function PDFDocumentLoadingTaskClosure() { var nextDocumentId = 0; /** @constructs PDFDocumentLoadingTask */ function PDFDocumentLoadingTask() { this._capability = createPromiseCapability(); this._transport = null; this._worker = null; /** * Unique document loading task id -- used in MessageHandlers. * @type {string} */ this.docId = 'd' + (nextDocumentId++); /** * Shows if loading task is destroyed. * @type {boolean} */ this.destroyed = false; /** * Callback to request a password if wrong or no password was provided. * The callback receives two parameters: function that needs to be called * with new password and reason (see {PasswordResponses}). */ this.onPassword = null; /** * Callback to be able to monitor the loading progress of the PDF file * (necessary to implement e.g. a loading bar). The callback receives * an {Object} with the properties: {number} loaded and {number} total. */ this.onProgress = null; /** * Callback to when unsupported feature is used. The callback receives * an {PDFJS.UNSUPPORTED_FEATURES} argument. */ this.onUnsupportedFeature = null; } PDFDocumentLoadingTask.prototype = /** @lends PDFDocumentLoadingTask.prototype */ { /** * @return {Promise} */ get promise() { return this._capability.promise; }, /** * Aborts all network requests and destroys worker. * @return {Promise} A promise that is resolved after destruction activity * is completed. */ destroy: function () { this.destroyed = true; var transportDestroyed = !this._transport ? Promise.resolve() : this._transport.destroy(); return transportDestroyed.then(function () { this._transport = null; if (this._worker) { this._worker.destroy(); this._worker = null; } }.bind(this)); }, /** * Registers callbacks to indicate the document loading completion. * * @param {function} onFulfilled The callback for the loading completion. * @param {function} onRejected The callback for the loading failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function PDFDocumentLoadingTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return PDFDocumentLoadingTask; })(); /** * Abstract class to support range requests file loading. * @class * @alias PDFJS.PDFDataRangeTransport * @param {number} length * @param {Uint8Array} initialData */ var PDFDataRangeTransport = (function pdfDataRangeTransportClosure() { function PDFDataRangeTransport(length, initialData) { this.length = length; this.initialData = initialData; this._rangeListeners = []; this._progressListeners = []; this._progressiveReadListeners = []; this._readyCapability = createPromiseCapability(); } PDFDataRangeTransport.prototype = /** @lends PDFDataRangeTransport.prototype */ { addRangeListener: function PDFDataRangeTransport_addRangeListener(listener) { this._rangeListeners.push(listener); }, addProgressListener: function PDFDataRangeTransport_addProgressListener(listener) { this._progressListeners.push(listener); }, addProgressiveReadListener: function PDFDataRangeTransport_addProgressiveReadListener(listener) { this._progressiveReadListeners.push(listener); }, onDataRange: function PDFDataRangeTransport_onDataRange(begin, chunk) { var listeners = this._rangeListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](begin, chunk); } }, onDataProgress: function PDFDataRangeTransport_onDataProgress(loaded) { this._readyCapability.promise.then(function () { var listeners = this._progressListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](loaded); } }.bind(this)); }, onDataProgressiveRead: function PDFDataRangeTransport_onDataProgress(chunk) { this._readyCapability.promise.then(function () { var listeners = this._progressiveReadListeners; for (var i = 0, n = listeners.length; i < n; ++i) { listeners[i](chunk); } }.bind(this)); }, transportReady: function PDFDataRangeTransport_transportReady() { this._readyCapability.resolve(); }, requestDataRange: function PDFDataRangeTransport_requestDataRange(begin, end) { throw new Error('Abstract method PDFDataRangeTransport.requestDataRange'); }, abort: function PDFDataRangeTransport_abort() { } }; return PDFDataRangeTransport; })(); PDFJS.PDFDataRangeTransport = PDFDataRangeTransport; /** * Proxy to a PDFDocument in the worker thread. Also, contains commonly used * properties that can be read synchronously. * @class * @alias PDFDocumentProxy */ var PDFDocumentProxy = (function PDFDocumentProxyClosure() { function PDFDocumentProxy(pdfInfo, transport, loadingTask) { this.pdfInfo = pdfInfo; this.transport = transport; this.loadingTask = loadingTask; } PDFDocumentProxy.prototype = /** @lends PDFDocumentProxy.prototype */ { /** * @return {number} Total number of pages the PDF contains. */ get numPages() { return this.pdfInfo.numPages; }, /** * @return {string} A unique ID to identify a PDF. Not guaranteed to be * unique. */ get fingerprint() { return this.pdfInfo.fingerprint; }, /** * @param {number} pageNumber The page number to get. The first page is 1. * @return {Promise} A promise that is resolved with a {@link PDFPageProxy} * object. */ getPage: function PDFDocumentProxy_getPage(pageNumber) { return this.transport.getPage(pageNumber); }, /** * @param {{num: number, gen: number}} ref The page reference. Must have * the 'num' and 'gen' properties. * @return {Promise} A promise that is resolved with the page index that is * associated with the reference. */ getPageIndex: function PDFDocumentProxy_getPageIndex(ref) { return this.transport.getPageIndex(ref); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named destinations to reference numbers. * * This can be slow for large documents: use getDestination instead */ getDestinations: function PDFDocumentProxy_getDestinations() { return this.transport.getDestinations(); }, /** * @param {string} id The named destination to get. * @return {Promise} A promise that is resolved with all information * of the given named destination. */ getDestination: function PDFDocumentProxy_getDestination(id) { return this.transport.getDestination(id); }, /** * @return {Promise} A promise that is resolved with a lookup table for * mapping named attachments to their content. */ getAttachments: function PDFDocumentProxy_getAttachments() { return this.transport.getAttachments(); }, /** * @return {Promise} A promise that is resolved with an array of all the * JavaScript strings in the name tree. */ getJavaScript: function PDFDocumentProxy_getJavaScript() { return this.transport.getJavaScript(); }, /** * @return {Promise} A promise that is resolved with an {Array} that is a * tree outline (if it has one) of the PDF. The tree is in the format of: * [ * { * title: string, * bold: boolean, * italic: boolean, * color: rgb array, * dest: dest obj, * items: array of more items like this * }, * ... * ]. */ getOutline: function PDFDocumentProxy_getOutline() { return this.transport.getOutline(); }, /** * @return {Promise} A promise that is resolved with an {Object} that has * info and metadata properties. Info is an {Object} filled with anything * available in the information dictionary and similarly metadata is a * {Metadata} object with information from the metadata section of the PDF. */ getMetadata: function PDFDocumentProxy_getMetadata() { return this.transport.getMetadata(); }, /** * @return {Promise} A promise that is resolved with a TypedArray that has * the raw data from the PDF. */ getData: function PDFDocumentProxy_getData() { return this.transport.getData(); }, /** * @return {Promise} A promise that is resolved when the document's data * is loaded. It is resolved with an {Object} that contains the length * property that indicates size of the PDF data in bytes. */ getDownloadInfo: function PDFDocumentProxy_getDownloadInfo() { return this.transport.downloadInfoCapability.promise; }, /** * @return {Promise} A promise this is resolved with current stats about * document structures (see {@link PDFDocumentStats}). */ getStats: function PDFDocumentProxy_getStats() { return this.transport.getStats(); }, /** * Cleans up resources allocated by the document, e.g. created @font-face. */ cleanup: function PDFDocumentProxy_cleanup() { this.transport.startCleanup(); }, /** * Destroys current document instance and terminates worker. */ destroy: function PDFDocumentProxy_destroy() { return this.loadingTask.destroy(); } }; return PDFDocumentProxy; })(); /** * Page getTextContent parameters. * * @typedef {Object} getTextContentParameters * @param {boolean} normalizeWhitespace - replaces all occurrences of * whitespace with standard spaces (0x20). The default value is `false`. */ /** * Page text content. * * @typedef {Object} TextContent * @property {array} items - array of {@link TextItem} * @property {Object} styles - {@link TextStyles} objects, indexed by font * name. */ /** * Page text content part. * * @typedef {Object} TextItem * @property {string} str - text content. * @property {string} dir - text direction: 'ttb', 'ltr' or 'rtl'. * @property {array} transform - transformation matrix. * @property {number} width - width in device space. * @property {number} height - height in device space. * @property {string} fontName - font name used by pdf.js for converted font. */ /** * Text style. * * @typedef {Object} TextStyle * @property {number} ascent - font ascent. * @property {number} descent - font descent. * @property {boolean} vertical - text is in vertical mode. * @property {string} fontFamily - possible font family */ /** * Page annotation parameters. * * @typedef {Object} GetAnnotationsParameters * @param {string} intent - Determines the annotations that will be fetched, * can be either 'display' (viewable annotations) or 'print' * (printable annotations). * If the parameter is omitted, all annotations are fetched. */ /** * Page render parameters. * * @typedef {Object} RenderParameters * @property {Object} canvasContext - A 2D context of a DOM Canvas object. * @property {PDFJS.PageViewport} viewport - Rendering viewport obtained by * calling of PDFPage.getViewport method. * @property {string} intent - Rendering intent, can be 'display' or 'print' * (default value is 'display'). * @property {Array} transform - (optional) Additional transform, applied * just before viewport transform. * @property {Object} imageLayer - (optional) An object that has beginLayout, * endLayout and appendImage functions. * @property {function} continueCallback - (deprecated) A function that will be * called each time the rendering is paused. To continue * rendering call the function that is the first argument * to the callback. */ /** * PDF page operator list. * * @typedef {Object} PDFOperatorList * @property {Array} fnArray - Array containing the operator functions. * @property {Array} argsArray - Array containing the arguments of the * functions. */ /** * Proxy to a PDFPage in the worker thread. * @class * @alias PDFPageProxy */ var PDFPageProxy = (function PDFPageProxyClosure() { function PDFPageProxy(pageIndex, pageInfo, transport) { this.pageIndex = pageIndex; this.pageInfo = pageInfo; this.transport = transport; this.stats = new StatTimer(); this.stats.enabled = !!globalScope.PDFJS.enableStats; this.commonObjs = transport.commonObjs; this.objs = new PDFObjects(); this.cleanupAfterRender = false; this.pendingCleanup = false; this.intentStates = {}; this.destroyed = false; } PDFPageProxy.prototype = /** @lends PDFPageProxy.prototype */ { /** * @return {number} Page number of the page. First page is 1. */ get pageNumber() { return this.pageIndex + 1; }, /** * @return {number} The number of degrees the page is rotated clockwise. */ get rotate() { return this.pageInfo.rotate; }, /** * @return {Object} The reference that points to this page. It has 'num' and * 'gen' properties. */ get ref() { return this.pageInfo.ref; }, /** * @return {Array} An array of the visible portion of the PDF page in the * user space units - [x1, y1, x2, y2]. */ get view() { return this.pageInfo.view; }, /** * @param {number} scale The desired scale of the viewport. * @param {number} rotate Degrees to rotate the viewport. If omitted this * defaults to the page rotation. * @return {PDFJS.PageViewport} Contains 'width' and 'height' properties * along with transforms required for rendering. */ getViewport: function PDFPageProxy_getViewport(scale, rotate) { if (arguments.length < 2) { rotate = this.rotate; } return new PDFJS.PageViewport(this.view, scale, rotate, 0, 0); }, /** * @param {GetAnnotationsParameters} params - Annotation parameters. * @return {Promise} A promise that is resolved with an {Array} of the * annotation objects. */ getAnnotations: function PDFPageProxy_getAnnotations(params) { var intent = (params && params.intent) || null; if (!this.annotationsPromise || this.annotationsIntent !== intent) { this.annotationsPromise = this.transport.getAnnotations(this.pageIndex, intent); this.annotationsIntent = intent; } return this.annotationsPromise; }, /** * Begins the process of rendering a page to the desired context. * @param {RenderParameters} params Page render parameters. * @return {RenderTask} An object that contains the promise, which * is resolved when the page finishes rendering. */ render: function PDFPageProxy_render(params) { var stats = this.stats; stats.time('Overall'); // If there was a pending destroy cancel it so no cleanup happens during // this call to render. this.pendingCleanup = false; var renderingIntent = (params.intent === 'print' ? 'print' : 'display'); if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; // If there's no displayReadyCapability yet, then the operatorList // was never requested before. Make the request and create the promise. if (!intentState.displayReadyCapability) { intentState.receivingOperatorList = true; intentState.displayReadyCapability = createPromiseCapability(); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.stats.time('Page Request'); this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageNumber - 1, intent: renderingIntent }); } var internalRenderTask = new InternalRenderTask(complete, params, this.objs, this.commonObjs, intentState.operatorList, this.pageNumber); internalRenderTask.useRequestAnimationFrame = renderingIntent !== 'print'; if (!intentState.renderTasks) { intentState.renderTasks = []; } intentState.renderTasks.push(internalRenderTask); var renderTask = internalRenderTask.task; // Obsolete parameter support if (params.continueCallback) { deprecated('render is used with continueCallback parameter'); renderTask.onContinue = params.continueCallback; } var self = this; intentState.displayReadyCapability.promise.then( function pageDisplayReadyPromise(transparency) { if (self.pendingCleanup) { complete(); return; } stats.time('Rendering'); internalRenderTask.initalizeGraphics(transparency); internalRenderTask.operatorListChanged(); }, function pageDisplayReadPromiseError(reason) { complete(reason); } ); function complete(error) { var i = intentState.renderTasks.indexOf(internalRenderTask); if (i >= 0) { intentState.renderTasks.splice(i, 1); } if (self.cleanupAfterRender) { self.pendingCleanup = true; } self._tryCleanup(); if (error) { internalRenderTask.capability.reject(error); } else { internalRenderTask.capability.resolve(); } stats.timeEnd('Rendering'); stats.timeEnd('Overall'); } return renderTask; }, /** * @return {Promise} A promise resolved with an {@link PDFOperatorList} * object that represents page's operator list. */ getOperatorList: function PDFPageProxy_getOperatorList() { function operatorListChanged() { if (intentState.operatorList.lastChunk) { intentState.opListReadCapability.resolve(intentState.operatorList); } } var renderingIntent = 'oplist'; if (!this.intentStates[renderingIntent]) { this.intentStates[renderingIntent] = {}; } var intentState = this.intentStates[renderingIntent]; if (!intentState.opListReadCapability) { var opListTask = {}; opListTask.operatorListChanged = operatorListChanged; intentState.receivingOperatorList = true; intentState.opListReadCapability = createPromiseCapability(); intentState.renderTasks = []; intentState.renderTasks.push(opListTask); intentState.operatorList = { fnArray: [], argsArray: [], lastChunk: false }; this.transport.messageHandler.send('RenderPageRequest', { pageIndex: this.pageIndex, intent: renderingIntent }); } return intentState.opListReadCapability.promise; }, /** * @param {getTextContentParameters} params - getTextContent parameters. * @return {Promise} That is resolved a {@link TextContent} * object that represent the page text content. */ getTextContent: function PDFPageProxy_getTextContent(params) { var normalizeWhitespace = (params && params.normalizeWhitespace) || false; return this.transport.messageHandler.sendWithPromise('GetTextContent', { pageIndex: this.pageNumber - 1, normalizeWhitespace: normalizeWhitespace, }); }, /** * Destroys page object. */ _destroy: function PDFPageProxy_destroy() { this.destroyed = true; this.transport.pageCache[this.pageIndex] = null; var waitOn = []; Object.keys(this.intentStates).forEach(function(intent) { var intentState = this.intentStates[intent]; intentState.renderTasks.forEach(function(renderTask) { var renderCompleted = renderTask.capability.promise. catch(function () {}); // ignoring failures waitOn.push(renderCompleted); renderTask.cancel(); }); }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; return Promise.all(waitOn); }, /** * Cleans up resources allocated by the page. (deprecated) */ destroy: function() { deprecated('page destroy method, use cleanup() instead'); this.cleanup(); }, /** * Cleans up resources allocated by the page. */ cleanup: function PDFPageProxy_cleanup() { this.pendingCleanup = true; this._tryCleanup(); }, /** * For internal use only. Attempts to clean up if rendering is in a state * where that's possible. * @ignore */ _tryCleanup: function PDFPageProxy_tryCleanup() { if (!this.pendingCleanup || Object.keys(this.intentStates).some(function(intent) { var intentState = this.intentStates[intent]; return (intentState.renderTasks.length !== 0 || intentState.receivingOperatorList); }, this)) { return; } Object.keys(this.intentStates).forEach(function(intent) { delete this.intentStates[intent]; }, this); this.objs.clear(); this.annotationsPromise = null; this.pendingCleanup = false; }, /** * For internal use only. * @ignore */ _startRenderPage: function PDFPageProxy_startRenderPage(transparency, intent) { var intentState = this.intentStates[intent]; // TODO Refactor RenderPageRequest to separate rendering // and operator list logic if (intentState.displayReadyCapability) { intentState.displayReadyCapability.resolve(transparency); } }, /** * For internal use only. * @ignore */ _renderPageChunk: function PDFPageProxy_renderPageChunk(operatorListChunk, intent) { var intentState = this.intentStates[intent]; var i, ii; // Add the new chunk to the current operator list. for (i = 0, ii = operatorListChunk.length; i < ii; i++) { intentState.operatorList.fnArray.push(operatorListChunk.fnArray[i]); intentState.operatorList.argsArray.push( operatorListChunk.argsArray[i]); } intentState.operatorList.lastChunk = operatorListChunk.lastChunk; // Notify all the rendering tasks there are more operators to be consumed. for (i = 0; i < intentState.renderTasks.length; i++) { intentState.renderTasks[i].operatorListChanged(); } if (operatorListChunk.lastChunk) { intentState.receivingOperatorList = false; this._tryCleanup(); } } }; return PDFPageProxy; })(); /** * PDF.js web worker abstraction, it controls instantiation of PDF documents and * WorkerTransport for them. If creation of a web worker is not possible, * a "fake" worker will be used instead. * @class */ var PDFWorker = (function PDFWorkerClosure() { var nextFakeWorkerId = 0; // Loads worker code into main thread. function setupFakeWorkerGlobal() { if (!PDFJS.fakeWorkerFilesLoadedCapability) { PDFJS.fakeWorkerFilesLoadedCapability = createPromiseCapability(); // In the developer build load worker_loader which in turn loads all the // other files and resolves the promise. In production only the // pdf.worker.js file is needed. Util.loadScript(PDFJS.workerSrc, function() { PDFJS.fakeWorkerFilesLoadedCapability.resolve(); }); } return PDFJS.fakeWorkerFilesLoadedCapability.promise; } function PDFWorker(name) { this.name = name; this.destroyed = false; this._readyCapability = createPromiseCapability(); this._port = null; this._webWorker = null; this._messageHandler = null; this._initialize(); } PDFWorker.prototype = /** @lends PDFWorker.prototype */ { get promise() { return this._readyCapability.promise; }, get port() { return this._port; }, get messageHandler() { return this._messageHandler; }, _initialize: function PDFWorker_initialize() { // If worker support isn't disabled explicit and the browser has worker // support, create a new web worker and test if it/the browser fullfills // all requirements to run parts of pdf.js in a web worker. // Right now, the requirement is, that an Uint8Array is still an // Uint8Array as it arrives on the worker. (Chrome added this with v.15.) if (!globalScope.PDFJS.disableWorker && typeof Worker !== 'undefined') { var workerSrc = PDFJS.workerSrc; if (!workerSrc) { error('No PDFJS.workerSrc specified'); } try { // Some versions of FF can't create a worker on localhost, see: // https://bugzilla.mozilla.org/show_bug.cgi?id=683280 var worker = new Worker(workerSrc); var messageHandler = new MessageHandler('main', 'worker', worker); messageHandler.on('test', function PDFWorker_test(data) { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); messageHandler.destroy(); worker.terminate(); return; // worker was destroyed } var supportTypedArray = data && data.supportTypedArray; if (supportTypedArray) { this._messageHandler = messageHandler; this._port = worker; this._webWorker = worker; if (!data.supportTransfers) { PDFJS.postMessageTransfers = false; } this._readyCapability.resolve(); } else { this._setupFakeWorker(); messageHandler.destroy(); worker.terminate(); } }.bind(this)); messageHandler.on('console_log', function (data) { console.log.apply(console, data); }); messageHandler.on('console_error', function (data) { console.error.apply(console, data); }); var testObj = new Uint8Array([PDFJS.postMessageTransfers ? 255 : 0]); // Some versions of Opera throw a DATA_CLONE_ERR on serializing the // typed array. Also, checking if we can use transfers. try { messageHandler.send('test', testObj, [testObj.buffer]); } catch (ex) { info('Cannot use postMessage transfers'); testObj[0] = 0; messageHandler.send('test', testObj); } return; } catch (e) { info('The worker has been disabled.'); } } // Either workers are disabled, not supported or have thrown an exception. // Thus, we fallback to a faked worker. this._setupFakeWorker(); }, _setupFakeWorker: function PDFWorker_setupFakeWorker() { warn('Setting up fake worker.'); globalScope.PDFJS.disableWorker = true; setupFakeWorkerGlobal().then(function () { if (this.destroyed) { this._readyCapability.reject(new Error('Worker was destroyed')); return; } // If we don't use a worker, just post/sendMessage to the main thread. var port = { _listeners: [], postMessage: function (obj) { var e = {data: obj}; this._listeners.forEach(function (listener) { listener.call(this, e); }, this); }, addEventListener: function (name, listener) { this._listeners.push(listener); }, removeEventListener: function (name, listener) { var i = this._listeners.indexOf(listener); this._listeners.splice(i, 1); }, terminate: function () {} }; this._port = port; // All fake workers use the same port, making id unique. var id = 'fake' + (nextFakeWorkerId++); // If the main thread is our worker, setup the handling for the // messages -- the main thread sends to it self. var workerHandler = new MessageHandler(id + '_worker', id, port); PDFJS.WorkerMessageHandler.setup(workerHandler, port); var messageHandler = new MessageHandler(id, id + '_worker', port); this._messageHandler = messageHandler; this._readyCapability.resolve(); }.bind(this)); }, /** * Destroys the worker instance. */ destroy: function PDFWorker_destroy() { this.destroyed = true; if (this._webWorker) { // We need to terminate only web worker created resource. this._webWorker.terminate(); this._webWorker = null; } this._port = null; if (this._messageHandler) { this._messageHandler.destroy(); this._messageHandler = null; } } }; return PDFWorker; })(); PDFJS.PDFWorker = PDFWorker; /** * For internal use only. * @ignore */ var WorkerTransport = (function WorkerTransportClosure() { function WorkerTransport(messageHandler, loadingTask, pdfDataRangeTransport) { this.messageHandler = messageHandler; this.loadingTask = loadingTask; this.pdfDataRangeTransport = pdfDataRangeTransport; this.commonObjs = new PDFObjects(); this.fontLoader = new FontLoader(loadingTask.docId); this.destroyed = false; this.destroyCapability = null; this.pageCache = []; this.pagePromises = []; this.downloadInfoCapability = createPromiseCapability(); this.setupMessageHandler(); } WorkerTransport.prototype = { destroy: function WorkerTransport_destroy() { if (this.destroyCapability) { return this.destroyCapability.promise; } this.destroyed = true; this.destroyCapability = createPromiseCapability(); var waitOn = []; // We need to wait for all renderings to be completed, e.g. // timeout/rAF can take a long time. this.pageCache.forEach(function (page) { if (page) { waitOn.push(page._destroy()); } }); this.pageCache = []; this.pagePromises = []; var self = this; // We also need to wait for the worker to finish its long running tasks. var terminated = this.messageHandler.sendWithPromise('Terminate', null); waitOn.push(terminated); Promise.all(waitOn).then(function () { self.fontLoader.clear(); if (self.pdfDataRangeTransport) { self.pdfDataRangeTransport.abort(); self.pdfDataRangeTransport = null; } if (self.messageHandler) { self.messageHandler.destroy(); self.messageHandler = null; } self.destroyCapability.resolve(); }, this.destroyCapability.reject); return this.destroyCapability.promise; }, setupMessageHandler: function WorkerTransport_setupMessageHandler() { var messageHandler = this.messageHandler; function updatePassword(password) { messageHandler.send('UpdatePassword', password); } var pdfDataRangeTransport = this.pdfDataRangeTransport; if (pdfDataRangeTransport) { pdfDataRangeTransport.addRangeListener(function(begin, chunk) { messageHandler.send('OnDataRange', { begin: begin, chunk: chunk }); }); pdfDataRangeTransport.addProgressListener(function(loaded) { messageHandler.send('OnDataProgress', { loaded: loaded }); }); pdfDataRangeTransport.addProgressiveReadListener(function(chunk) { messageHandler.send('OnDataRange', { chunk: chunk }); }); messageHandler.on('RequestDataRange', function transportDataRange(data) { pdfDataRangeTransport.requestDataRange(data.begin, data.end); }, this); } messageHandler.on('GetDoc', function transportDoc(data) { var pdfInfo = data.pdfInfo; this.numPages = data.pdfInfo.numPages; var loadingTask = this.loadingTask; var pdfDocument = new PDFDocumentProxy(pdfInfo, this, loadingTask); this.pdfDocument = pdfDocument; loadingTask._capability.resolve(pdfDocument); }, this); messageHandler.on('NeedPassword', function transportNeedPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.NEED_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('IncorrectPassword', function transportIncorrectPassword(exception) { var loadingTask = this.loadingTask; if (loadingTask.onPassword) { return loadingTask.onPassword(updatePassword, PasswordResponses.INCORRECT_PASSWORD); } loadingTask._capability.reject( new PasswordException(exception.message, exception.code)); }, this); messageHandler.on('InvalidPDF', function transportInvalidPDF(exception) { this.loadingTask._capability.reject( new InvalidPDFException(exception.message)); }, this); messageHandler.on('MissingPDF', function transportMissingPDF(exception) { this.loadingTask._capability.reject( new MissingPDFException(exception.message)); }, this); messageHandler.on('UnexpectedResponse', function transportUnexpectedResponse(exception) { this.loadingTask._capability.reject( new UnexpectedResponseException(exception.message, exception.status)); }, this); messageHandler.on('UnknownError', function transportUnknownError(exception) { this.loadingTask._capability.reject( new UnknownErrorException(exception.message, exception.details)); }, this); messageHandler.on('DataLoaded', function transportPage(data) { this.downloadInfoCapability.resolve(data); }, this); messageHandler.on('PDFManagerReady', function transportPage(data) { if (this.pdfDataRangeTransport) { this.pdfDataRangeTransport.transportReady(); } }, this); messageHandler.on('StartRenderPage', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page.stats.timeEnd('Page Request'); page._startRenderPage(data.transparency, data.intent); }, this); messageHandler.on('RenderPageChunk', function transportRender(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageIndex]; page._renderPageChunk(data.operatorList, data.intent); }, this); messageHandler.on('commonobj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var type = data[1]; if (this.commonObjs.hasData(id)) { return; } switch (type) { case 'Font': var exportedData = data[2]; var font; if ('error' in exportedData) { var error = exportedData.error; warn('Error during font loading: ' + error); this.commonObjs.resolve(id, error); break; } else { font = new FontFaceObject(exportedData); } this.fontLoader.bind( [font], function fontReady(fontObjs) { this.commonObjs.resolve(id, font); }.bind(this) ); break; case 'FontPath': this.commonObjs.resolve(id, data[2]); break; default: error('Got unknown common object type ' + type); } }, this); messageHandler.on('obj', function transportObj(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var id = data[0]; var pageIndex = data[1]; var type = data[2]; var pageProxy = this.pageCache[pageIndex]; var imageData; if (pageProxy.objs.hasData(id)) { return; } switch (type) { case 'JpegStream': imageData = data[3]; loadJpegStream(id, imageData, pageProxy.objs); break; case 'Image': imageData = data[3]; pageProxy.objs.resolve(id, imageData); // heuristics that will allow not to store large data var MAX_IMAGE_SIZE_TO_STORE = 8000000; if (imageData && 'data' in imageData && imageData.data.length > MAX_IMAGE_SIZE_TO_STORE) { pageProxy.cleanupAfterRender = true; } break; default: error('Got unknown object type ' + type); } }, this); messageHandler.on('DocProgress', function transportDocProgress(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var loadingTask = this.loadingTask; if (loadingTask.onProgress) { loadingTask.onProgress({ loaded: data.loaded, total: data.total }); } }, this); messageHandler.on('PageError', function transportError(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var page = this.pageCache[data.pageNum - 1]; var intentState = page.intentStates[data.intent]; if (intentState.displayReadyCapability) { intentState.displayReadyCapability.reject(data.error); } else { error(data.error); } }, this); messageHandler.on('UnsupportedFeature', function transportUnsupportedFeature(data) { if (this.destroyed) { return; // Ignore any pending requests if the worker was terminated. } var featureId = data.featureId; var loadingTask = this.loadingTask; if (loadingTask.onUnsupportedFeature) { loadingTask.onUnsupportedFeature(featureId); } PDFJS.UnsupportedManager.notify(featureId); }, this); messageHandler.on('JpegDecode', function(data) { if (this.destroyed) { return Promise.reject('Worker was terminated'); } var imageUrl = data[0]; var components = data[1]; if (components !== 3 && components !== 1) { return Promise.reject( new Error('Only 3 components or 1 component can be returned')); } return new Promise(function (resolve, reject) { var img = new Image(); img.onload = function () { var width = img.width; var height = img.height; var size = width * height; var rgbaLength = size * 4; var buf = new Uint8Array(size * components); var tmpCanvas = createScratchCanvas(width, height); var tmpCtx = tmpCanvas.getContext('2d'); tmpCtx.drawImage(img, 0, 0); var data = tmpCtx.getImageData(0, 0, width, height).data; var i, j; if (components === 3) { for (i = 0, j = 0; i < rgbaLength; i += 4, j += 3) { buf[j] = data[i]; buf[j + 1] = data[i + 1]; buf[j + 2] = data[i + 2]; } } else if (components === 1) { for (i = 0, j = 0; i < rgbaLength; i += 4, j++) { buf[j] = data[i]; } } resolve({ data: buf, width: width, height: height}); }; img.onerror = function () { reject(new Error('JpegDecode failed to load image')); }; img.src = imageUrl; }); }, this); }, getData: function WorkerTransport_getData() { return this.messageHandler.sendWithPromise('GetData', null); }, getPage: function WorkerTransport_getPage(pageNumber, capability) { if (pageNumber <= 0 || pageNumber > this.numPages || (pageNumber|0) !== pageNumber) { return Promise.reject(new Error('Invalid page request')); } var pageIndex = pageNumber - 1; if (pageIndex in this.pagePromises) { return this.pagePromises[pageIndex]; } var promise = this.messageHandler.sendWithPromise('GetPage', { pageIndex: pageIndex }).then(function (pageInfo) { if (this.destroyed) { throw new Error('Transport destroyed'); } var page = new PDFPageProxy(pageIndex, pageInfo, this); this.pageCache[pageIndex] = page; return page; }.bind(this)); this.pagePromises[pageIndex] = promise; return promise; }, getPageIndex: function WorkerTransport_getPageIndexByRef(ref) { return this.messageHandler.sendWithPromise('GetPageIndex', { ref: ref }); }, getAnnotations: function WorkerTransport_getAnnotations(pageIndex, intent) { return this.messageHandler.sendWithPromise('GetAnnotations', { pageIndex: pageIndex, intent: intent, }); }, getDestinations: function WorkerTransport_getDestinations() { return this.messageHandler.sendWithPromise('GetDestinations', null); }, getDestination: function WorkerTransport_getDestination(id) { return this.messageHandler.sendWithPromise('GetDestination', { id: id }); }, getAttachments: function WorkerTransport_getAttachments() { return this.messageHandler.sendWithPromise('GetAttachments', null); }, getJavaScript: function WorkerTransport_getJavaScript() { return this.messageHandler.sendWithPromise('GetJavaScript', null); }, getOutline: function WorkerTransport_getOutline() { return this.messageHandler.sendWithPromise('GetOutline', null); }, getMetadata: function WorkerTransport_getMetadata() { return this.messageHandler.sendWithPromise('GetMetadata', null). then(function transportMetadata(results) { return { info: results[0], metadata: (results[1] ? new PDFJS.Metadata(results[1]) : null) }; }); }, getStats: function WorkerTransport_getStats() { return this.messageHandler.sendWithPromise('GetStats', null); }, startCleanup: function WorkerTransport_startCleanup() { this.messageHandler.sendWithPromise('Cleanup', null). then(function endCleanup() { for (var i = 0, ii = this.pageCache.length; i < ii; i++) { var page = this.pageCache[i]; if (page) { page.cleanup(); } } this.commonObjs.clear(); this.fontLoader.clear(); }.bind(this)); } }; return WorkerTransport; })(); /** * A PDF document and page is built of many objects. E.g. there are objects * for fonts, images, rendering code and such. These objects might get processed * inside of a worker. The `PDFObjects` implements some basic functions to * manage these objects. * @ignore */ var PDFObjects = (function PDFObjectsClosure() { function PDFObjects() { this.objs = {}; } PDFObjects.prototype = { /** * Internal function. * Ensures there is an object defined for `objId`. */ ensureObj: function PDFObjects_ensureObj(objId) { if (this.objs[objId]) { return this.objs[objId]; } var obj = { capability: createPromiseCapability(), data: null, resolved: false }; this.objs[objId] = obj; return obj; }, /** * If called *without* callback, this returns the data of `objId` but the * object needs to be resolved. If it isn't, this function throws. * * If called *with* a callback, the callback is called with the data of the * object once the object is resolved. That means, if you call this * function and the object is already resolved, the callback gets called * right away. */ get: function PDFObjects_get(objId, callback) { // If there is a callback, then the get can be async and the object is // not required to be resolved right now if (callback) { this.ensureObj(objId).capability.promise.then(callback); return null; } // If there isn't a callback, the user expects to get the resolved data // directly. var obj = this.objs[objId]; // If there isn't an object yet or the object isn't resolved, then the // data isn't ready yet! if (!obj || !obj.resolved) { error('Requesting object that isn\'t resolved yet ' + objId); } return obj.data; }, /** * Resolves the object `objId` with optional `data`. */ resolve: function PDFObjects_resolve(objId, data) { var obj = this.ensureObj(objId); obj.resolved = true; obj.data = data; obj.capability.resolve(data); }, isResolved: function PDFObjects_isResolved(objId) { var objs = this.objs; if (!objs[objId]) { return false; } else { return objs[objId].resolved; } }, hasData: function PDFObjects_hasData(objId) { return this.isResolved(objId); }, /** * Returns the data of `objId` if object exists, null otherwise. */ getData: function PDFObjects_getData(objId) { var objs = this.objs; if (!objs[objId] || !objs[objId].resolved) { return null; } else { return objs[objId].data; } }, clear: function PDFObjects_clear() { this.objs = {}; } }; return PDFObjects; })(); /** * Allows controlling of the rendering tasks. * @class * @alias RenderTask */ var RenderTask = (function RenderTaskClosure() { function RenderTask(internalRenderTask) { this._internalRenderTask = internalRenderTask; /** * Callback for incremental rendering -- a function that will be called * each time the rendering is paused. To continue rendering call the * function that is the first argument to the callback. * @type {function} */ this.onContinue = null; } RenderTask.prototype = /** @lends RenderTask.prototype */ { /** * Promise for rendering task completion. * @return {Promise} */ get promise() { return this._internalRenderTask.capability.promise; }, /** * Cancels the rendering task. If the task is currently rendering it will * not be cancelled until graphics pauses with a timeout. The promise that * this object extends will resolved when cancelled. */ cancel: function RenderTask_cancel() { this._internalRenderTask.cancel(); }, /** * Registers callbacks to indicate the rendering task completion. * * @param {function} onFulfilled The callback for the rendering completion. * @param {function} onRejected The callback for the rendering failure. * @return {Promise} A promise that is resolved after the onFulfilled or * onRejected callback. */ then: function RenderTask_then(onFulfilled, onRejected) { return this.promise.then.apply(this.promise, arguments); } }; return RenderTask; })(); /** * For internal use only. * @ignore */ var InternalRenderTask = (function InternalRenderTaskClosure() { function InternalRenderTask(callback, params, objs, commonObjs, operatorList, pageNumber) { this.callback = callback; this.params = params; this.objs = objs; this.commonObjs = commonObjs; this.operatorListIdx = null; this.operatorList = operatorList; this.pageNumber = pageNumber; this.running = false; this.graphicsReadyCallback = null; this.graphicsReady = false; this.useRequestAnimationFrame = false; this.cancelled = false; this.capability = createPromiseCapability(); this.task = new RenderTask(this); // caching this-bound methods this._continueBound = this._continue.bind(this); this._scheduleNextBound = this._scheduleNext.bind(this); this._nextBound = this._next.bind(this); } InternalRenderTask.prototype = { initalizeGraphics: function InternalRenderTask_initalizeGraphics(transparency) { if (this.cancelled) { return; } if (PDFJS.pdfBug && 'StepperManager' in globalScope && globalScope.StepperManager.enabled) { this.stepper = globalScope.StepperManager.create(this.pageNumber - 1); this.stepper.init(this.operatorList); this.stepper.nextBreakPoint = this.stepper.getNextBreakPoint(); } var params = this.params; this.gfx = new CanvasGraphics(params.canvasContext, this.commonObjs, this.objs, params.imageLayer); this.gfx.beginDrawing(params.transform, params.viewport, transparency); this.operatorListIdx = 0; this.graphicsReady = true; if (this.graphicsReadyCallback) { this.graphicsReadyCallback(); } }, cancel: function InternalRenderTask_cancel() { this.running = false; this.cancelled = true; this.callback('cancelled'); }, operatorListChanged: function InternalRenderTask_operatorListChanged() { if (!this.graphicsReady) { if (!this.graphicsReadyCallback) { this.graphicsReadyCallback = this._continueBound; } return; } if (this.stepper) { this.stepper.updateOperatorList(this.operatorList); } if (this.running) { return; } this._continue(); }, _continue: function InternalRenderTask__continue() { this.running = true; if (this.cancelled) { return; } if (this.task.onContinue) { this.task.onContinue.call(this.task, this._scheduleNextBound); } else { this._scheduleNext(); } }, _scheduleNext: function InternalRenderTask__scheduleNext() { if (this.useRequestAnimationFrame) { window.requestAnimationFrame(this._nextBound); } else { Promise.resolve(undefined).then(this._nextBound); } }, _next: function InternalRenderTask__next() { if (this.cancelled) { return; } this.operatorListIdx = this.gfx.executeOperatorList(this.operatorList, this.operatorListIdx, this._continueBound, this.stepper); if (this.operatorListIdx === this.operatorList.argsArray.length) { this.running = false; if (this.operatorList.lastChunk) { this.gfx.endDrawing(); this.callback(); } } } }; return InternalRenderTask; })(); /** * (Deprecated) Global observer of unsupported feature usages. Use * onUnsupportedFeature callback of the {PDFDocumentLoadingTask} instance. */ PDFJS.UnsupportedManager = (function UnsupportedManagerClosure() { var listeners = []; return { listen: function (cb) { deprecated('Global UnsupportedManager.listen is used: ' + ' use PDFDocumentLoadingTask.onUnsupportedFeature instead'); listeners.push(cb); }, notify: function (featureId) { for (var i = 0, ii = listeners.length; i < ii; i++) { listeners[i](featureId); } } }; })(); var Metadata = PDFJS.Metadata = (function MetadataClosure() { function fixMetadata(meta) { return meta.replace(/>\\376\\377([^<]+)/g, function(all, codes) { var bytes = codes.replace(/\\([0-3])([0-7])([0-7])/g, function(code, d1, d2, d3) { return String.fromCharCode(d1 * 64 + d2 * 8 + d3 * 1); }); var chars = ''; for (var i = 0; i < bytes.length; i += 2) { var code = bytes.charCodeAt(i) * 256 + bytes.charCodeAt(i + 1); chars += code >= 32 && code < 127 && code !== 60 && code !== 62 && code !== 38 && false ? String.fromCharCode(code) : '&#x' + (0x10000 + code).toString(16).substring(1) + ';'; } return '>' + chars; }); } function Metadata(meta) { if (typeof meta === 'string') { // Ghostscript produces invalid metadata meta = fixMetadata(meta); var parser = new DOMParser(); meta = parser.parseFromString(meta, 'application/xml'); } else if (!(meta instanceof Document)) { error('Metadata: Invalid metadata object'); } this.metaDocument = meta; this.metadata = {}; this.parse(); } Metadata.prototype = { parse: function Metadata_parse() { var doc = this.metaDocument; var rdf = doc.documentElement; if (rdf.nodeName.toLowerCase() !== 'rdf:rdf') { // Wrapped in <xmpmeta> rdf = rdf.firstChild; while (rdf && rdf.nodeName.toLowerCase() !== 'rdf:rdf') { rdf = rdf.nextSibling; } } var nodeName = (rdf) ? rdf.nodeName.toLowerCase() : null; if (!rdf || nodeName !== 'rdf:rdf' || !rdf.hasChildNodes()) { return; } var children = rdf.childNodes, desc, entry, name, i, ii, length, iLength; for (i = 0, length = children.length; i < length; i++) { desc = children[i]; if (desc.nodeName.toLowerCase() !== 'rdf:description') { continue; } for (ii = 0, iLength = desc.childNodes.length; ii < iLength; ii++) { if (desc.childNodes[ii].nodeName.toLowerCase() !== '#text') { entry = desc.childNodes[ii]; name = entry.nodeName.toLowerCase(); this.metadata[name] = entry.textContent.trim(); } } } }, get: function Metadata_get(name) { return this.metadata[name] || null; }, has: function Metadata_has(name) { return typeof this.metadata[name] !== 'undefined'; } }; return Metadata; })(); // <canvas> contexts store most of the state we need natively. // However, PDF needs a bit more state, which we store here. // Minimal font size that would be used during canvas fillText operations. var MIN_FONT_SIZE = 16; // Maximum font size that would be used during canvas fillText operations. var MAX_FONT_SIZE = 100; var MAX_GROUP_SIZE = 4096; // Heuristic value used when enforcing minimum line widths. var MIN_WIDTH_FACTOR = 0.65; var COMPILE_TYPE3_GLYPHS = true; var MAX_SIZE_TO_COMPILE = 1000; var FULL_CHUNK_HEIGHT = 16; function createScratchCanvas(width, height) { var canvas = document.createElement('canvas'); canvas.width = width; canvas.height = height; return canvas; } function addContextCurrentTransform(ctx) { // If the context doesn't expose a `mozCurrentTransform`, add a JS based one. if (!ctx.mozCurrentTransform) { ctx._originalSave = ctx.save; ctx._originalRestore = ctx.restore; ctx._originalRotate = ctx.rotate; ctx._originalScale = ctx.scale; ctx._originalTranslate = ctx.translate; ctx._originalTransform = ctx.transform; ctx._originalSetTransform = ctx.setTransform; ctx._transformMatrix = ctx._transformMatrix || [1, 0, 0, 1, 0, 0]; ctx._transformStack = []; Object.defineProperty(ctx, 'mozCurrentTransform', { get: function getCurrentTransform() { return this._transformMatrix; } }); Object.defineProperty(ctx, 'mozCurrentTransformInverse', { get: function getCurrentTransformInverse() { // Calculation done using WolframAlpha: // http://www.wolframalpha.com/input/? // i=Inverse+{{a%2C+c%2C+e}%2C+{b%2C+d%2C+f}%2C+{0%2C+0%2C+1}} var m = this._transformMatrix; var a = m[0], b = m[1], c = m[2], d = m[3], e = m[4], f = m[5]; var ad_bc = a * d - b * c; var bc_ad = b * c - a * d; return [ d / ad_bc, b / bc_ad, c / bc_ad, a / ad_bc, (d * e - c * f) / bc_ad, (b * e - a * f) / ad_bc ]; } }); ctx.save = function ctxSave() { var old = this._transformMatrix; this._transformStack.push(old); this._transformMatrix = old.slice(0, 6); this._originalSave(); }; ctx.restore = function ctxRestore() { var prev = this._transformStack.pop(); if (prev) { this._transformMatrix = prev; this._originalRestore(); } }; ctx.translate = function ctxTranslate(x, y) { var m = this._transformMatrix; m[4] = m[0] * x + m[2] * y + m[4]; m[5] = m[1] * x + m[3] * y + m[5]; this._originalTranslate(x, y); }; ctx.scale = function ctxScale(x, y) { var m = this._transformMatrix; m[0] = m[0] * x; m[1] = m[1] * x; m[2] = m[2] * y; m[3] = m[3] * y; this._originalScale(x, y); }; ctx.transform = function ctxTransform(a, b, c, d, e, f) { var m = this._transformMatrix; this._transformMatrix = [ m[0] * a + m[2] * b, m[1] * a + m[3] * b, m[0] * c + m[2] * d, m[1] * c + m[3] * d, m[0] * e + m[2] * f + m[4], m[1] * e + m[3] * f + m[5] ]; ctx._originalTransform(a, b, c, d, e, f); }; ctx.setTransform = function ctxSetTransform(a, b, c, d, e, f) { this._transformMatrix = [a, b, c, d, e, f]; ctx._originalSetTransform(a, b, c, d, e, f); }; ctx.rotate = function ctxRotate(angle) { var cosValue = Math.cos(angle); var sinValue = Math.sin(angle); var m = this._transformMatrix; this._transformMatrix = [ m[0] * cosValue + m[2] * sinValue, m[1] * cosValue + m[3] * sinValue, m[0] * (-sinValue) + m[2] * cosValue, m[1] * (-sinValue) + m[3] * cosValue, m[4], m[5] ]; this._originalRotate(angle); }; } } var CachedCanvases = (function CachedCanvasesClosure() { function CachedCanvases() { this.cache = Object.create(null); } CachedCanvases.prototype = { getCanvas: function CachedCanvases_getCanvas(id, width, height, trackTransform) { var canvasEntry; if (this.cache[id] !== undefined) { canvasEntry = this.cache[id]; canvasEntry.canvas.width = width; canvasEntry.canvas.height = height; // reset canvas transform for emulated mozCurrentTransform, if needed canvasEntry.context.setTransform(1, 0, 0, 1, 0, 0); } else { var canvas = createScratchCanvas(width, height); var ctx = canvas.getContext('2d'); if (trackTransform) { addContextCurrentTransform(ctx); } this.cache[id] = canvasEntry = {canvas: canvas, context: ctx}; } return canvasEntry; }, clear: function () { for (var id in this.cache) { var canvasEntry = this.cache[id]; // Zeroing the width and height causes Firefox to release graphics // resources immediately, which can greatly reduce memory consumption. canvasEntry.canvas.width = 0; canvasEntry.canvas.height = 0; delete this.cache[id]; } } }; return CachedCanvases; })(); function compileType3Glyph(imgData) { var POINT_TO_PROCESS_LIMIT = 1000; var width = imgData.width, height = imgData.height; var i, j, j0, width1 = width + 1; var points = new Uint8Array(width1 * (height + 1)); var POINT_TYPES = new Uint8Array([0, 2, 4, 0, 1, 0, 5, 4, 8, 10, 0, 8, 0, 2, 1, 0]); // decodes bit-packed mask data var lineSize = (width + 7) & ~7, data0 = imgData.data; var data = new Uint8Array(lineSize * height), pos = 0, ii; for (i = 0, ii = data0.length; i < ii; i++) { var mask = 128, elem = data0[i]; while (mask > 0) { data[pos++] = (elem & mask) ? 0 : 255; mask >>= 1; } } // finding iteresting points: every point is located between mask pixels, // so there will be points of the (width + 1)x(height + 1) grid. Every point // will have flags assigned based on neighboring mask pixels: // 4 | 8 // --P-- // 2 | 1 // We are interested only in points with the flags: // - outside corners: 1, 2, 4, 8; // - inside corners: 7, 11, 13, 14; // - and, intersections: 5, 10. var count = 0; pos = 0; if (data[pos] !== 0) { points[0] = 1; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j] = data[pos] ? 2 : 1; ++count; } pos++; } if (data[pos] !== 0) { points[j] = 2; ++count; } for (i = 1; i < height; i++) { pos = i * lineSize; j0 = i * width1; if (data[pos - lineSize] !== data[pos]) { points[j0] = data[pos] ? 1 : 8; ++count; } // 'sum' is the position of the current pixel configuration in the 'TYPES' // array (in order 8-1-2-4, so we can use '>>2' to shift the column). var sum = (data[pos] ? 4 : 0) + (data[pos - lineSize] ? 8 : 0); for (j = 1; j < width; j++) { sum = (sum >> 2) + (data[pos + 1] ? 4 : 0) + (data[pos - lineSize + 1] ? 8 : 0); if (POINT_TYPES[sum]) { points[j0 + j] = POINT_TYPES[sum]; ++count; } pos++; } if (data[pos - lineSize] !== data[pos]) { points[j0 + j] = data[pos] ? 2 : 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } } pos = lineSize * (height - 1); j0 = i * width1; if (data[pos] !== 0) { points[j0] = 8; ++count; } for (j = 1; j < width; j++) { if (data[pos] !== data[pos + 1]) { points[j0 + j] = data[pos] ? 4 : 8; ++count; } pos++; } if (data[pos] !== 0) { points[j0 + j] = 4; ++count; } if (count > POINT_TO_PROCESS_LIMIT) { return null; } // building outlines var steps = new Int32Array([0, width1, -1, 0, -width1, 0, 0, 0, 1]); var outlines = []; for (i = 0; count && i <= height; i++) { var p = i * width1; var end = p + width; while (p < end && !points[p]) { p++; } if (p === end) { continue; } var coords = [p % width1, i]; var type = points[p], p0 = p, pp; do { var step = steps[type]; do { p += step; } while (!points[p]); pp = points[p]; if (pp !== 5 && pp !== 10) { // set new direction type = pp; // delete mark points[p] = 0; } else { // type is 5 or 10, ie, a crossing // set new direction type = pp & ((0x33 * type) >> 4); // set new type for "future hit" points[p] &= (type >> 2 | type << 2); } coords.push(p % width1); coords.push((p / width1) | 0); --count; } while (p0 !== p); outlines.push(coords); --i; } var drawOutline = function(c) { c.save(); // the path shall be painted in [0..1]x[0..1] space c.scale(1 / width, -1 / height); c.translate(0, -height); c.beginPath(); for (var i = 0, ii = outlines.length; i < ii; i++) { var o = outlines[i]; c.moveTo(o[0], o[1]); for (var j = 2, jj = o.length; j < jj; j += 2) { c.lineTo(o[j], o[j+1]); } } c.fill(); c.beginPath(); c.restore(); }; return drawOutline; } var CanvasExtraState = (function CanvasExtraStateClosure() { function CanvasExtraState(old) { // Are soft masks and alpha values shapes or opacities? this.alphaIsShape = false; this.fontSize = 0; this.fontSizeScale = 1; this.textMatrix = IDENTITY_MATRIX; this.textMatrixScale = 1; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRenderingMode = TextRenderingMode.FILL; this.textRise = 0; // Default fore and background colors this.fillColor = '#000000'; this.strokeColor = '#000000'; this.patternFill = false; // Note: fill alpha applies to all non-stroking operations this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.activeSMask = null; // nonclonable field (see the save method below) this.old = old; } CanvasExtraState.prototype = { clone: function CanvasExtraState_clone() { return Object.create(this); }, setCurrentPoint: function CanvasExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return CanvasExtraState; })(); var CanvasGraphics = (function CanvasGraphicsClosure() { // Defines the time the executeOperatorList is going to be executing // before it stops and shedules a continue of execution. var EXECUTION_TIME = 15; // Defines the number of steps before checking the execution time var EXECUTION_STEPS = 10; function CanvasGraphics(canvasCtx, commonObjs, objs, imageLayer) { this.ctx = canvasCtx; this.current = new CanvasExtraState(); this.stateStack = []; this.pendingClip = null; this.pendingEOFill = false; this.res = null; this.xobjs = null; this.commonObjs = commonObjs; this.objs = objs; this.imageLayer = imageLayer; this.groupStack = []; this.processingType3 = null; // Patterns are painted relative to the initial page/form transform, see pdf // spec 8.7.2 NOTE 1. this.baseTransform = null; this.baseTransformStack = []; this.groupLevel = 0; this.smaskStack = []; this.smaskCounter = 0; this.tempSMask = null; this.cachedCanvases = new CachedCanvases(); if (canvasCtx) { // NOTE: if mozCurrentTransform is polyfilled, then the current state of // the transformation must already be set in canvasCtx._transformMatrix. addContextCurrentTransform(canvasCtx); } this.cachedGetSinglePixelWidth = null; } function putBinaryImageData(ctx, imgData) { if (typeof ImageData !== 'undefined' && imgData instanceof ImageData) { ctx.putImageData(imgData, 0, 0); return; } // Put the image data to the canvas in chunks, rather than putting the // whole image at once. This saves JS memory, because the ImageData object // is smaller. It also possibly saves C++ memory within the implementation // of putImageData(). (E.g. in Firefox we make two short-lived copies of // the data passed to putImageData()). |n| shouldn't be too small, however, // because too many putImageData() calls will slow things down. // // Note: as written, if the last chunk is partial, the putImageData() call // will (conceptually) put pixels past the bounds of the canvas. But // that's ok; any such pixels are ignored. var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0, destPos; var src = imgData.data; var dest = chunkImgData.data; var i, j, thisChunkHeight, elemsInThisChunk; // There are multiple forms in which the pixel data can be passed, and // imgData.kind tells us which one this is. if (imgData.kind === ImageKind.GRAYSCALE_1BPP) { // Grayscale, 1 bit per pixel (i.e. black-and-white). var srcLength = src.byteLength; var dest32 = PDFJS.hasCanvasTypedArrays ? new Uint32Array(dest.buffer) : new Uint32ArrayView(dest); var dest32DataLength = dest32.length; var fullSrcDiff = (width + 7) >> 3; var white = 0xFFFFFFFF; var black = (PDFJS.isLittleEndian || !PDFJS.hasCanvasTypedArrays) ? 0xFF000000 : 0x000000FF; for (i = 0; i < totalChunks; i++) { thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; destPos = 0; for (j = 0; j < thisChunkHeight; j++) { var srcDiff = srcLength - srcPos; var k = 0; var kEnd = (srcDiff > fullSrcDiff) ? width : srcDiff * 8 - 7; var kEndUnrolled = kEnd & ~7; var mask = 0; var srcByte = 0; for (; k < kEndUnrolled; k += 8) { srcByte = src[srcPos++]; dest32[destPos++] = (srcByte & 128) ? white : black; dest32[destPos++] = (srcByte & 64) ? white : black; dest32[destPos++] = (srcByte & 32) ? white : black; dest32[destPos++] = (srcByte & 16) ? white : black; dest32[destPos++] = (srcByte & 8) ? white : black; dest32[destPos++] = (srcByte & 4) ? white : black; dest32[destPos++] = (srcByte & 2) ? white : black; dest32[destPos++] = (srcByte & 1) ? white : black; } for (; k < kEnd; k++) { if (mask === 0) { srcByte = src[srcPos++]; mask = 128; } dest32[destPos++] = (srcByte & mask) ? white : black; mask >>= 1; } } // We ran out of input. Make all remaining pixels transparent. while (destPos < dest32DataLength) { dest32[destPos++] = 0; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else if (imgData.kind === ImageKind.RGBA_32BPP) { // RGBA, 32-bits per pixel. j = 0; elemsInThisChunk = width * FULL_CHUNK_HEIGHT * 4; for (i = 0; i < fullChunks; i++) { dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); srcPos += elemsInThisChunk; ctx.putImageData(chunkImgData, 0, j); j += FULL_CHUNK_HEIGHT; } if (i < totalChunks) { elemsInThisChunk = width * partialChunkHeight * 4; dest.set(src.subarray(srcPos, srcPos + elemsInThisChunk)); ctx.putImageData(chunkImgData, 0, j); } } else if (imgData.kind === ImageKind.RGB_24BPP) { // RGB, 24-bits per pixel. thisChunkHeight = FULL_CHUNK_HEIGHT; elemsInThisChunk = width * thisChunkHeight; for (i = 0; i < totalChunks; i++) { if (i >= fullChunks) { thisChunkHeight = partialChunkHeight; elemsInThisChunk = width * thisChunkHeight; } destPos = 0; for (j = elemsInThisChunk; j--;) { dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = src[srcPos++]; dest[destPos++] = 255; } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } else { error('bad image kind: ' + imgData.kind); } } function putBinaryImageMask(ctx, imgData) { var height = imgData.height, width = imgData.width; var partialChunkHeight = height % FULL_CHUNK_HEIGHT; var fullChunks = (height - partialChunkHeight) / FULL_CHUNK_HEIGHT; var totalChunks = partialChunkHeight === 0 ? fullChunks : fullChunks + 1; var chunkImgData = ctx.createImageData(width, FULL_CHUNK_HEIGHT); var srcPos = 0; var src = imgData.data; var dest = chunkImgData.data; for (var i = 0; i < totalChunks; i++) { var thisChunkHeight = (i < fullChunks) ? FULL_CHUNK_HEIGHT : partialChunkHeight; // Expand the mask so it can be used by the canvas. Any required // inversion has already been handled. var destPos = 3; // alpha component offset for (var j = 0; j < thisChunkHeight; j++) { var mask = 0; for (var k = 0; k < width; k++) { if (!mask) { var elem = src[srcPos++]; mask = 128; } dest[destPos] = (elem & mask) ? 0 : 255; destPos += 4; mask >>= 1; } } ctx.putImageData(chunkImgData, 0, i * FULL_CHUNK_HEIGHT); } } function copyCtxState(sourceCtx, destCtx) { var properties = ['strokeStyle', 'fillStyle', 'fillRule', 'globalAlpha', 'lineWidth', 'lineCap', 'lineJoin', 'miterLimit', 'globalCompositeOperation', 'font']; for (var i = 0, ii = properties.length; i < ii; i++) { var property = properties[i]; if (sourceCtx[property] !== undefined) { destCtx[property] = sourceCtx[property]; } } if (sourceCtx.setLineDash !== undefined) { destCtx.setLineDash(sourceCtx.getLineDash()); destCtx.lineDashOffset = sourceCtx.lineDashOffset; } else if (sourceCtx.mozDashOffset !== undefined) { destCtx.mozDash = sourceCtx.mozDash; destCtx.mozDashOffset = sourceCtx.mozDashOffset; } } function composeSMaskBackdrop(bytes, r0, g0, b0) { var length = bytes.length; for (var i = 3; i < length; i += 4) { var alpha = bytes[i]; if (alpha === 0) { bytes[i - 3] = r0; bytes[i - 2] = g0; bytes[i - 1] = b0; } else if (alpha < 255) { var alpha_ = 255 - alpha; bytes[i - 3] = (bytes[i - 3] * alpha + r0 * alpha_) >> 8; bytes[i - 2] = (bytes[i - 2] * alpha + g0 * alpha_) >> 8; bytes[i - 1] = (bytes[i - 1] * alpha + b0 * alpha_) >> 8; } } } function composeSMaskAlpha(maskData, layerData, transferMap) { var length = maskData.length; var scale = 1 / 255; for (var i = 3; i < length; i += 4) { var alpha = transferMap ? transferMap[maskData[i]] : maskData[i]; layerData[i] = (layerData[i] * alpha * scale) | 0; } } function composeSMaskLuminosity(maskData, layerData, transferMap) { var length = maskData.length; for (var i = 3; i < length; i += 4) { var y = (maskData[i - 3] * 77) + // * 0.3 / 255 * 0x10000 (maskData[i - 2] * 152) + // * 0.59 .... (maskData[i - 1] * 28); // * 0.11 .... layerData[i] = transferMap ? (layerData[i] * transferMap[y >> 8]) >> 8 : (layerData[i] * y) >> 16; } } function genericComposeSMask(maskCtx, layerCtx, width, height, subtype, backdrop, transferMap) { var hasBackdrop = !!backdrop; var r0 = hasBackdrop ? backdrop[0] : 0; var g0 = hasBackdrop ? backdrop[1] : 0; var b0 = hasBackdrop ? backdrop[2] : 0; var composeFn; if (subtype === 'Luminosity') { composeFn = composeSMaskLuminosity; } else { composeFn = composeSMaskAlpha; } // processing image in chunks to save memory var PIXELS_TO_PROCESS = 1048576; var chunkSize = Math.min(height, Math.ceil(PIXELS_TO_PROCESS / width)); for (var row = 0; row < height; row += chunkSize) { var chunkHeight = Math.min(chunkSize, height - row); var maskData = maskCtx.getImageData(0, row, width, chunkHeight); var layerData = layerCtx.getImageData(0, row, width, chunkHeight); if (hasBackdrop) { composeSMaskBackdrop(maskData.data, r0, g0, b0); } composeFn(maskData.data, layerData.data, transferMap); maskCtx.putImageData(layerData, 0, row); } } function composeSMask(ctx, smask, layerCtx) { var mask = smask.canvas; var maskCtx = smask.context; ctx.setTransform(smask.scaleX, 0, 0, smask.scaleY, smask.offsetX, smask.offsetY); var backdrop = smask.backdrop || null; if (!smask.transferMap && WebGLUtils.isEnabled) { var composed = WebGLUtils.composeSMask(layerCtx.canvas, mask, {subtype: smask.subtype, backdrop: backdrop}); ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(composed, smask.offsetX, smask.offsetY); return; } genericComposeSMask(maskCtx, layerCtx, mask.width, mask.height, smask.subtype, backdrop, smask.transferMap); ctx.drawImage(mask, 0, 0); } var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var NORMAL_CLIP = {}; var EO_CLIP = {}; CanvasGraphics.prototype = { beginDrawing: function CanvasGraphics_beginDrawing(transform, viewport, transparency) { // For pdfs that use blend modes we have to clear the canvas else certain // blend modes can look wrong since we'd be blending with a white // backdrop. The problem with a transparent backdrop though is we then // don't get sub pixel anti aliasing on text, creating temporary // transparent canvas when we have blend modes. var width = this.ctx.canvas.width; var height = this.ctx.canvas.height; this.ctx.save(); this.ctx.fillStyle = 'rgb(255, 255, 255)'; this.ctx.fillRect(0, 0, width, height); this.ctx.restore(); if (transparency) { var transparentCanvas = this.cachedCanvases.getCanvas( 'transparent', width, height, true); this.compositeCtx = this.ctx; this.transparentCanvas = transparentCanvas.canvas; this.ctx = transparentCanvas.context; this.ctx.save(); // The transform can be applied before rendering, transferring it to // the new canvas. this.ctx.transform.apply(this.ctx, this.compositeCtx.mozCurrentTransform); } this.ctx.save(); if (transform) { this.ctx.transform.apply(this.ctx, transform); } this.ctx.transform.apply(this.ctx, viewport.transform); this.baseTransform = this.ctx.mozCurrentTransform.slice(); if (this.imageLayer) { this.imageLayer.beginLayout(); } }, executeOperatorList: function CanvasGraphics_executeOperatorList( operatorList, executionStartIdx, continueCallback, stepper) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var i = executionStartIdx || 0; var argsArrayLen = argsArray.length; // Sometimes the OperatorList to execute is empty. if (argsArrayLen === i) { return i; } var chunkOperations = (argsArrayLen - i > EXECUTION_STEPS && typeof continueCallback === 'function'); var endTime = chunkOperations ? Date.now() + EXECUTION_TIME : 0; var steps = 0; var commonObjs = this.commonObjs; var objs = this.objs; var fnId; while (true) { if (stepper !== undefined && i === stepper.nextBreakPoint) { stepper.breakIt(i, continueCallback); return i; } fnId = fnArray[i]; if (fnId !== OPS.dependency) { this[fnId].apply(this, argsArray[i]); } else { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var depObjId = deps[n]; var common = depObjId[0] === 'g' && depObjId[1] === '_'; var objsPool = common ? commonObjs : objs; // If the promise isn't resolved yet, add the continueCallback // to the promise and bail out. if (!objsPool.isResolved(depObjId)) { objsPool.get(depObjId, continueCallback); return i; } } } i++; // If the entire operatorList was executed, stop as were done. if (i === argsArrayLen) { return i; } // If the execution took longer then a certain amount of time and // `continueCallback` is specified, interrupt the execution. if (chunkOperations && ++steps > EXECUTION_STEPS) { if (Date.now() > endTime) { continueCallback(); return i; } steps = 0; } // If the operatorList isn't executed completely yet OR the execution // time was short enough, do another execution round. } }, endDrawing: function CanvasGraphics_endDrawing() { this.ctx.restore(); if (this.transparentCanvas) { this.ctx = this.compositeCtx; this.ctx.drawImage(this.transparentCanvas, 0, 0); this.transparentCanvas = null; } this.cachedCanvases.clear(); WebGLUtils.clear(); if (this.imageLayer) { this.imageLayer.endLayout(); } }, // Graphics state setLineWidth: function CanvasGraphics_setLineWidth(width) { this.current.lineWidth = width; this.ctx.lineWidth = width; }, setLineCap: function CanvasGraphics_setLineCap(style) { this.ctx.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function CanvasGraphics_setLineJoin(style) { this.ctx.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function CanvasGraphics_setMiterLimit(limit) { this.ctx.miterLimit = limit; }, setDash: function CanvasGraphics_setDash(dashArray, dashPhase) { var ctx = this.ctx; if (ctx.setLineDash !== undefined) { ctx.setLineDash(dashArray); ctx.lineDashOffset = dashPhase; } else { ctx.mozDash = dashArray; ctx.mozDashOffset = dashPhase; } }, setRenderingIntent: function CanvasGraphics_setRenderingIntent(intent) { // Maybe if we one day fully support color spaces this will be important // for now we can ignore. // TODO set rendering intent? }, setFlatness: function CanvasGraphics_setFlatness(flatness) { // There's no way to control this with canvas, but we can safely ignore. // TODO set flatness? }, setGState: function CanvasGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': this.setRenderingIntent(value); break; case 'FL': this.setFlatness(value); break; case 'Font': this.setFont(value[0], value[1]); break; case 'CA': this.current.strokeAlpha = state[1]; break; case 'ca': this.current.fillAlpha = state[1]; this.ctx.globalAlpha = state[1]; break; case 'BM': if (value && value.name && (value.name !== 'Normal')) { var mode = value.name.replace(/([A-Z])/g, function(c) { return '-' + c.toLowerCase(); } ).substring(1); this.ctx.globalCompositeOperation = mode; if (this.ctx.globalCompositeOperation !== mode) { warn('globalCompositeOperation "' + mode + '" is not supported'); } } else { this.ctx.globalCompositeOperation = 'source-over'; } break; case 'SMask': if (this.current.activeSMask) { this.endSMaskGroup(); } this.current.activeSMask = value ? this.tempSMask : null; if (this.current.activeSMask) { this.beginSMaskGroup(); } this.tempSMask = null; break; } } }, beginSMaskGroup: function CanvasGraphics_beginSMaskGroup() { var activeSMask = this.current.activeSMask; var drawnWidth = activeSMask.canvas.width; var drawnHeight = activeSMask.canvas.height; var cacheId = 'smaskGroupAt' + this.groupLevel; var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var currentCtx = this.ctx; var currentTransform = currentCtx.mozCurrentTransform; this.ctx.save(); var groupCtx = scratchCanvas.context; groupCtx.scale(1 / activeSMask.scaleX, 1 / activeSMask.scaleY); groupCtx.translate(-activeSMask.offsetX, -activeSMask.offsetY); groupCtx.transform.apply(groupCtx, currentTransform); copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endSMaskGroup: function CanvasGraphics_endSMaskGroup() { var groupCtx = this.ctx; this.groupLevel--; this.ctx = this.groupStack.pop(); composeSMask(this.ctx, this.current.activeSMask, groupCtx); this.ctx.restore(); copyCtxState(groupCtx, this.ctx); }, save: function CanvasGraphics_save() { this.ctx.save(); var old = this.current; this.stateStack.push(old); this.current = old.clone(); this.current.activeSMask = null; }, restore: function CanvasGraphics_restore() { if (this.stateStack.length !== 0) { if (this.current.activeSMask !== null) { this.endSMaskGroup(); } this.current = this.stateStack.pop(); this.ctx.restore(); // Ensure that the clipping path is reset (fixes issue6413.pdf). this.pendingClip = null; this.cachedGetSinglePixelWidth = null; } }, transform: function CanvasGraphics_transform(a, b, c, d, e, f) { this.ctx.transform(a, b, c, d, e, f); this.cachedGetSinglePixelWidth = null; }, // Path constructPath: function CanvasGraphics_constructPath(ops, args) { var ctx = this.ctx; var current = this.current; var x = current.x, y = current.y; for (var i = 0, j = 0, ii = ops.length; i < ii; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; if (width === 0) { width = this.getSinglePixelWidth(); } if (height === 0) { height = this.getSinglePixelWidth(); } var xw = x + width; var yh = y + height; this.ctx.moveTo(x, y); this.ctx.lineTo(xw, y); this.ctx.lineTo(xw, yh); this.ctx.lineTo(x, yh); this.ctx.lineTo(x, y); this.ctx.closePath(); break; case OPS.moveTo: x = args[j++]; y = args[j++]; ctx.moveTo(x, y); break; case OPS.lineTo: x = args[j++]; y = args[j++]; ctx.lineTo(x, y); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; ctx.bezierCurveTo(args[j], args[j + 1], args[j + 2], args[j + 3], x, y); j += 6; break; case OPS.curveTo2: ctx.bezierCurveTo(x, y, args[j], args[j + 1], args[j + 2], args[j + 3]); x = args[j + 2]; y = args[j + 3]; j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; ctx.bezierCurveTo(args[j], args[j + 1], x, y, x, y); j += 4; break; case OPS.closePath: ctx.closePath(); break; } } current.setCurrentPoint(x, y); }, closePath: function CanvasGraphics_closePath() { this.ctx.closePath(); }, stroke: function CanvasGraphics_stroke(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var strokeColor = this.current.strokeColor; // Prevent drawing too thin lines by enforcing a minimum line width. ctx.lineWidth = Math.max(this.getSinglePixelWidth() * MIN_WIDTH_FACTOR, this.current.lineWidth); // For stroke we want to temporarily change the global alpha to the // stroking alpha. ctx.globalAlpha = this.current.strokeAlpha; if (strokeColor && strokeColor.hasOwnProperty('type') && strokeColor.type === 'Pattern') { // for patterns, we transform to pattern space, calculate // the pattern, call stroke, and restore to user space ctx.save(); ctx.strokeStyle = strokeColor.getPattern(ctx, this); ctx.stroke(); ctx.restore(); } else { ctx.stroke(); } if (consumePath) { this.consumePath(); } // Restore the global alpha to the fill alpha ctx.globalAlpha = this.current.fillAlpha; }, closeStroke: function CanvasGraphics_closeStroke() { this.closePath(); this.stroke(); }, fill: function CanvasGraphics_fill(consumePath) { consumePath = typeof consumePath !== 'undefined' ? consumePath : true; var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var needRestore = false; if (isPatternFill) { ctx.save(); if (this.baseTransform) { ctx.setTransform.apply(ctx, this.baseTransform); } ctx.fillStyle = fillColor.getPattern(ctx, this); needRestore = true; } if (this.pendingEOFill) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.fill(); ctx.mozFillRule = 'nonzero'; } else { ctx.fill('evenodd'); } this.pendingEOFill = false; } else { ctx.fill(); } if (needRestore) { ctx.restore(); } if (consumePath) { this.consumePath(); } }, eoFill: function CanvasGraphics_eoFill() { this.pendingEOFill = true; this.fill(); }, fillStroke: function CanvasGraphics_fillStroke() { this.fill(false); this.stroke(false); this.consumePath(); }, eoFillStroke: function CanvasGraphics_eoFillStroke() { this.pendingEOFill = true; this.fillStroke(); }, closeFillStroke: function CanvasGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, closeEOFillStroke: function CanvasGraphics_closeEOFillStroke() { this.pendingEOFill = true; this.closePath(); this.fillStroke(); }, endPath: function CanvasGraphics_endPath() { this.consumePath(); }, // Clipping clip: function CanvasGraphics_clip() { this.pendingClip = NORMAL_CLIP; }, eoClip: function CanvasGraphics_eoClip() { this.pendingClip = EO_CLIP; }, // Text beginText: function CanvasGraphics_beginText() { this.current.textMatrix = IDENTITY_MATRIX; this.current.textMatrixScale = 1; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, endText: function CanvasGraphics_endText() { var paths = this.pendingTextPaths; var ctx = this.ctx; if (paths === undefined) { ctx.beginPath(); return; } ctx.save(); ctx.beginPath(); for (var i = 0; i < paths.length; i++) { var path = paths[i]; ctx.setTransform.apply(ctx, path.transform); ctx.translate(path.x, path.y); path.addToPath(ctx, path.fontSize); } ctx.restore(); ctx.clip(); ctx.beginPath(); delete this.pendingTextPaths; }, setCharSpacing: function CanvasGraphics_setCharSpacing(spacing) { this.current.charSpacing = spacing; }, setWordSpacing: function CanvasGraphics_setWordSpacing(spacing) { this.current.wordSpacing = spacing; }, setHScale: function CanvasGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setLeading: function CanvasGraphics_setLeading(leading) { this.current.leading = -leading; }, setFont: function CanvasGraphics_setFont(fontRefName, size) { var fontObj = this.commonObjs.get(fontRefName); var current = this.current; if (!fontObj) { error('Can\'t find font for ' + fontRefName); } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); // A valid matrix needs all main diagonal elements to be non-zero // This also ensures we bypass FF bugzilla bug #719844. if (current.fontMatrix[0] === 0 || current.fontMatrix[3] === 0) { warn('Invalid font matrix for font ' + fontRefName); } // The spec for Tf (setFont) says that 'size' specifies the font 'scale', // and in some docs this can be negative (inverted x-y axes). if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } this.current.font = fontObj; this.current.fontSize = size; if (fontObj.isType3Font) { return; // we don't need ctx.font for Type3 fonts } var name = fontObj.loadedName || 'sans-serif'; var bold = fontObj.black ? (fontObj.bold ? '900' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; var typeface = '"' + name + '", ' + fontObj.fallbackName; // Some font backends cannot handle fonts below certain size. // Keeping the font at minimal size and using the fontSizeScale to change // the current transformation matrix before the fillText/strokeText. // See https://bugzilla.mozilla.org/show_bug.cgi?id=726227 var browserFontSize = size < MIN_FONT_SIZE ? MIN_FONT_SIZE : size > MAX_FONT_SIZE ? MAX_FONT_SIZE : size; this.current.fontSizeScale = size / browserFontSize; var rule = italic + ' ' + bold + ' ' + browserFontSize + 'px ' + typeface; this.ctx.font = rule; }, setTextRenderingMode: function CanvasGraphics_setTextRenderingMode(mode) { this.current.textRenderingMode = mode; }, setTextRise: function CanvasGraphics_setTextRise(rise) { this.current.textRise = rise; }, moveText: function CanvasGraphics_moveText(x, y) { this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; }, setLeadingMoveText: function CanvasGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, setTextMatrix: function CanvasGraphics_setTextMatrix(a, b, c, d, e, f) { this.current.textMatrix = [a, b, c, d, e, f]; this.current.textMatrixScale = Math.sqrt(a * a + b * b); this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; }, nextLine: function CanvasGraphics_nextLine() { this.moveText(0, this.current.leading); }, paintChar: function CanvasGraphics_paintChar(character, x, y) { var ctx = this.ctx; var current = this.current; var font = current.font; var textRenderingMode = current.textRenderingMode; var fontSize = current.fontSize / current.fontSizeScale; var fillStrokeMode = textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; var isAddToPathSet = !!(textRenderingMode & TextRenderingMode.ADD_TO_PATH_FLAG); var addToPath; if (font.disableFontFace || isAddToPathSet) { addToPath = font.getPathGenerator(this.commonObjs, character); } if (font.disableFontFace) { ctx.save(); ctx.translate(x, y); ctx.beginPath(); addToPath(ctx, fontSize); if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fill(); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.stroke(); } ctx.restore(); } else { if (fillStrokeMode === TextRenderingMode.FILL || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.fillText(character, x, y); } if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { ctx.strokeText(character, x, y); } } if (isAddToPathSet) { var paths = this.pendingTextPaths || (this.pendingTextPaths = []); paths.push({ transform: ctx.mozCurrentTransform, x: x, y: y, fontSize: fontSize, addToPath: addToPath }); } }, get isFontSubpixelAAEnabled() { // Checks if anti-aliasing is enabled when scaled text is painted. // On Windows GDI scaled fonts looks bad. var ctx = document.createElement('canvas').getContext('2d'); ctx.scale(1.5, 1); ctx.fillText('I', 0, 10); var data = ctx.getImageData(0, 0, 10, 10).data; var enabled = false; for (var i = 3; i < data.length; i += 4) { if (data[i] > 0 && data[i] < 255) { enabled = true; break; } } return shadow(this, 'isFontSubpixelAAEnabled', enabled); }, showText: function CanvasGraphics_showText(glyphs) { var current = this.current; var font = current.font; if (font.isType3Font) { return this.showType3Text(glyphs); } var fontSize = current.fontSize; if (fontSize === 0) { return; } var ctx = this.ctx; var fontSizeScale = current.fontSizeScale; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var spacingDir = vertical ? 1 : -1; var defaultVMetrics = font.defaultVMetrics; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var simpleFillText = current.textRenderingMode === TextRenderingMode.FILL && !font.disableFontFace; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y + current.textRise); if (fontDirection > 0) { ctx.scale(textHScale, -1); } else { ctx.scale(textHScale, 1); } var lineWidth = current.lineWidth; var scale = current.textMatrixScale; if (scale === 0 || lineWidth === 0) { var fillStrokeMode = current.textRenderingMode & TextRenderingMode.FILL_STROKE_MASK; if (fillStrokeMode === TextRenderingMode.STROKE || fillStrokeMode === TextRenderingMode.FILL_STROKE) { this.cachedGetSinglePixelWidth = null; lineWidth = this.getSinglePixelWidth() * MIN_WIDTH_FACTOR; } } else { lineWidth /= scale; } if (fontSizeScale !== 1.0) { ctx.scale(fontSizeScale, fontSizeScale); lineWidth /= fontSizeScale; } ctx.lineWidth = lineWidth; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (isNum(glyph)) { x += spacingDir * glyph * fontSize / 1000; continue; } var restoreNeeded = false; var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var character = glyph.fontChar; var accent = glyph.accent; var scaledX, scaledY, scaledAccentX, scaledAccentY; var width = glyph.width; if (vertical) { var vmetric, vx, vy; vmetric = glyph.vmetric || defaultVMetrics; vx = glyph.vmetric ? vmetric[1] : width * 0.5; vx = -vx * widthAdvanceScale; vy = vmetric[2] * widthAdvanceScale; width = vmetric ? -vmetric[0] : width; scaledX = vx / fontSizeScale; scaledY = (x + vy) / fontSizeScale; } else { scaledX = x / fontSizeScale; scaledY = 0; } if (font.remeasure && width > 0) { // Some standard fonts may not have the exact width: rescale per // character if measured width is greater than expected glyph width // and subpixel-aa is enabled, otherwise just center the glyph. var measuredWidth = ctx.measureText(character).width * 1000 / fontSize * fontSizeScale; if (width < measuredWidth && this.isFontSubpixelAAEnabled) { var characterScaleX = width / measuredWidth; restoreNeeded = true; ctx.save(); ctx.scale(characterScaleX, 1); scaledX /= characterScaleX; } else if (width !== measuredWidth) { scaledX += (width - measuredWidth) / 2000 * fontSize / fontSizeScale; } } if (simpleFillText && !accent) { // common case ctx.fillText(character, scaledX, scaledY); } else { this.paintChar(character, scaledX, scaledY); if (accent) { scaledAccentX = scaledX + accent.offset.x / fontSizeScale; scaledAccentY = scaledY - accent.offset.y / fontSizeScale; this.paintChar(accent.fontChar, scaledAccentX, scaledAccentY); } } var charWidth = width * widthAdvanceScale + spacing * fontDirection; x += charWidth; if (restoreNeeded) { ctx.restore(); } } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } ctx.restore(); }, showType3Text: function CanvasGraphics_showType3Text(glyphs) { // Type3 fonts - each glyph is a "mini-PDF" var ctx = this.ctx; var current = this.current; var font = current.font; var fontSize = current.fontSize; var fontDirection = current.fontDirection; var spacingDir = font.vertical ? 1 : -1; var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var textHScale = current.textHScale * fontDirection; var fontMatrix = current.fontMatrix || FONT_IDENTITY_MATRIX; var glyphsLength = glyphs.length; var isTextInvisible = current.textRenderingMode === TextRenderingMode.INVISIBLE; var i, glyph, width, spacingLength; if (isTextInvisible || fontSize === 0) { return; } this.cachedGetSinglePixelWidth = null; ctx.save(); ctx.transform.apply(ctx, current.textMatrix); ctx.translate(current.x, current.y); ctx.scale(textHScale, fontDirection); for (i = 0; i < glyphsLength; ++i) { glyph = glyphs[i]; if (isNum(glyph)) { spacingLength = spacingDir * glyph * fontSize / 1000; this.ctx.translate(spacingLength, 0); current.x += spacingLength * textHScale; continue; } var spacing = (glyph.isSpace ? wordSpacing : 0) + charSpacing; var operatorList = font.charProcOperatorList[glyph.operatorListId]; if (!operatorList) { warn('Type3 character \"' + glyph.operatorListId + '\" is not available'); continue; } this.processingType3 = glyph; this.save(); ctx.scale(fontSize, fontSize); ctx.transform.apply(ctx, fontMatrix); this.executeOperatorList(operatorList); this.restore(); var transformed = Util.applyTransform([glyph.width, 0], fontMatrix); width = transformed[0] * fontSize + spacing; ctx.translate(width, 0); current.x += width * textHScale; } ctx.restore(); this.processingType3 = null; }, // Type3 fonts setCharWidth: function CanvasGraphics_setCharWidth(xWidth, yWidth) { // We can safely ignore this since the width should be the same // as the width in the Widths array. }, setCharWidthAndBounds: function CanvasGraphics_setCharWidthAndBounds(xWidth, yWidth, llx, lly, urx, ury) { // TODO According to the spec we're also suppose to ignore any operators // that set color or include images while processing this type3 font. this.ctx.rect(llx, lly, urx - llx, ury - lly); this.clip(); this.endPath(); }, // Color getColorN_Pattern: function CanvasGraphics_getColorN_Pattern(IR) { var pattern; if (IR[0] === 'TilingPattern') { var color = IR[1]; var baseTransform = this.baseTransform || this.ctx.mozCurrentTransform.slice(); pattern = new TilingPattern(IR, color, this.ctx, this.objs, this.commonObjs, baseTransform); } else { pattern = getShadingPatternFromIR(IR); } return pattern; }, setStrokeColorN: function CanvasGraphics_setStrokeColorN(/*...*/) { this.current.strokeColor = this.getColorN_Pattern(arguments); }, setFillColorN: function CanvasGraphics_setFillColorN(/*...*/) { this.current.fillColor = this.getColorN_Pattern(arguments); this.current.patternFill = true; }, setStrokeRGBColor: function CanvasGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.strokeStyle = color; this.current.strokeColor = color; }, setFillRGBColor: function CanvasGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.ctx.fillStyle = color; this.current.fillColor = color; this.current.patternFill = false; }, shadingFill: function CanvasGraphics_shadingFill(patternIR) { var ctx = this.ctx; this.save(); var pattern = getShadingPatternFromIR(patternIR); ctx.fillStyle = pattern.getPattern(ctx, this, true); var inv = ctx.mozCurrentTransformInverse; if (inv) { var canvas = ctx.canvas; var width = canvas.width; var height = canvas.height; var bl = Util.applyTransform([0, 0], inv); var br = Util.applyTransform([0, height], inv); var ul = Util.applyTransform([width, 0], inv); var ur = Util.applyTransform([width, height], inv); var x0 = Math.min(bl[0], br[0], ul[0], ur[0]); var y0 = Math.min(bl[1], br[1], ul[1], ur[1]); var x1 = Math.max(bl[0], br[0], ul[0], ur[0]); var y1 = Math.max(bl[1], br[1], ul[1], ur[1]); this.ctx.fillRect(x0, y0, x1 - x0, y1 - y0); } else { // HACK to draw the gradient onto an infinite rectangle. // PDF gradients are drawn across the entire image while // Canvas only allows gradients to be drawn in a rectangle // The following bug should allow us to remove this. // https://bugzilla.mozilla.org/show_bug.cgi?id=664884 this.ctx.fillRect(-1e10, -1e10, 2e10, 2e10); } this.restore(); }, // Images beginInlineImage: function CanvasGraphics_beginInlineImage() { error('Should not call beginInlineImage'); }, beginImageData: function CanvasGraphics_beginImageData() { error('Should not call beginImageData'); }, paintFormXObjectBegin: function CanvasGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); this.baseTransformStack.push(this.baseTransform); if (isArray(matrix) && 6 === matrix.length) { this.transform.apply(this, matrix); } this.baseTransform = this.ctx.mozCurrentTransform; if (isArray(bbox) && 4 === bbox.length) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; this.ctx.rect(bbox[0], bbox[1], width, height); this.clip(); this.endPath(); } }, paintFormXObjectEnd: function CanvasGraphics_paintFormXObjectEnd() { this.restore(); this.baseTransform = this.baseTransformStack.pop(); }, beginGroup: function CanvasGraphics_beginGroup(group) { this.save(); var currentCtx = this.ctx; // TODO non-isolated groups - according to Rik at adobe non-isolated // group results aren't usually that different and they even have tools // that ignore this setting. Notes from Rik on implmenting: // - When you encounter an transparency group, create a new canvas with // the dimensions of the bbox // - copy the content from the previous canvas to the new canvas // - draw as usual // - remove the backdrop alpha: // alphaNew = 1 - (1 - alpha)/(1 - alphaBackdrop) with 'alpha' the alpha // value of your transparency group and 'alphaBackdrop' the alpha of the // backdrop // - remove background color: // colorNew = color - alphaNew *colorBackdrop /(1 - alphaNew) if (!group.isolated) { info('TODO: Support non-isolated groups.'); } // TODO knockout - supposedly possible with the clever use of compositing // modes. if (group.knockout) { warn('Knockout groups not supported.'); } var currentTransform = currentCtx.mozCurrentTransform; if (group.matrix) { currentCtx.transform.apply(currentCtx, group.matrix); } assert(group.bbox, 'Bounding box is required.'); // Based on the current transform figure out how big the bounding box // will actually be. var bounds = Util.getAxialAlignedBoundingBox( group.bbox, currentCtx.mozCurrentTransform); // Clip the bounding box to the current canvas. var canvasBounds = [0, 0, currentCtx.canvas.width, currentCtx.canvas.height]; bounds = Util.intersect(bounds, canvasBounds) || [0, 0, 0, 0]; // Use ceil in case we're between sizes so we don't create canvas that is // too small and make the canvas at least 1x1 pixels. var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var drawnWidth = Math.max(Math.ceil(bounds[2]) - offsetX, 1); var drawnHeight = Math.max(Math.ceil(bounds[3]) - offsetY, 1); var scaleX = 1, scaleY = 1; if (drawnWidth > MAX_GROUP_SIZE) { scaleX = drawnWidth / MAX_GROUP_SIZE; drawnWidth = MAX_GROUP_SIZE; } if (drawnHeight > MAX_GROUP_SIZE) { scaleY = drawnHeight / MAX_GROUP_SIZE; drawnHeight = MAX_GROUP_SIZE; } var cacheId = 'groupAt' + this.groupLevel; if (group.smask) { // Using two cache entries is case if masks are used one after another. cacheId += '_smask_' + ((this.smaskCounter++) % 2); } var scratchCanvas = this.cachedCanvases.getCanvas( cacheId, drawnWidth, drawnHeight, true); var groupCtx = scratchCanvas.context; // Since we created a new canvas that is just the size of the bounding box // we have to translate the group ctx. groupCtx.scale(1 / scaleX, 1 / scaleY); groupCtx.translate(-offsetX, -offsetY); groupCtx.transform.apply(groupCtx, currentTransform); if (group.smask) { // Saving state and cached mask to be used in setGState. this.smaskStack.push({ canvas: scratchCanvas.canvas, context: groupCtx, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY, subtype: group.smask.subtype, backdrop: group.smask.backdrop, transferMap: group.smask.transferMap || null }); } else { // Setup the current ctx so when the group is popped we draw it at the // right location. currentCtx.setTransform(1, 0, 0, 1, 0, 0); currentCtx.translate(offsetX, offsetY); currentCtx.scale(scaleX, scaleY); } // The transparency group inherits all off the current graphics state // except the blend mode, soft mask, and alpha constants. copyCtxState(currentCtx, groupCtx); this.ctx = groupCtx; this.setGState([ ['BM', 'Normal'], ['ca', 1], ['CA', 1] ]); this.groupStack.push(currentCtx); this.groupLevel++; }, endGroup: function CanvasGraphics_endGroup(group) { this.groupLevel--; var groupCtx = this.ctx; this.ctx = this.groupStack.pop(); // Turn off image smoothing to avoid sub pixel interpolation which can // look kind of blurry for some pdfs. if (this.ctx.imageSmoothingEnabled !== undefined) { this.ctx.imageSmoothingEnabled = false; } else { this.ctx.mozImageSmoothingEnabled = false; } if (group.smask) { this.tempSMask = this.smaskStack.pop(); } else { this.ctx.drawImage(groupCtx.canvas, 0, 0); } this.restore(); }, beginAnnotations: function CanvasGraphics_beginAnnotations() { this.save(); this.current = new CanvasExtraState(); }, endAnnotations: function CanvasGraphics_endAnnotations() { this.restore(); }, beginAnnotation: function CanvasGraphics_beginAnnotation(rect, transform, matrix) { this.save(); if (isArray(rect) && 4 === rect.length) { var width = rect[2] - rect[0]; var height = rect[3] - rect[1]; this.ctx.rect(rect[0], rect[1], width, height); this.clip(); this.endPath(); } this.transform.apply(this, transform); this.transform.apply(this, matrix); }, endAnnotation: function CanvasGraphics_endAnnotation() { this.restore(); }, paintJpegXObject: function CanvasGraphics_paintJpegXObject(objId, w, h) { var domImage = this.objs.get(objId); if (!domImage) { warn('Dependent image isn\'t ready yet'); return; } this.save(); var ctx = this.ctx; // scale the image to the unit square ctx.scale(1 / w, -1 / h); ctx.drawImage(domImage, 0, 0, domImage.width, domImage.height, 0, -h, w, h); if (this.imageLayer) { var currentTransform = ctx.mozCurrentTransformInverse; var position = this.getCanvasPosition(0, 0); this.imageLayer.appendImage({ objId: objId, left: position[0], top: position[1], width: w / currentTransform[0], height: h / currentTransform[3] }); } this.restore(); }, paintImageMaskXObject: function CanvasGraphics_paintImageMaskXObject(img) { var ctx = this.ctx; var width = img.width, height = img.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var glyph = this.processingType3; if (COMPILE_TYPE3_GLYPHS && glyph && glyph.compiled === undefined) { if (width <= MAX_SIZE_TO_COMPILE && height <= MAX_SIZE_TO_COMPILE) { glyph.compiled = compileType3Glyph({data: img.data, width: width, height: height}); } else { glyph.compiled = null; } } if (glyph && glyph.compiled) { glyph.compiled(ctx); return; } var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, img); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); this.paintInlineImageXObject(maskCanvas.canvas); }, paintImageMaskXObjectRepeat: function CanvasGraphics_paintImageMaskXObjectRepeat(imgData, scaleX, scaleY, positions) { var width = imgData.width; var height = imgData.height; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, imgData); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); var ctx = this.ctx; for (var i = 0, ii = positions.length; i < ii; i += 2) { ctx.save(); ctx.transform(scaleX, 0, 0, scaleY, positions[i], positions[i + 1]); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageMaskXObjectGroup: function CanvasGraphics_paintImageMaskXObjectGroup(images) { var ctx = this.ctx; var fillColor = this.current.fillColor; var isPatternFill = this.current.patternFill; for (var i = 0, ii = images.length; i < ii; i++) { var image = images[i]; var width = image.width, height = image.height; var maskCanvas = this.cachedCanvases.getCanvas('maskCanvas', width, height); var maskCtx = maskCanvas.context; maskCtx.save(); putBinaryImageMask(maskCtx, image); maskCtx.globalCompositeOperation = 'source-in'; maskCtx.fillStyle = isPatternFill ? fillColor.getPattern(maskCtx, this) : fillColor; maskCtx.fillRect(0, 0, width, height); maskCtx.restore(); ctx.save(); ctx.transform.apply(ctx, image.transform); ctx.scale(1, -1); ctx.drawImage(maskCanvas.canvas, 0, 0, width, height, 0, -1, 1, 1); ctx.restore(); } }, paintImageXObject: function CanvasGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintImageXObjectRepeat: function CanvasGraphics_paintImageXObjectRepeat(objId, scaleX, scaleY, positions) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } var width = imgData.width; var height = imgData.height; var map = []; for (var i = 0, ii = positions.length; i < ii; i += 2) { map.push({transform: [scaleX, 0, 0, scaleY, positions[i], positions[i + 1]], x: 0, y: 0, w: width, h: height}); } this.paintInlineImageXObjectGroup(imgData, map); }, paintInlineImageXObject: function CanvasGraphics_paintInlineImageXObject(imgData) { var width = imgData.width; var height = imgData.height; var ctx = this.ctx; this.save(); // scale the image to the unit square ctx.scale(1 / width, -1 / height); var currentTransform = ctx.mozCurrentTransformInverse; var a = currentTransform[0], b = currentTransform[1]; var widthScale = Math.max(Math.sqrt(a * a + b * b), 1); var c = currentTransform[2], d = currentTransform[3]; var heightScale = Math.max(Math.sqrt(c * c + d * d), 1); var imgToPaint, tmpCanvas; // instanceof HTMLElement does not work in jsdom node.js module if (imgData instanceof HTMLElement || !imgData.data) { imgToPaint = imgData; } else { tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', width, height); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); imgToPaint = tmpCanvas.canvas; } var paintWidth = width, paintHeight = height; var tmpCanvasId = 'prescale1'; // Vertial or horizontal scaling shall not be more than 2 to not loose the // pixels during drawImage operation, painting on the temporary canvas(es) // that are twice smaller in size while ((widthScale > 2 && paintWidth > 1) || (heightScale > 2 && paintHeight > 1)) { var newWidth = paintWidth, newHeight = paintHeight; if (widthScale > 2 && paintWidth > 1) { newWidth = Math.ceil(paintWidth / 2); widthScale /= paintWidth / newWidth; } if (heightScale > 2 && paintHeight > 1) { newHeight = Math.ceil(paintHeight / 2); heightScale /= paintHeight / newHeight; } tmpCanvas = this.cachedCanvases.getCanvas(tmpCanvasId, newWidth, newHeight); tmpCtx = tmpCanvas.context; tmpCtx.clearRect(0, 0, newWidth, newHeight); tmpCtx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, 0, newWidth, newHeight); imgToPaint = tmpCanvas.canvas; paintWidth = newWidth; paintHeight = newHeight; tmpCanvasId = tmpCanvasId === 'prescale1' ? 'prescale2' : 'prescale1'; } ctx.drawImage(imgToPaint, 0, 0, paintWidth, paintHeight, 0, -height, width, height); if (this.imageLayer) { var position = this.getCanvasPosition(0, -height); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: width / currentTransform[0], height: height / currentTransform[3] }); } this.restore(); }, paintInlineImageXObjectGroup: function CanvasGraphics_paintInlineImageXObjectGroup(imgData, map) { var ctx = this.ctx; var w = imgData.width; var h = imgData.height; var tmpCanvas = this.cachedCanvases.getCanvas('inlineImage', w, h); var tmpCtx = tmpCanvas.context; putBinaryImageData(tmpCtx, imgData); for (var i = 0, ii = map.length; i < ii; i++) { var entry = map[i]; ctx.save(); ctx.transform.apply(ctx, entry.transform); ctx.scale(1, -1); ctx.drawImage(tmpCanvas.canvas, entry.x, entry.y, entry.w, entry.h, 0, -1, 1, 1); if (this.imageLayer) { var position = this.getCanvasPosition(entry.x, entry.y); this.imageLayer.appendImage({ imgData: imgData, left: position[0], top: position[1], width: w, height: h }); } ctx.restore(); } }, paintSolidColorImageMask: function CanvasGraphics_paintSolidColorImageMask() { this.ctx.fillRect(0, 0, 1, 1); }, paintXObject: function CanvasGraphics_paintXObject() { warn('Unsupported \'paintXObject\' command.'); }, // Marked content markPoint: function CanvasGraphics_markPoint(tag) { // TODO Marked content. }, markPointProps: function CanvasGraphics_markPointProps(tag, properties) { // TODO Marked content. }, beginMarkedContent: function CanvasGraphics_beginMarkedContent(tag) { // TODO Marked content. }, beginMarkedContentProps: function CanvasGraphics_beginMarkedContentProps( tag, properties) { // TODO Marked content. }, endMarkedContent: function CanvasGraphics_endMarkedContent() { // TODO Marked content. }, // Compatibility beginCompat: function CanvasGraphics_beginCompat() { // TODO ignore undefined operators (should we do that anyway?) }, endCompat: function CanvasGraphics_endCompat() { // TODO stop ignoring undefined operators }, // Helper functions consumePath: function CanvasGraphics_consumePath() { var ctx = this.ctx; if (this.pendingClip) { if (this.pendingClip === EO_CLIP) { if (ctx.mozFillRule !== undefined) { ctx.mozFillRule = 'evenodd'; ctx.clip(); ctx.mozFillRule = 'nonzero'; } else { ctx.clip('evenodd'); } } else { ctx.clip(); } this.pendingClip = null; } ctx.beginPath(); }, getSinglePixelWidth: function CanvasGraphics_getSinglePixelWidth(scale) { if (this.cachedGetSinglePixelWidth === null) { var inverse = this.ctx.mozCurrentTransformInverse; // max of the current horizontal and vertical scale this.cachedGetSinglePixelWidth = Math.sqrt(Math.max( (inverse[0] * inverse[0] + inverse[1] * inverse[1]), (inverse[2] * inverse[2] + inverse[3] * inverse[3]))); } return this.cachedGetSinglePixelWidth; }, getCanvasPosition: function CanvasGraphics_getCanvasPosition(x, y) { var transform = this.ctx.mozCurrentTransform; return [ transform[0] * x + transform[2] * y + transform[4], transform[1] * x + transform[3] * y + transform[5] ]; } }; for (var op in OPS) { CanvasGraphics.prototype[OPS[op]] = CanvasGraphics.prototype[op]; } return CanvasGraphics; })(); var WebGLUtils = (function WebGLUtilsClosure() { function loadShader(gl, code, shaderType) { var shader = gl.createShader(shaderType); gl.shaderSource(shader, code); gl.compileShader(shader); var compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { var errorMsg = gl.getShaderInfoLog(shader); throw new Error('Error during shader compilation: ' + errorMsg); } return shader; } function createVertexShader(gl, code) { return loadShader(gl, code, gl.VERTEX_SHADER); } function createFragmentShader(gl, code) { return loadShader(gl, code, gl.FRAGMENT_SHADER); } function createProgram(gl, shaders) { var program = gl.createProgram(); for (var i = 0, ii = shaders.length; i < ii; ++i) { gl.attachShader(program, shaders[i]); } gl.linkProgram(program); var linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { var errorMsg = gl.getProgramInfoLog(program); throw new Error('Error during program linking: ' + errorMsg); } return program; } function createTexture(gl, image, textureId) { gl.activeTexture(textureId); var texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, image); return texture; } var currentGL, currentCanvas; function generateGL() { if (currentGL) { return; } currentCanvas = document.createElement('canvas'); currentGL = currentCanvas.getContext('webgl', { premultipliedalpha: false }); } var smaskVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec2 a_texCoord; \ \ uniform vec2 u_resolution; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec2 clipSpace = (a_position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_texCoord = a_texCoord; \ } '; var smaskFragmentShaderCode = '\ precision mediump float; \ \ uniform vec4 u_backdrop; \ uniform int u_subtype; \ uniform sampler2D u_image; \ uniform sampler2D u_mask; \ \ varying vec2 v_texCoord; \ \ void main() { \ vec4 imageColor = texture2D(u_image, v_texCoord); \ vec4 maskColor = texture2D(u_mask, v_texCoord); \ if (u_backdrop.a > 0.0) { \ maskColor.rgb = maskColor.rgb * maskColor.a + \ u_backdrop.rgb * (1.0 - maskColor.a); \ } \ float lum; \ if (u_subtype == 0) { \ lum = maskColor.a; \ } else { \ lum = maskColor.r * 0.3 + maskColor.g * 0.59 + \ maskColor.b * 0.11; \ } \ imageColor.a *= lum; \ imageColor.rgb *= imageColor.a; \ gl_FragColor = imageColor; \ } '; var smaskCache = null; function initSmaskGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, smaskVertexShaderCode); var fragmentShader = createFragmentShader(gl, smaskFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.backdropLocation = gl.getUniformLocation(program, 'u_backdrop'); cache.subtypeLocation = gl.getUniformLocation(program, 'u_subtype'); var texCoordLocation = gl.getAttribLocation(program, 'a_texCoord'); var texLayerLocation = gl.getUniformLocation(program, 'u_image'); var texMaskLocation = gl.getUniformLocation(program, 'u_mask'); // provide texture coordinates for the rectangle. var texCoordBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, texCoordBuffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 0.0, 1.0, 1.0, 0.0, 1.0, 1.0]), gl.STATIC_DRAW); gl.enableVertexAttribArray(texCoordLocation); gl.vertexAttribPointer(texCoordLocation, 2, gl.FLOAT, false, 0, 0); gl.uniform1i(texLayerLocation, 0); gl.uniform1i(texMaskLocation, 1); smaskCache = cache; } function composeSMask(layer, mask, properties) { var width = layer.width, height = layer.height; if (!smaskCache) { initSmaskGL(); } var cache = smaskCache,canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); if (properties.backdrop) { gl.uniform4f(cache.resolutionLocation, properties.backdrop[0], properties.backdrop[1], properties.backdrop[2], 1); } else { gl.uniform4f(cache.resolutionLocation, 0, 0, 0, 0); } gl.uniform1i(cache.subtypeLocation, properties.subtype === 'Luminosity' ? 1 : 0); // Create a textures var texture = createTexture(gl, layer, gl.TEXTURE0); var maskTexture = createTexture(gl, mask, gl.TEXTURE1); // Create a buffer and put a single clipspace rectangle in // it (2 triangles) var buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, buffer); gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([ 0, 0, width, 0, 0, height, 0, height, width, 0, width, height]), gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); // draw gl.clearColor(0, 0, 0, 0); gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA); gl.clear(gl.COLOR_BUFFER_BIT); gl.drawArrays(gl.TRIANGLES, 0, 6); gl.flush(); gl.deleteTexture(texture); gl.deleteTexture(maskTexture); gl.deleteBuffer(buffer); return canvas; } var figuresVertexShaderCode = '\ attribute vec2 a_position; \ attribute vec3 a_color; \ \ uniform vec2 u_resolution; \ uniform vec2 u_scale; \ uniform vec2 u_offset; \ \ varying vec4 v_color; \ \ void main() { \ vec2 position = (a_position + u_offset) * u_scale; \ vec2 clipSpace = (position / u_resolution) * 2.0 - 1.0; \ gl_Position = vec4(clipSpace * vec2(1, -1), 0, 1); \ \ v_color = vec4(a_color / 255.0, 1.0); \ } '; var figuresFragmentShaderCode = '\ precision mediump float; \ \ varying vec4 v_color; \ \ void main() { \ gl_FragColor = v_color; \ } '; var figuresCache = null; function initFiguresGL() { var canvas, gl; generateGL(); canvas = currentCanvas; currentCanvas = null; gl = currentGL; currentGL = null; // setup a GLSL program var vertexShader = createVertexShader(gl, figuresVertexShaderCode); var fragmentShader = createFragmentShader(gl, figuresFragmentShaderCode); var program = createProgram(gl, [vertexShader, fragmentShader]); gl.useProgram(program); var cache = {}; cache.gl = gl; cache.canvas = canvas; cache.resolutionLocation = gl.getUniformLocation(program, 'u_resolution'); cache.scaleLocation = gl.getUniformLocation(program, 'u_scale'); cache.offsetLocation = gl.getUniformLocation(program, 'u_offset'); cache.positionLocation = gl.getAttribLocation(program, 'a_position'); cache.colorLocation = gl.getAttribLocation(program, 'a_color'); figuresCache = cache; } function drawFigures(width, height, backgroundColor, figures, context) { if (!figuresCache) { initFiguresGL(); } var cache = figuresCache, canvas = cache.canvas, gl = cache.gl; canvas.width = width; canvas.height = height; gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); gl.uniform2f(cache.resolutionLocation, width, height); // count triangle points var count = 0; var i, ii, rows; for (i = 0, ii = figures.length; i < ii; i++) { switch (figures[i].type) { case 'lattice': rows = (figures[i].coords.length / figures[i].verticesPerRow) | 0; count += (rows - 1) * (figures[i].verticesPerRow - 1) * 6; break; case 'triangles': count += figures[i].coords.length; break; } } // transfer data var coords = new Float32Array(count * 2); var colors = new Uint8Array(count * 3); var coordsMap = context.coords, colorsMap = context.colors; var pIndex = 0, cIndex = 0; for (i = 0, ii = figures.length; i < ii; i++) { var figure = figures[i], ps = figure.coords, cs = figure.colors; switch (figure.type) { case 'lattice': var cols = figure.verticesPerRow; rows = (ps.length / cols) | 0; for (var row = 1; row < rows; row++) { var offset = row * cols + 1; for (var col = 1; col < cols; col++, offset++) { coords[pIndex] = coordsMap[ps[offset - cols - 1]]; coords[pIndex + 1] = coordsMap[ps[offset - cols - 1] + 1]; coords[pIndex + 2] = coordsMap[ps[offset - cols]]; coords[pIndex + 3] = coordsMap[ps[offset - cols] + 1]; coords[pIndex + 4] = coordsMap[ps[offset - 1]]; coords[pIndex + 5] = coordsMap[ps[offset - 1] + 1]; colors[cIndex] = colorsMap[cs[offset - cols - 1]]; colors[cIndex + 1] = colorsMap[cs[offset - cols - 1] + 1]; colors[cIndex + 2] = colorsMap[cs[offset - cols - 1] + 2]; colors[cIndex + 3] = colorsMap[cs[offset - cols]]; colors[cIndex + 4] = colorsMap[cs[offset - cols] + 1]; colors[cIndex + 5] = colorsMap[cs[offset - cols] + 2]; colors[cIndex + 6] = colorsMap[cs[offset - 1]]; colors[cIndex + 7] = colorsMap[cs[offset - 1] + 1]; colors[cIndex + 8] = colorsMap[cs[offset - 1] + 2]; coords[pIndex + 6] = coords[pIndex + 2]; coords[pIndex + 7] = coords[pIndex + 3]; coords[pIndex + 8] = coords[pIndex + 4]; coords[pIndex + 9] = coords[pIndex + 5]; coords[pIndex + 10] = coordsMap[ps[offset]]; coords[pIndex + 11] = coordsMap[ps[offset] + 1]; colors[cIndex + 9] = colors[cIndex + 3]; colors[cIndex + 10] = colors[cIndex + 4]; colors[cIndex + 11] = colors[cIndex + 5]; colors[cIndex + 12] = colors[cIndex + 6]; colors[cIndex + 13] = colors[cIndex + 7]; colors[cIndex + 14] = colors[cIndex + 8]; colors[cIndex + 15] = colorsMap[cs[offset]]; colors[cIndex + 16] = colorsMap[cs[offset] + 1]; colors[cIndex + 17] = colorsMap[cs[offset] + 2]; pIndex += 12; cIndex += 18; } } break; case 'triangles': for (var j = 0, jj = ps.length; j < jj; j++) { coords[pIndex] = coordsMap[ps[j]]; coords[pIndex + 1] = coordsMap[ps[j] + 1]; colors[cIndex] = colorsMap[cs[j]]; colors[cIndex + 1] = colorsMap[cs[j] + 1]; colors[cIndex + 2] = colorsMap[cs[j] + 2]; pIndex += 2; cIndex += 3; } break; } } // draw if (backgroundColor) { gl.clearColor(backgroundColor[0] / 255, backgroundColor[1] / 255, backgroundColor[2] / 255, 1.0); } else { gl.clearColor(0, 0, 0, 0); } gl.clear(gl.COLOR_BUFFER_BIT); var coordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, coordsBuffer); gl.bufferData(gl.ARRAY_BUFFER, coords, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.positionLocation); gl.vertexAttribPointer(cache.positionLocation, 2, gl.FLOAT, false, 0, 0); var colorsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, colorsBuffer); gl.bufferData(gl.ARRAY_BUFFER, colors, gl.STATIC_DRAW); gl.enableVertexAttribArray(cache.colorLocation); gl.vertexAttribPointer(cache.colorLocation, 3, gl.UNSIGNED_BYTE, false, 0, 0); gl.uniform2f(cache.scaleLocation, context.scaleX, context.scaleY); gl.uniform2f(cache.offsetLocation, context.offsetX, context.offsetY); gl.drawArrays(gl.TRIANGLES, 0, count); gl.flush(); gl.deleteBuffer(coordsBuffer); gl.deleteBuffer(colorsBuffer); return canvas; } function cleanup() { if (smaskCache && smaskCache.canvas) { smaskCache.canvas.width = 0; smaskCache.canvas.height = 0; } if (figuresCache && figuresCache.canvas) { figuresCache.canvas.width = 0; figuresCache.canvas.height = 0; } smaskCache = null; figuresCache = null; } return { get isEnabled() { if (PDFJS.disableWebGL) { return false; } var enabled = false; try { generateGL(); enabled = !!currentGL; } catch (e) { } return shadow(this, 'isEnabled', enabled); }, composeSMask: composeSMask, drawFigures: drawFigures, clear: cleanup }; })(); var ShadingIRs = {}; ShadingIRs.RadialAxial = { fromIR: function RadialAxial_fromIR(raw) { var type = raw[1]; var colorStops = raw[2]; var p0 = raw[3]; var p1 = raw[4]; var r0 = raw[5]; var r1 = raw[6]; return { type: 'Pattern', getPattern: function RadialAxial_getPattern(ctx) { var grad; if (type === 'axial') { grad = ctx.createLinearGradient(p0[0], p0[1], p1[0], p1[1]); } else if (type === 'radial') { grad = ctx.createRadialGradient(p0[0], p0[1], r0, p1[0], p1[1], r1); } for (var i = 0, ii = colorStops.length; i < ii; ++i) { var c = colorStops[i]; grad.addColorStop(c[0], c[1]); } return grad; } }; } }; var createMeshCanvas = (function createMeshCanvasClosure() { function drawTriangle(data, context, p1, p2, p3, c1, c2, c3) { // Very basic Gouraud-shaded triangle rasterization algorithm. var coords = context.coords, colors = context.colors; var bytes = data.data, rowSize = data.width * 4; var tmp; if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } if (coords[p2 + 1] > coords[p3 + 1]) { tmp = p2; p2 = p3; p3 = tmp; tmp = c2; c2 = c3; c3 = tmp; } if (coords[p1 + 1] > coords[p2 + 1]) { tmp = p1; p1 = p2; p2 = tmp; tmp = c1; c1 = c2; c2 = tmp; } var x1 = (coords[p1] + context.offsetX) * context.scaleX; var y1 = (coords[p1 + 1] + context.offsetY) * context.scaleY; var x2 = (coords[p2] + context.offsetX) * context.scaleX; var y2 = (coords[p2 + 1] + context.offsetY) * context.scaleY; var x3 = (coords[p3] + context.offsetX) * context.scaleX; var y3 = (coords[p3 + 1] + context.offsetY) * context.scaleY; if (y1 >= y3) { return; } var c1r = colors[c1], c1g = colors[c1 + 1], c1b = colors[c1 + 2]; var c2r = colors[c2], c2g = colors[c2 + 1], c2b = colors[c2 + 2]; var c3r = colors[c3], c3g = colors[c3 + 1], c3b = colors[c3 + 2]; var minY = Math.round(y1), maxY = Math.round(y3); var xa, car, cag, cab; var xb, cbr, cbg, cbb; var k; for (var y = minY; y <= maxY; y++) { if (y < y2) { k = y < y1 ? 0 : y1 === y2 ? 1 : (y1 - y) / (y1 - y2); xa = x1 - (x1 - x2) * k; car = c1r - (c1r - c2r) * k; cag = c1g - (c1g - c2g) * k; cab = c1b - (c1b - c2b) * k; } else { k = y > y3 ? 1 : y2 === y3 ? 0 : (y2 - y) / (y2 - y3); xa = x2 - (x2 - x3) * k; car = c2r - (c2r - c3r) * k; cag = c2g - (c2g - c3g) * k; cab = c2b - (c2b - c3b) * k; } k = y < y1 ? 0 : y > y3 ? 1 : (y1 - y) / (y1 - y3); xb = x1 - (x1 - x3) * k; cbr = c1r - (c1r - c3r) * k; cbg = c1g - (c1g - c3g) * k; cbb = c1b - (c1b - c3b) * k; var x1_ = Math.round(Math.min(xa, xb)); var x2_ = Math.round(Math.max(xa, xb)); var j = rowSize * y + x1_ * 4; for (var x = x1_; x <= x2_; x++) { k = (xa - x) / (xa - xb); k = k < 0 ? 0 : k > 1 ? 1 : k; bytes[j++] = (car - (car - cbr) * k) | 0; bytes[j++] = (cag - (cag - cbg) * k) | 0; bytes[j++] = (cab - (cab - cbb) * k) | 0; bytes[j++] = 255; } } } function drawFigure(data, figure, context) { var ps = figure.coords; var cs = figure.colors; var i, ii; switch (figure.type) { case 'lattice': var verticesPerRow = figure.verticesPerRow; var rows = Math.floor(ps.length / verticesPerRow) - 1; var cols = verticesPerRow - 1; for (i = 0; i < rows; i++) { var q = i * verticesPerRow; for (var j = 0; j < cols; j++, q++) { drawTriangle(data, context, ps[q], ps[q + 1], ps[q + verticesPerRow], cs[q], cs[q + 1], cs[q + verticesPerRow]); drawTriangle(data, context, ps[q + verticesPerRow + 1], ps[q + 1], ps[q + verticesPerRow], cs[q + verticesPerRow + 1], cs[q + 1], cs[q + verticesPerRow]); } } break; case 'triangles': for (i = 0, ii = ps.length; i < ii; i += 3) { drawTriangle(data, context, ps[i], ps[i + 1], ps[i + 2], cs[i], cs[i + 1], cs[i + 2]); } break; default: error('illigal figure'); break; } } function createMeshCanvas(bounds, combinesScale, coords, colors, figures, backgroundColor, cachedCanvases) { // we will increase scale on some weird factor to let antialiasing take // care of "rough" edges var EXPECTED_SCALE = 1.1; // MAX_PATTERN_SIZE is used to avoid OOM situation. var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough var offsetX = Math.floor(bounds[0]); var offsetY = Math.floor(bounds[1]); var boundsWidth = Math.ceil(bounds[2]) - offsetX; var boundsHeight = Math.ceil(bounds[3]) - offsetY; var width = Math.min(Math.ceil(Math.abs(boundsWidth * combinesScale[0] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var height = Math.min(Math.ceil(Math.abs(boundsHeight * combinesScale[1] * EXPECTED_SCALE)), MAX_PATTERN_SIZE); var scaleX = boundsWidth / width; var scaleY = boundsHeight / height; var context = { coords: coords, colors: colors, offsetX: -offsetX, offsetY: -offsetY, scaleX: 1 / scaleX, scaleY: 1 / scaleY }; var canvas, tmpCanvas, i, ii; if (WebGLUtils.isEnabled) { canvas = WebGLUtils.drawFigures(width, height, backgroundColor, figures, context); // https://bugzilla.mozilla.org/show_bug.cgi?id=972126 tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); tmpCanvas.context.drawImage(canvas, 0, 0); canvas = tmpCanvas.canvas; } else { tmpCanvas = cachedCanvases.getCanvas('mesh', width, height, false); var tmpCtx = tmpCanvas.context; var data = tmpCtx.createImageData(width, height); if (backgroundColor) { var bytes = data.data; for (i = 0, ii = bytes.length; i < ii; i += 4) { bytes[i] = backgroundColor[0]; bytes[i + 1] = backgroundColor[1]; bytes[i + 2] = backgroundColor[2]; bytes[i + 3] = 255; } } for (i = 0; i < figures.length; i++) { drawFigure(data, figures[i], context); } tmpCtx.putImageData(data, 0, 0); canvas = tmpCanvas.canvas; } return {canvas: canvas, offsetX: offsetX, offsetY: offsetY, scaleX: scaleX, scaleY: scaleY}; } return createMeshCanvas; })(); ShadingIRs.Mesh = { fromIR: function Mesh_fromIR(raw) { //var type = raw[1]; var coords = raw[2]; var colors = raw[3]; var figures = raw[4]; var bounds = raw[5]; var matrix = raw[6]; //var bbox = raw[7]; var background = raw[8]; return { type: 'Pattern', getPattern: function Mesh_getPattern(ctx, owner, shadingFill) { var scale; if (shadingFill) { scale = Util.singularValueDecompose2dScale(ctx.mozCurrentTransform); } else { // Obtain scale from matrix and current transformation matrix. scale = Util.singularValueDecompose2dScale(owner.baseTransform); if (matrix) { var matrixScale = Util.singularValueDecompose2dScale(matrix); scale = [scale[0] * matrixScale[0], scale[1] * matrixScale[1]]; } } // Rasterizing on the main thread since sending/queue large canvases // might cause OOM. var temporaryPatternCanvas = createMeshCanvas(bounds, scale, coords, colors, figures, shadingFill ? null : background, owner.cachedCanvases); if (!shadingFill) { ctx.setTransform.apply(ctx, owner.baseTransform); if (matrix) { ctx.transform.apply(ctx, matrix); } } ctx.translate(temporaryPatternCanvas.offsetX, temporaryPatternCanvas.offsetY); ctx.scale(temporaryPatternCanvas.scaleX, temporaryPatternCanvas.scaleY); return ctx.createPattern(temporaryPatternCanvas.canvas, 'no-repeat'); } }; } }; ShadingIRs.Dummy = { fromIR: function Dummy_fromIR() { return { type: 'Pattern', getPattern: function Dummy_fromIR_getPattern() { return 'hotpink'; } }; } }; function getShadingPatternFromIR(raw) { var shadingIR = ShadingIRs[raw[0]]; if (!shadingIR) { error('Unknown IR type: ' + raw[0]); } return shadingIR.fromIR(raw); } var TilingPattern = (function TilingPatternClosure() { var PaintType = { COLORED: 1, UNCOLORED: 2 }; var MAX_PATTERN_SIZE = 3000; // 10in @ 300dpi shall be enough function TilingPattern(IR, color, ctx, objs, commonObjs, baseTransform) { this.operatorList = IR[2]; this.matrix = IR[3] || [1, 0, 0, 1, 0, 0]; this.bbox = IR[4]; this.xstep = IR[5]; this.ystep = IR[6]; this.paintType = IR[7]; this.tilingType = IR[8]; this.color = color; this.objs = objs; this.commonObjs = commonObjs; this.baseTransform = baseTransform; this.type = 'Pattern'; this.ctx = ctx; } TilingPattern.prototype = { createPatternCanvas: function TilinPattern_createPatternCanvas(owner) { var operatorList = this.operatorList; var bbox = this.bbox; var xstep = this.xstep; var ystep = this.ystep; var paintType = this.paintType; var tilingType = this.tilingType; var color = this.color; var objs = this.objs; var commonObjs = this.commonObjs; info('TilingType: ' + tilingType); var x0 = bbox[0], y0 = bbox[1], x1 = bbox[2], y1 = bbox[3]; var topLeft = [x0, y0]; // we want the canvas to be as large as the step size var botRight = [x0 + xstep, y0 + ystep]; var width = botRight[0] - topLeft[0]; var height = botRight[1] - topLeft[1]; // Obtain scale from matrix and current transformation matrix. var matrixScale = Util.singularValueDecompose2dScale(this.matrix); var curMatrixScale = Util.singularValueDecompose2dScale( this.baseTransform); var combinedScale = [matrixScale[0] * curMatrixScale[0], matrixScale[1] * curMatrixScale[1]]; // MAX_PATTERN_SIZE is used to avoid OOM situation. // Use width and height values that are as close as possible to the end // result when the pattern is used. Too low value makes the pattern look // blurry. Too large value makes it look too crispy. width = Math.min(Math.ceil(Math.abs(width * combinedScale[0])), MAX_PATTERN_SIZE); height = Math.min(Math.ceil(Math.abs(height * combinedScale[1])), MAX_PATTERN_SIZE); var tmpCanvas = owner.cachedCanvases.getCanvas('pattern', width, height, true); var tmpCtx = tmpCanvas.context; var graphics = new CanvasGraphics(tmpCtx, commonObjs, objs); graphics.groupLevel = owner.groupLevel; this.setFillAndStrokeStyleToContext(tmpCtx, paintType, color); this.setScale(width, height, xstep, ystep); this.transformToScale(graphics); // transform coordinates to pattern space var tmpTranslate = [1, 0, 0, 1, -topLeft[0], -topLeft[1]]; graphics.transform.apply(graphics, tmpTranslate); this.clipBbox(graphics, bbox, x0, y0, x1, y1); graphics.executeOperatorList(operatorList); return tmpCanvas.canvas; }, setScale: function TilingPattern_setScale(width, height, xstep, ystep) { this.scale = [width / xstep, height / ystep]; }, transformToScale: function TilingPattern_transformToScale(graphics) { var scale = this.scale; var tmpScale = [scale[0], 0, 0, scale[1], 0, 0]; graphics.transform.apply(graphics, tmpScale); }, scaleToContext: function TilingPattern_scaleToContext() { var scale = this.scale; this.ctx.scale(1 / scale[0], 1 / scale[1]); }, clipBbox: function clipBbox(graphics, bbox, x0, y0, x1, y1) { if (bbox && isArray(bbox) && bbox.length === 4) { var bboxWidth = x1 - x0; var bboxHeight = y1 - y0; graphics.ctx.rect(x0, y0, bboxWidth, bboxHeight); graphics.clip(); graphics.endPath(); } }, setFillAndStrokeStyleToContext: function setFillAndStrokeStyleToContext(context, paintType, color) { switch (paintType) { case PaintType.COLORED: var ctx = this.ctx; context.fillStyle = ctx.fillStyle; context.strokeStyle = ctx.strokeStyle; break; case PaintType.UNCOLORED: var cssColor = Util.makeCssRgb(color[0], color[1], color[2]); context.fillStyle = cssColor; context.strokeStyle = cssColor; break; default: error('Unsupported paint type: ' + paintType); } }, getPattern: function TilingPattern_getPattern(ctx, owner) { var temporaryPatternCanvas = this.createPatternCanvas(owner); ctx = this.ctx; ctx.setTransform.apply(ctx, this.baseTransform); ctx.transform.apply(ctx, this.matrix); this.scaleToContext(); return ctx.createPattern(temporaryPatternCanvas, 'repeat'); } }; return TilingPattern; })(); function FontLoader(docId) { this.docId = docId; this.styleElement = null; this.nativeFontFaces = []; this.loadTestFontId = 0; this.loadingContext = { requests: [], nextRequestId: 0 }; } FontLoader.prototype = { insertRule: function fontLoaderInsertRule(rule) { var styleElement = this.styleElement; if (!styleElement) { styleElement = this.styleElement = document.createElement('style'); styleElement.id = 'PDFJS_FONT_STYLE_TAG_' + this.docId; document.documentElement.getElementsByTagName('head')[0].appendChild( styleElement); } var styleSheet = styleElement.sheet; styleSheet.insertRule(rule, styleSheet.cssRules.length); }, clear: function fontLoaderClear() { var styleElement = this.styleElement; if (styleElement) { styleElement.parentNode.removeChild(styleElement); styleElement = this.styleElement = null; } this.nativeFontFaces.forEach(function(nativeFontFace) { document.fonts.delete(nativeFontFace); }); this.nativeFontFaces.length = 0; }, get loadTestFont() { // This is a CFF font with 1 glyph for '.' that fills its entire width and // height. return shadow(this, 'loadTestFont', atob( 'T1RUTwALAIAAAwAwQ0ZGIDHtZg4AAAOYAAAAgUZGVE1lkzZwAAAEHAAAABxHREVGABQAFQ' + 'AABDgAAAAeT1MvMlYNYwkAAAEgAAAAYGNtYXABDQLUAAACNAAAAUJoZWFk/xVFDQAAALwA' + 'AAA2aGhlYQdkA+oAAAD0AAAAJGhtdHgD6AAAAAAEWAAAAAZtYXhwAAJQAAAAARgAAAAGbm' + 'FtZVjmdH4AAAGAAAAAsXBvc3T/hgAzAAADeAAAACAAAQAAAAEAALZRFsRfDzz1AAsD6AAA' + 'AADOBOTLAAAAAM4KHDwAAAAAA+gDIQAAAAgAAgAAAAAAAAABAAADIQAAAFoD6AAAAAAD6A' + 'ABAAAAAAAAAAAAAAAAAAAAAQAAUAAAAgAAAAQD6AH0AAUAAAKKArwAAACMAooCvAAAAeAA' + 'MQECAAACAAYJAAAAAAAAAAAAAQAAAAAAAAAAAAAAAFBmRWQAwAAuAC4DIP84AFoDIQAAAA' + 'AAAQAAAAAAAAAAACAAIAABAAAADgCuAAEAAAAAAAAAAQAAAAEAAAAAAAEAAQAAAAEAAAAA' + 'AAIAAQAAAAEAAAAAAAMAAQAAAAEAAAAAAAQAAQAAAAEAAAAAAAUAAQAAAAEAAAAAAAYAAQ' + 'AAAAMAAQQJAAAAAgABAAMAAQQJAAEAAgABAAMAAQQJAAIAAgABAAMAAQQJAAMAAgABAAMA' + 'AQQJAAQAAgABAAMAAQQJAAUAAgABAAMAAQQJAAYAAgABWABYAAAAAAAAAwAAAAMAAAAcAA' + 'EAAAAAADwAAwABAAAAHAAEACAAAAAEAAQAAQAAAC7//wAAAC7////TAAEAAAAAAAABBgAA' + 'AQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' + 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMAAA' + 'AAAAD/gwAyAAAAAQAAAAAAAAAAAAAAAAAAAAABAAQEAAEBAQJYAAEBASH4DwD4GwHEAvgc' + 'A/gXBIwMAYuL+nz5tQXkD5j3CBLnEQACAQEBIVhYWFhYWFhYWFhYWFhYWFhYWFhYWFhYWF' + 'hYWFhYWFhYAAABAQAADwACAQEEE/t3Dov6fAH6fAT+fPp8+nwHDosMCvm1Cvm1DAz6fBQA' + 'AAAAAAABAAAAAMmJbzEAAAAAzgTjFQAAAADOBOQpAAEAAAAAAAAADAAUAAQAAAABAAAAAg' + 'ABAAAAAAAAAAAD6AAAAAAAAA==' )); }, addNativeFontFace: function fontLoader_addNativeFontFace(nativeFontFace) { this.nativeFontFaces.push(nativeFontFace); document.fonts.add(nativeFontFace); }, bind: function fontLoaderBind(fonts, callback) { assert(!isWorker, 'bind() shall be called from main thread'); var rules = []; var fontsToLoad = []; var fontLoadPromises = []; var getNativeFontPromise = function(nativeFontFace) { // Return a promise that is always fulfilled, even when the font fails to // load. return nativeFontFace.loaded.catch(function(e) { warn('Failed to load font "' + nativeFontFace.family + '": ' + e); }); }; for (var i = 0, ii = fonts.length; i < ii; i++) { var font = fonts[i]; // Add the font to the DOM only once or skip if the font // is already loaded. if (font.attached || font.loading === false) { continue; } font.attached = true; if (FontLoader.isFontLoadingAPISupported) { var nativeFontFace = font.createNativeFontFace(); if (nativeFontFace) { this.addNativeFontFace(nativeFontFace); fontLoadPromises.push(getNativeFontPromise(nativeFontFace)); } } else { var rule = font.createFontFaceRule(); if (rule) { this.insertRule(rule); rules.push(rule); fontsToLoad.push(font); } } } var request = this.queueLoadingCallback(callback); if (FontLoader.isFontLoadingAPISupported) { Promise.all(fontLoadPromises).then(function() { request.complete(); }); } else if (rules.length > 0 && !FontLoader.isSyncFontLoadingSupported) { this.prepareFontLoadEvent(rules, fontsToLoad, request); } else { request.complete(); } }, queueLoadingCallback: function FontLoader_queueLoadingCallback(callback) { function LoadLoader_completeRequest() { assert(!request.end, 'completeRequest() cannot be called twice'); request.end = Date.now(); // sending all completed requests in order how they were queued while (context.requests.length > 0 && context.requests[0].end) { var otherRequest = context.requests.shift(); setTimeout(otherRequest.callback, 0); } } var context = this.loadingContext; var requestId = 'pdfjs-font-loading-' + (context.nextRequestId++); var request = { id: requestId, complete: LoadLoader_completeRequest, callback: callback, started: Date.now() }; context.requests.push(request); return request; }, prepareFontLoadEvent: function fontLoaderPrepareFontLoadEvent(rules, fonts, request) { /** Hack begin */ // There's currently no event when a font has finished downloading so the // following code is a dirty hack to 'guess' when a font is // ready. It's assumed fonts are loaded in order, so add a known test // font after the desired fonts and then test for the loading of that // test font. function int32(data, offset) { return (data.charCodeAt(offset) << 24) | (data.charCodeAt(offset + 1) << 16) | (data.charCodeAt(offset + 2) << 8) | (data.charCodeAt(offset + 3) & 0xff); } function spliceString(s, offset, remove, insert) { var chunk1 = s.substr(0, offset); var chunk2 = s.substr(offset + remove); return chunk1 + insert + chunk2; } var i, ii; var canvas = document.createElement('canvas'); canvas.width = 1; canvas.height = 1; var ctx = canvas.getContext('2d'); var called = 0; function isFontReady(name, callback) { called++; // With setTimeout clamping this gives the font ~100ms to load. if(called > 30) { warn('Load test font never loaded.'); callback(); return; } ctx.font = '30px ' + name; ctx.fillText('.', 0, 20); var imageData = ctx.getImageData(0, 0, 1, 1); if (imageData.data[3] > 0) { callback(); return; } setTimeout(isFontReady.bind(null, name, callback)); } var loadTestFontId = 'lt' + Date.now() + this.loadTestFontId++; // Chromium seems to cache fonts based on a hash of the actual font data, // so the font must be modified for each load test else it will appear to // be loaded already. // TODO: This could maybe be made faster by avoiding the btoa of the full // font by splitting it in chunks before hand and padding the font id. var data = this.loadTestFont; var COMMENT_OFFSET = 976; // has to be on 4 byte boundary (for checksum) data = spliceString(data, COMMENT_OFFSET, loadTestFontId.length, loadTestFontId); // CFF checksum is important for IE, adjusting it var CFF_CHECKSUM_OFFSET = 16; var XXXX_VALUE = 0x58585858; // the "comment" filled with 'X' var checksum = int32(data, CFF_CHECKSUM_OFFSET); for (i = 0, ii = loadTestFontId.length - 3; i < ii; i += 4) { checksum = (checksum - XXXX_VALUE + int32(loadTestFontId, i)) | 0; } if (i < loadTestFontId.length) { // align to 4 bytes boundary checksum = (checksum - XXXX_VALUE + int32(loadTestFontId + 'XXX', i)) | 0; } data = spliceString(data, CFF_CHECKSUM_OFFSET, 4, string32(checksum)); var url = 'url(data:font/opentype;base64,' + btoa(data) + ');'; var rule = '@font-face { font-family:"' + loadTestFontId + '";src:' + url + '}'; this.insertRule(rule); var names = []; for (i = 0, ii = fonts.length; i < ii; i++) { names.push(fonts[i].loadedName); } names.push(loadTestFontId); var div = document.createElement('div'); div.setAttribute('style', 'visibility: hidden;' + 'width: 10px; height: 10px;' + 'position: absolute; top: 0px; left: 0px;'); for (i = 0, ii = names.length; i < ii; ++i) { var span = document.createElement('span'); span.textContent = 'Hi'; span.style.fontFamily = names[i]; div.appendChild(span); } document.body.appendChild(div); isFontReady(loadTestFontId, function() { document.body.removeChild(div); request.complete(); }); /** Hack end */ } }; FontLoader.isFontLoadingAPISupported = (!isWorker && typeof document !== 'undefined' && !!document.fonts); Object.defineProperty(FontLoader, 'isSyncFontLoadingSupported', { get: function () { var supported = false; // User agent string sniffing is bad, but there is no reliable way to tell // if font is fully loaded and ready to be used with canvas. var userAgent = window.navigator.userAgent; var m = /Mozilla\/5.0.*?rv:(\d+).*? Gecko/.exec(userAgent); if (m && m[1] >= 14) { supported = true; } // TODO other browsers if (userAgent === 'node') { supported = true; } return shadow(FontLoader, 'isSyncFontLoadingSupported', supported); }, enumerable: true, configurable: true }); var FontFaceObject = (function FontFaceObjectClosure() { function FontFaceObject(translatedData) { this.compiledGlyphs = {}; // importing translated data for (var i in translatedData) { this[i] = translatedData[i]; } } Object.defineProperty(FontFaceObject, 'isEvalSupported', { get: function () { var evalSupport = false; if (PDFJS.isEvalSupported) { try { /* jshint evil: true */ new Function(''); evalSupport = true; } catch (e) {} } return shadow(this, 'isEvalSupported', evalSupport); }, enumerable: true, configurable: true }); FontFaceObject.prototype = { createNativeFontFace: function FontFaceObject_createNativeFontFace() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var nativeFontFace = new FontFace(this.loadedName, this.data, {}); if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this); } return nativeFontFace; }, createFontFaceRule: function FontFaceObject_createFontFaceRule() { if (!this.data) { return null; } if (PDFJS.disableFontFace) { this.disableFontFace = true; return null; } var data = bytesToString(new Uint8Array(this.data)); var fontName = this.loadedName; // Add the font-face rule to the document var url = ('url(data:' + this.mimetype + ';base64,' + window.btoa(data) + ');'); var rule = '@font-face { font-family:"' + fontName + '";src:' + url + '}'; if (PDFJS.pdfBug && 'FontInspector' in globalScope && globalScope['FontInspector'].enabled) { globalScope['FontInspector'].fontAdded(this, url); } return rule; }, getPathGenerator: function FontFaceObject_getPathGenerator(objs, character) { if (!(character in this.compiledGlyphs)) { var cmds = objs.get(this.loadedName + '_path_' + character); var current, i, len; // If we can, compile cmds into JS for MAXIMUM SPEED if (FontFaceObject.isEvalSupported) { var args, js = ''; for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.args !== undefined) { args = current.args.join(','); } else { args = ''; } js += 'c.' + current.cmd + '(' + args + ');\n'; } /* jshint -W054 */ this.compiledGlyphs[character] = new Function('c', 'size', js); } else { // But fall back on using Function.prototype.apply() if we're // blocked from using eval() for whatever reason (like CSP policies) this.compiledGlyphs[character] = function(c, size) { for (i = 0, len = cmds.length; i < len; i++) { current = cmds[i]; if (current.cmd === 'scale') { current.args = [size, -size]; } c[current.cmd].apply(c, current.args); } }; } } return this.compiledGlyphs[character]; } }; return FontFaceObject; })(); /** * Optimised CSS custom property getter/setter. * @class */ var CustomStyle = (function CustomStyleClosure() { // As noted on: http://www.zachstronaut.com/posts/2009/02/17/ // animate-css-transforms-firefox-webkit.html // in some versions of IE9 it is critical that ms appear in this list // before Moz var prefixes = ['ms', 'Moz', 'Webkit', 'O']; var _cache = {}; function CustomStyle() {} CustomStyle.getProp = function get(propName, element) { // check cache only when no element is given if (arguments.length === 1 && typeof _cache[propName] === 'string') { return _cache[propName]; } element = element || document.documentElement; var style = element.style, prefixed, uPropName; // test standard property first if (typeof style[propName] === 'string') { return (_cache[propName] = propName); } // capitalize uPropName = propName.charAt(0).toUpperCase() + propName.slice(1); // test vendor specific properties for (var i = 0, l = prefixes.length; i < l; i++) { prefixed = prefixes[i] + uPropName; if (typeof style[prefixed] === 'string') { return (_cache[propName] = prefixed); } } //if all fails then set to undefined return (_cache[propName] = 'undefined'); }; CustomStyle.setProp = function set(propName, element, str) { var prop = this.getProp(propName); if (prop !== 'undefined') { element.style[prop] = str; } }; return CustomStyle; })(); PDFJS.CustomStyle = CustomStyle; var ANNOT_MIN_SIZE = 10; // px var AnnotationLayer = (function AnnotationLayerClosure() { // TODO(mack): This dupes some of the logic in CanvasGraphics.setFont() function setTextStyles(element, item, fontObj) { var style = element.style; style.fontSize = item.fontSize + 'px'; style.direction = item.fontDirection < 0 ? 'rtl': 'ltr'; if (!fontObj) { return; } style.fontWeight = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); style.fontStyle = fontObj.italic ? 'italic' : 'normal'; var fontName = fontObj.loadedName; var fontFamily = fontName ? '"' + fontName + '", ' : ''; // Use a reasonable default font if the font doesn't specify a fallback var fallbackName = fontObj.fallbackName || 'Helvetica, sans-serif'; style.fontFamily = fontFamily + fallbackName; } function getContainer(data, page, viewport) { var container = document.createElement('section'); var width = data.rect[2] - data.rect[0]; var height = data.rect[3] - data.rect[1]; container.setAttribute('data-annotation-id', data.id); data.rect = Util.normalizeRect([ data.rect[0], page.view[3] - data.rect[1] + page.view[1], data.rect[2], page.view[3] - data.rect[3] + page.view[1] ]); CustomStyle.setProp('transform', container, 'matrix(' + viewport.transform.join(',') + ')'); CustomStyle.setProp('transformOrigin', container, -data.rect[0] + 'px ' + -data.rect[1] + 'px'); if (data.borderStyle.width > 0) { container.style.borderWidth = data.borderStyle.width + 'px'; if (data.borderStyle.style !== AnnotationBorderStyleType.UNDERLINE) { // Underline styles only have a bottom border, so we do not need // to adjust for all borders. This yields a similar result as // Adobe Acrobat/Reader. width = width - 2 * data.borderStyle.width; height = height - 2 * data.borderStyle.width; } var horizontalRadius = data.borderStyle.horizontalCornerRadius; var verticalRadius = data.borderStyle.verticalCornerRadius; if (horizontalRadius > 0 || verticalRadius > 0) { var radius = horizontalRadius + 'px / ' + verticalRadius + 'px'; CustomStyle.setProp('borderRadius', container, radius); } switch (data.borderStyle.style) { case AnnotationBorderStyleType.SOLID: container.style.borderStyle = 'solid'; break; case AnnotationBorderStyleType.DASHED: container.style.borderStyle = 'dashed'; break; case AnnotationBorderStyleType.BEVELED: warn('Unimplemented border style: beveled'); break; case AnnotationBorderStyleType.INSET: warn('Unimplemented border style: inset'); break; case AnnotationBorderStyleType.UNDERLINE: container.style.borderBottomStyle = 'solid'; break; default: break; } if (data.color) { container.style.borderColor = Util.makeCssRgb(data.color[0] | 0, data.color[1] | 0, data.color[2] | 0); } else { // Transparent (invisible) border, so do not draw it at all. container.style.borderWidth = 0; } } container.style.left = data.rect[0] + 'px'; container.style.top = data.rect[1] + 'px'; container.style.width = width + 'px'; container.style.height = height + 'px'; return container; } function getHtmlElementForTextWidgetAnnotation(item, page) { var element = document.createElement('div'); var width = item.rect[2] - item.rect[0]; var height = item.rect[3] - item.rect[1]; element.style.width = width + 'px'; element.style.height = height + 'px'; element.style.display = 'table'; var content = document.createElement('div'); content.textContent = item.fieldValue; var textAlignment = item.textAlignment; content.style.textAlign = ['left', 'center', 'right'][textAlignment]; content.style.verticalAlign = 'middle'; content.style.display = 'table-cell'; var fontObj = item.fontRefName ? page.commonObjs.getData(item.fontRefName) : null; setTextStyles(content, item, fontObj); element.appendChild(content); return element; } function getHtmlElementForTextAnnotation(item, page, viewport) { var rect = item.rect; // sanity check because of OOo-generated PDFs if ((rect[3] - rect[1]) < ANNOT_MIN_SIZE) { rect[3] = rect[1] + ANNOT_MIN_SIZE; } if ((rect[2] - rect[0]) < ANNOT_MIN_SIZE) { rect[2] = rect[0] + (rect[3] - rect[1]); // make it square } var container = getContainer(item, page, viewport); container.className = 'annotText'; var image = document.createElement('img'); image.style.height = container.style.height; image.style.width = container.style.width; var iconName = item.name; image.src = PDFJS.imageResourcesPath + 'annotation-' + iconName.toLowerCase() + '.svg'; image.alt = '[{{type}} Annotation]'; image.dataset.l10nId = 'text_annotation_type'; image.dataset.l10nArgs = JSON.stringify({type: iconName}); var contentWrapper = document.createElement('div'); contentWrapper.className = 'annotTextContentWrapper'; contentWrapper.style.left = Math.floor(rect[2] - rect[0] + 5) + 'px'; contentWrapper.style.top = '-10px'; var content = document.createElement('div'); content.className = 'annotTextContent'; content.setAttribute('hidden', true); var i, ii; if (item.hasBgColor && item.color) { var color = item.color; // Enlighten the color (70%) var BACKGROUND_ENLIGHT = 0.7; var r = BACKGROUND_ENLIGHT * (255 - color[0]) + color[0]; var g = BACKGROUND_ENLIGHT * (255 - color[1]) + color[1]; var b = BACKGROUND_ENLIGHT * (255 - color[2]) + color[2]; content.style.backgroundColor = Util.makeCssRgb(r | 0, g | 0, b | 0); } var title = document.createElement('h1'); var text = document.createElement('p'); title.textContent = item.title; if (!item.content && !item.title) { content.setAttribute('hidden', true); } else { var e = document.createElement('span'); var lines = item.content.split(/(?:\r\n?|\n)/); for (i = 0, ii = lines.length; i < ii; ++i) { var line = lines[i]; e.appendChild(document.createTextNode(line)); if (i < (ii - 1)) { e.appendChild(document.createElement('br')); } } text.appendChild(e); var pinned = false; var showAnnotation = function showAnnotation(pin) { if (pin) { pinned = true; } if (content.hasAttribute('hidden')) { container.style.zIndex += 1; content.removeAttribute('hidden'); } }; var hideAnnotation = function hideAnnotation(unpin) { if (unpin) { pinned = false; } if (!content.hasAttribute('hidden') && !pinned) { container.style.zIndex -= 1; content.setAttribute('hidden', true); } }; var toggleAnnotation = function toggleAnnotation() { if (pinned) { hideAnnotation(true); } else { showAnnotation(true); } }; image.addEventListener('click', function image_clickHandler() { toggleAnnotation(); }, false); image.addEventListener('mouseover', function image_mouseOverHandler() { showAnnotation(); }, false); image.addEventListener('mouseout', function image_mouseOutHandler() { hideAnnotation(); }, false); content.addEventListener('click', function content_clickHandler() { hideAnnotation(true); }, false); } content.appendChild(title); content.appendChild(text); contentWrapper.appendChild(content); container.appendChild(image); container.appendChild(contentWrapper); return container; } function getHtmlElementForLinkAnnotation(item, page, viewport, linkService) { function bindLink(link, dest) { link.href = linkService.getDestinationHash(dest); link.onclick = function annotationsLayerBuilderLinksOnclick() { if (dest) { linkService.navigateTo(dest); } return false; }; if (dest) { link.className = 'internalLink'; } } function bindNamedAction(link, action) { link.href = linkService.getAnchorUrl(''); link.onclick = function annotationsLayerBuilderNamedActionOnClick() { linkService.executeNamedAction(action); return false; }; link.className = 'internalLink'; } var container = getContainer(item, page, viewport); container.className = 'annotLink'; var link = document.createElement('a'); link.href = link.title = item.url || ''; if (item.url && isExternalLinkTargetSet()) { link.target = LinkTargetStringMap[PDFJS.externalLinkTarget]; } if (!item.url) { if (item.action) { bindNamedAction(link, item.action); } else { bindLink(link, ('dest' in item) ? item.dest : null); } } container.appendChild(link); return container; } function getHtmlElement(data, page, viewport, linkService) { switch (data.annotationType) { case AnnotationType.WIDGET: return getHtmlElementForTextWidgetAnnotation(data, page); case AnnotationType.TEXT: return getHtmlElementForTextAnnotation(data, page, viewport); case AnnotationType.LINK: return getHtmlElementForLinkAnnotation(data, page, viewport, linkService); default: throw new Error('Unsupported annotationType: ' + data.annotationType); } } function render(viewport, div, annotations, page, linkService) { for (var i = 0, ii = annotations.length; i < ii; i++) { var data = annotations[i]; if (!data || !data.hasHtml) { continue; } var element = getHtmlElement(data, page, viewport, linkService); div.appendChild(element); } } function update(viewport, div, annotations) { for (var i = 0, ii = annotations.length; i < ii; i++) { var data = annotations[i]; var element = div.querySelector( '[data-annotation-id="' + data.id + '"]'); if (element) { CustomStyle.setProp('transform', element, 'matrix(' + viewport.transform.join(',') + ')'); } } div.removeAttribute('hidden'); } return { render: render, update: update }; })(); PDFJS.AnnotationLayer = AnnotationLayer; /** * Text layer render parameters. * * @typedef {Object} TextLayerRenderParameters * @property {TextContent} textContent - Text content to render (the object is * returned by the page's getTextContent() method). * @property {HTMLElement} container - HTML element that will contain text runs. * @property {PDFJS.PageViewport} viewport - The target viewport to properly * layout the text runs. * @property {Array} textDivs - (optional) HTML elements that are correspond * the text items of the textContent input. This is output and shall be * initially be set to empty array. * @property {number} timeout - (optional) Delay in milliseconds before * rendering of the text runs occurs. */ var renderTextLayer = (function renderTextLayerClosure() { var MAX_TEXT_DIVS_TO_RENDER = 100000; var NonWhitespaceRegexp = /\S/; function isAllWhitespace(str) { return !NonWhitespaceRegexp.test(str); } function appendText(textDivs, viewport, geom, styles) { var style = styles[geom.fontName]; var textDiv = document.createElement('div'); textDivs.push(textDiv); if (isAllWhitespace(geom.str)) { textDiv.dataset.isWhitespace = true; return; } var tx = PDFJS.Util.transform(viewport.transform, geom.transform); var angle = Math.atan2(tx[1], tx[0]); if (style.vertical) { angle += Math.PI / 2; } var fontHeight = Math.sqrt((tx[2] * tx[2]) + (tx[3] * tx[3])); var fontAscent = fontHeight; if (style.ascent) { fontAscent = style.ascent * fontAscent; } else if (style.descent) { fontAscent = (1 + style.descent) * fontAscent; } var left; var top; if (angle === 0) { left = tx[4]; top = tx[5] - fontAscent; } else { left = tx[4] + (fontAscent * Math.sin(angle)); top = tx[5] - (fontAscent * Math.cos(angle)); } textDiv.style.left = left + 'px'; textDiv.style.top = top + 'px'; textDiv.style.fontSize = fontHeight + 'px'; textDiv.style.fontFamily = style.fontFamily; textDiv.textContent = geom.str; // |fontName| is only used by the Font Inspector. This test will succeed // when e.g. the Font Inspector is off but the Stepper is on, but it's // not worth the effort to do a more accurate test. if (PDFJS.pdfBug) { textDiv.dataset.fontName = geom.fontName; } // Storing into dataset will convert number into string. if (angle !== 0) { textDiv.dataset.angle = angle * (180 / Math.PI); } // We don't bother scaling single-char text divs, because it has very // little effect on text highlighting. This makes scrolling on docs with // lots of such divs a lot faster. if (geom.str.length > 1) { if (style.vertical) { textDiv.dataset.canvasWidth = geom.height * viewport.scale; } else { textDiv.dataset.canvasWidth = geom.width * viewport.scale; } } } function render(task) { if (task._canceled) { return; } var textLayerFrag = task._container; var textDivs = task._textDivs; var capability = task._capability; var textDivsLength = textDivs.length; // No point in rendering many divs as it would make the browser // unusable even after the divs are rendered. if (textDivsLength > MAX_TEXT_DIVS_TO_RENDER) { capability.resolve(); return; } var canvas = document.createElement('canvas'); canvas.mozOpaque = true; var ctx = canvas.getContext('2d', {alpha: false}); var lastFontSize; var lastFontFamily; for (var i = 0; i < textDivsLength; i++) { var textDiv = textDivs[i]; if (textDiv.dataset.isWhitespace !== undefined) { continue; } var fontSize = textDiv.style.fontSize; var fontFamily = textDiv.style.fontFamily; // Only build font string and set to context if different from last. if (fontSize !== lastFontSize || fontFamily !== lastFontFamily) { ctx.font = fontSize + ' ' + fontFamily; lastFontSize = fontSize; lastFontFamily = fontFamily; } var width = ctx.measureText(textDiv.textContent).width; if (width > 0) { textLayerFrag.appendChild(textDiv); var transform; if (textDiv.dataset.canvasWidth !== undefined) { // Dataset values come of type string. var textScale = textDiv.dataset.canvasWidth / width; transform = 'scaleX(' + textScale + ')'; } else { transform = ''; } var rotation = textDiv.dataset.angle; if (rotation) { transform = 'rotate(' + rotation + 'deg) ' + transform; } if (transform) { PDFJS.CustomStyle.setProp('transform' , textDiv, transform); } } } capability.resolve(); } /** * Text layer rendering task. * * @param {TextContent} textContent * @param {HTMLElement} container * @param {PDFJS.PageViewport} viewport * @param {Array} textDivs * @private */ function TextLayerRenderTask(textContent, container, viewport, textDivs) { this._textContent = textContent; this._container = container; this._viewport = viewport; textDivs = textDivs || []; this._textDivs = textDivs; this._canceled = false; this._capability = createPromiseCapability(); this._renderTimer = null; } TextLayerRenderTask.prototype = { get promise() { return this._capability.promise; }, cancel: function TextLayer_cancel() { this._canceled = true; if (this._renderTimer !== null) { clearTimeout(this._renderTimer); this._renderTimer = null; } this._capability.reject('canceled'); }, _render: function TextLayer_render(timeout) { var textItems = this._textContent.items; var styles = this._textContent.styles; var textDivs = this._textDivs; var viewport = this._viewport; for (var i = 0, len = textItems.length; i < len; i++) { appendText(textDivs, viewport, textItems[i], styles); } if (!timeout) { // Render right away render(this); } else { // Schedule var self = this; this._renderTimer = setTimeout(function() { render(self); self._renderTimer = null; }, timeout); } } }; /** * Starts rendering of the text layer. * * @param {TextLayerRenderParameters} renderParameters * @returns {TextLayerRenderTask} */ function renderTextLayer(renderParameters) { var task = new TextLayerRenderTask(renderParameters.textContent, renderParameters.container, renderParameters.viewport, renderParameters.textDivs); task._render(renderParameters.timeout); return task; } return renderTextLayer; })(); PDFJS.renderTextLayer = renderTextLayer; var SVG_DEFAULTS = { fontStyle: 'normal', fontWeight: 'normal', fillColor: '#000000' }; var convertImgDataToPng = (function convertImgDataToPngClosure() { var PNG_HEADER = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]); var CHUNK_WRAPPER_SIZE = 12; var crcTable = new Int32Array(256); for (var i = 0; i < 256; i++) { var c = i; for (var h = 0; h < 8; h++) { if (c & 1) { c = 0xedB88320 ^ ((c >> 1) & 0x7fffffff); } else { c = (c >> 1) & 0x7fffffff; } } crcTable[i] = c; } function crc32(data, start, end) { var crc = -1; for (var i = start; i < end; i++) { var a = (crc ^ data[i]) & 0xff; var b = crcTable[a]; crc = (crc >>> 8) ^ b; } return crc ^ -1; } function writePngChunk(type, body, data, offset) { var p = offset; var len = body.length; data[p] = len >> 24 & 0xff; data[p + 1] = len >> 16 & 0xff; data[p + 2] = len >> 8 & 0xff; data[p + 3] = len & 0xff; p += 4; data[p] = type.charCodeAt(0) & 0xff; data[p + 1] = type.charCodeAt(1) & 0xff; data[p + 2] = type.charCodeAt(2) & 0xff; data[p + 3] = type.charCodeAt(3) & 0xff; p += 4; data.set(body, p); p += body.length; var crc = crc32(data, offset + 4, p); data[p] = crc >> 24 & 0xff; data[p + 1] = crc >> 16 & 0xff; data[p + 2] = crc >> 8 & 0xff; data[p + 3] = crc & 0xff; } function adler32(data, start, end) { var a = 1; var b = 0; for (var i = start; i < end; ++i) { a = (a + (data[i] & 0xff)) % 65521; b = (b + a) % 65521; } return (b << 16) | a; } function encode(imgData, kind) { var width = imgData.width; var height = imgData.height; var bitDepth, colorType, lineSize; var bytes = imgData.data; switch (kind) { case ImageKind.GRAYSCALE_1BPP: colorType = 0; bitDepth = 1; lineSize = (width + 7) >> 3; break; case ImageKind.RGB_24BPP: colorType = 2; bitDepth = 8; lineSize = width * 3; break; case ImageKind.RGBA_32BPP: colorType = 6; bitDepth = 8; lineSize = width * 4; break; default: throw new Error('invalid format'); } // prefix every row with predictor 0 var literals = new Uint8Array((1 + lineSize) * height); var offsetLiterals = 0, offsetBytes = 0; var y, i; for (y = 0; y < height; ++y) { literals[offsetLiterals++] = 0; // no prediction literals.set(bytes.subarray(offsetBytes, offsetBytes + lineSize), offsetLiterals); offsetBytes += lineSize; offsetLiterals += lineSize; } if (kind === ImageKind.GRAYSCALE_1BPP) { // inverting for B/W offsetLiterals = 0; for (y = 0; y < height; y++) { offsetLiterals++; // skipping predictor for (i = 0; i < lineSize; i++) { literals[offsetLiterals++] ^= 0xFF; } } } var ihdr = new Uint8Array([ width >> 24 & 0xff, width >> 16 & 0xff, width >> 8 & 0xff, width & 0xff, height >> 24 & 0xff, height >> 16 & 0xff, height >> 8 & 0xff, height & 0xff, bitDepth, // bit depth colorType, // color type 0x00, // compression method 0x00, // filter method 0x00 // interlace method ]); var len = literals.length; var maxBlockLength = 0xFFFF; var deflateBlocks = Math.ceil(len / maxBlockLength); var idat = new Uint8Array(2 + len + deflateBlocks * 5 + 4); var pi = 0; idat[pi++] = 0x78; // compression method and flags idat[pi++] = 0x9c; // flags var pos = 0; while (len > maxBlockLength) { // writing non-final DEFLATE blocks type 0 and length of 65535 idat[pi++] = 0x00; idat[pi++] = 0xff; idat[pi++] = 0xff; idat[pi++] = 0x00; idat[pi++] = 0x00; idat.set(literals.subarray(pos, pos + maxBlockLength), pi); pi += maxBlockLength; pos += maxBlockLength; len -= maxBlockLength; } // writing non-final DEFLATE blocks type 0 idat[pi++] = 0x01; idat[pi++] = len & 0xff; idat[pi++] = len >> 8 & 0xff; idat[pi++] = (~len & 0xffff) & 0xff; idat[pi++] = (~len & 0xffff) >> 8 & 0xff; idat.set(literals.subarray(pos), pi); pi += literals.length - pos; var adler = adler32(literals, 0, literals.length); // checksum idat[pi++] = adler >> 24 & 0xff; idat[pi++] = adler >> 16 & 0xff; idat[pi++] = adler >> 8 & 0xff; idat[pi++] = adler & 0xff; // PNG will consists: header, IHDR+data, IDAT+data, and IEND. var pngLength = PNG_HEADER.length + (CHUNK_WRAPPER_SIZE * 3) + ihdr.length + idat.length; var data = new Uint8Array(pngLength); var offset = 0; data.set(PNG_HEADER, offset); offset += PNG_HEADER.length; writePngChunk('IHDR', ihdr, data, offset); offset += CHUNK_WRAPPER_SIZE + ihdr.length; writePngChunk('IDATA', idat, data, offset); offset += CHUNK_WRAPPER_SIZE + idat.length; writePngChunk('IEND', new Uint8Array(0), data, offset); return PDFJS.createObjectURL(data, 'image/png'); } return function convertImgDataToPng(imgData) { var kind = (imgData.kind === undefined ? ImageKind.GRAYSCALE_1BPP : imgData.kind); return encode(imgData, kind); }; })(); var SVGExtraState = (function SVGExtraStateClosure() { function SVGExtraState() { this.fontSizeScale = 1; this.fontWeight = SVG_DEFAULTS.fontWeight; this.fontSize = 0; this.textMatrix = IDENTITY_MATRIX; this.fontMatrix = FONT_IDENTITY_MATRIX; this.leading = 0; // Current point (in user coordinates) this.x = 0; this.y = 0; // Start of text line (in text coordinates) this.lineX = 0; this.lineY = 0; // Character and word spacing this.charSpacing = 0; this.wordSpacing = 0; this.textHScale = 1; this.textRise = 0; // Default foreground and background colors this.fillColor = SVG_DEFAULTS.fillColor; this.strokeColor = '#000000'; this.fillAlpha = 1; this.strokeAlpha = 1; this.lineWidth = 1; this.lineJoin = ''; this.lineCap = ''; this.miterLimit = 0; this.dashArray = []; this.dashPhase = 0; this.dependencies = []; // Clipping this.clipId = ''; this.pendingClip = false; this.maskId = ''; } SVGExtraState.prototype = { clone: function SVGExtraState_clone() { return Object.create(this); }, setCurrentPoint: function SVGExtraState_setCurrentPoint(x, y) { this.x = x; this.y = y; } }; return SVGExtraState; })(); var SVGGraphics = (function SVGGraphicsClosure() { function createScratchSVG(width, height) { var NS = 'http://www.w3.org/2000/svg'; var svg = document.createElementNS(NS, 'svg:svg'); svg.setAttributeNS(null, 'version', '1.1'); svg.setAttributeNS(null, 'width', width + 'px'); svg.setAttributeNS(null, 'height', height + 'px'); svg.setAttributeNS(null, 'viewBox', '0 0 ' + width + ' ' + height); return svg; } function opListToTree(opList) { var opTree = []; var tmp = []; var opListLen = opList.length; for (var x = 0; x < opListLen; x++) { if (opList[x].fn === 'save') { opTree.push({'fnId': 92, 'fn': 'group', 'items': []}); tmp.push(opTree); opTree = opTree[opTree.length - 1].items; continue; } if(opList[x].fn === 'restore') { opTree = tmp.pop(); } else { opTree.push(opList[x]); } } return opTree; } /** * Formats float number. * @param value {number} number to format. * @returns {string} */ function pf(value) { if (value === (value | 0)) { // integer number return value.toString(); } var s = value.toFixed(10); var i = s.length - 1; if (s[i] !== '0') { return s; } // removing trailing zeros do { i--; } while (s[i] === '0'); return s.substr(0, s[i] === '.' ? i : i + 1); } /** * Formats transform matrix. The standard rotation, scale and translate * matrices are replaced by their shorter forms, and for identity matrix * returns empty string to save the memory. * @param m {Array} matrix to format. * @returns {string} */ function pm(m) { if (m[4] === 0 && m[5] === 0) { if (m[1] === 0 && m[2] === 0) { if (m[0] === 1 && m[3] === 1) { return ''; } return 'scale(' + pf(m[0]) + ' ' + pf(m[3]) + ')'; } if (m[0] === m[3] && m[1] === -m[2]) { var a = Math.acos(m[0]) * 180 / Math.PI; return 'rotate(' + pf(a) + ')'; } } else { if (m[0] === 1 && m[1] === 0 && m[2] === 0 && m[3] === 1) { return 'translate(' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } } return 'matrix(' + pf(m[0]) + ' ' + pf(m[1]) + ' ' + pf(m[2]) + ' ' + pf(m[3]) + ' ' + pf(m[4]) + ' ' + pf(m[5]) + ')'; } function SVGGraphics(commonObjs, objs) { this.current = new SVGExtraState(); this.transformMatrix = IDENTITY_MATRIX; // Graphics state matrix this.transformStack = []; this.extraStack = []; this.commonObjs = commonObjs; this.objs = objs; this.pendingEOFill = false; this.embedFonts = false; this.embeddedFonts = {}; this.cssStyle = null; } var NS = 'http://www.w3.org/2000/svg'; var XML_NS = 'http://www.w3.org/XML/1998/namespace'; var XLINK_NS = 'http://www.w3.org/1999/xlink'; var LINE_CAP_STYLES = ['butt', 'round', 'square']; var LINE_JOIN_STYLES = ['miter', 'round', 'bevel']; var clipCount = 0; var maskCount = 0; SVGGraphics.prototype = { save: function SVGGraphics_save() { this.transformStack.push(this.transformMatrix); var old = this.current; this.extraStack.push(old); this.current = old.clone(); }, restore: function SVGGraphics_restore() { this.transformMatrix = this.transformStack.pop(); this.current = this.extraStack.pop(); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.pgrp.appendChild(this.tgrp); }, group: function SVGGraphics_group(items) { this.save(); this.executeOpTree(items); this.restore(); }, loadDependencies: function SVGGraphics_loadDependencies(operatorList) { var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var argsArray = operatorList.argsArray; var self = this; for (var i = 0; i < fnArrayLen; i++) { if (OPS.dependency === fnArray[i]) { var deps = argsArray[i]; for (var n = 0, nn = deps.length; n < nn; n++) { var obj = deps[n]; var common = obj.substring(0, 2) === 'g_'; var promise; if (common) { promise = new Promise(function(resolve) { self.commonObjs.get(obj, resolve); }); } else { promise = new Promise(function(resolve) { self.objs.get(obj, resolve); }); } this.current.dependencies.push(promise); } } } return Promise.all(this.current.dependencies); }, transform: function SVGGraphics_transform(a, b, c, d, e, f) { var transformMatrix = [a, b, c, d, e, f]; this.transformMatrix = PDFJS.Util.transform(this.transformMatrix, transformMatrix); this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, getSVG: function SVGGraphics_getSVG(operatorList, viewport) { this.svg = createScratchSVG(viewport.width, viewport.height); this.viewport = viewport; return this.loadDependencies(operatorList).then(function () { this.transformMatrix = IDENTITY_MATRIX; this.pgrp = document.createElementNS(NS, 'svg:g'); // Parent group this.pgrp.setAttributeNS(null, 'transform', pm(viewport.transform)); this.tgrp = document.createElementNS(NS, 'svg:g'); // Transform group this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.defs = document.createElementNS(NS, 'svg:defs'); this.pgrp.appendChild(this.defs); this.pgrp.appendChild(this.tgrp); this.svg.appendChild(this.pgrp); var opTree = this.convertOpList(operatorList); this.executeOpTree(opTree); return this.svg; }.bind(this)); }, convertOpList: function SVGGraphics_convertOpList(operatorList) { var argsArray = operatorList.argsArray; var fnArray = operatorList.fnArray; var fnArrayLen = fnArray.length; var REVOPS = []; var opList = []; for (var op in OPS) { REVOPS[OPS[op]] = op; } for (var x = 0; x < fnArrayLen; x++) { var fnId = fnArray[x]; opList.push({'fnId' : fnId, 'fn': REVOPS[fnId], 'args': argsArray[x]}); } return opListToTree(opList); }, executeOpTree: function SVGGraphics_executeOpTree(opTree) { var opTreeLen = opTree.length; for(var x = 0; x < opTreeLen; x++) { var fn = opTree[x].fn; var fnId = opTree[x].fnId; var args = opTree[x].args; switch (fnId | 0) { case OPS.beginText: this.beginText(); break; case OPS.setLeading: this.setLeading(args); break; case OPS.setLeadingMoveText: this.setLeadingMoveText(args[0], args[1]); break; case OPS.setFont: this.setFont(args); break; case OPS.showText: this.showText(args[0]); break; case OPS.showSpacedText: this.showText(args[0]); break; case OPS.endText: this.endText(); break; case OPS.moveText: this.moveText(args[0], args[1]); break; case OPS.setCharSpacing: this.setCharSpacing(args[0]); break; case OPS.setWordSpacing: this.setWordSpacing(args[0]); break; case OPS.setHScale: this.setHScale(args[0]); break; case OPS.setTextMatrix: this.setTextMatrix(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.setLineWidth: this.setLineWidth(args[0]); break; case OPS.setLineJoin: this.setLineJoin(args[0]); break; case OPS.setLineCap: this.setLineCap(args[0]); break; case OPS.setMiterLimit: this.setMiterLimit(args[0]); break; case OPS.setFillRGBColor: this.setFillRGBColor(args[0], args[1], args[2]); break; case OPS.setStrokeRGBColor: this.setStrokeRGBColor(args[0], args[1], args[2]); break; case OPS.setDash: this.setDash(args[0], args[1]); break; case OPS.setGState: this.setGState(args[0]); break; case OPS.fill: this.fill(); break; case OPS.eoFill: this.eoFill(); break; case OPS.stroke: this.stroke(); break; case OPS.fillStroke: this.fillStroke(); break; case OPS.eoFillStroke: this.eoFillStroke(); break; case OPS.clip: this.clip('nonzero'); break; case OPS.eoClip: this.clip('evenodd'); break; case OPS.paintSolidColorImageMask: this.paintSolidColorImageMask(); break; case OPS.paintJpegXObject: this.paintJpegXObject(args[0], args[1], args[2]); break; case OPS.paintImageXObject: this.paintImageXObject(args[0]); break; case OPS.paintInlineImageXObject: this.paintInlineImageXObject(args[0]); break; case OPS.paintImageMaskXObject: this.paintImageMaskXObject(args[0]); break; case OPS.paintFormXObjectBegin: this.paintFormXObjectBegin(args[0], args[1]); break; case OPS.paintFormXObjectEnd: this.paintFormXObjectEnd(); break; case OPS.closePath: this.closePath(); break; case OPS.closeStroke: this.closeStroke(); break; case OPS.closeFillStroke: this.closeFillStroke(); break; case OPS.nextLine: this.nextLine(); break; case OPS.transform: this.transform(args[0], args[1], args[2], args[3], args[4], args[5]); break; case OPS.constructPath: this.constructPath(args[0], args[1]); break; case OPS.endPath: this.endPath(); break; case 92: this.group(opTree[x].items); break; default: warn('Unimplemented method '+ fn); break; } } }, setWordSpacing: function SVGGraphics_setWordSpacing(wordSpacing) { this.current.wordSpacing = wordSpacing; }, setCharSpacing: function SVGGraphics_setCharSpacing(charSpacing) { this.current.charSpacing = charSpacing; }, nextLine: function SVGGraphics_nextLine() { this.moveText(0, this.current.leading); }, setTextMatrix: function SVGGraphics_setTextMatrix(a, b, c, d, e, f) { var current = this.current; this.current.textMatrix = this.current.lineMatrix = [a, b, c, d, e, f]; this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.txtElement = document.createElementNS(NS, 'svg:text'); current.txtElement.appendChild(current.tspan); }, beginText: function SVGGraphics_beginText() { this.current.x = this.current.lineX = 0; this.current.y = this.current.lineY = 0; this.current.textMatrix = IDENTITY_MATRIX; this.current.lineMatrix = IDENTITY_MATRIX; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.txtElement = document.createElementNS(NS, 'svg:text'); this.current.txtgrp = document.createElementNS(NS, 'svg:g'); this.current.xcoords = []; }, moveText: function SVGGraphics_moveText(x, y) { var current = this.current; this.current.x = this.current.lineX += x; this.current.y = this.current.lineY += y; current.xcoords = []; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); }, showText: function SVGGraphics_showText(glyphs) { var current = this.current; var font = current.font; var fontSize = current.fontSize; if (fontSize === 0) { return; } var charSpacing = current.charSpacing; var wordSpacing = current.wordSpacing; var fontDirection = current.fontDirection; var textHScale = current.textHScale * fontDirection; var glyphsLength = glyphs.length; var vertical = font.vertical; var widthAdvanceScale = fontSize * current.fontMatrix[0]; var x = 0, i; for (i = 0; i < glyphsLength; ++i) { var glyph = glyphs[i]; if (glyph === null) { // word break x += fontDirection * wordSpacing; continue; } else if (isNum(glyph)) { x += -glyph * fontSize * 0.001; continue; } current.xcoords.push(current.x + x * textHScale); var width = glyph.width; var character = glyph.fontChar; var charWidth = width * widthAdvanceScale + charSpacing * fontDirection; x += charWidth; current.tspan.textContent += character; } if (vertical) { current.y -= x * textHScale; } else { current.x += x * textHScale; } current.tspan.setAttributeNS(null, 'x', current.xcoords.map(pf).join(' ')); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.tspan.setAttributeNS(null, 'font-family', current.fontFamily); current.tspan.setAttributeNS(null, 'font-size', pf(current.fontSize) + 'px'); if (current.fontStyle !== SVG_DEFAULTS.fontStyle) { current.tspan.setAttributeNS(null, 'font-style', current.fontStyle); } if (current.fontWeight !== SVG_DEFAULTS.fontWeight) { current.tspan.setAttributeNS(null, 'font-weight', current.fontWeight); } if (current.fillColor !== SVG_DEFAULTS.fillColor) { current.tspan.setAttributeNS(null, 'fill', current.fillColor); } current.txtElement.setAttributeNS(null, 'transform', pm(current.textMatrix) + ' scale(1, -1)' ); current.txtElement.setAttributeNS(XML_NS, 'xml:space', 'preserve'); current.txtElement.appendChild(current.tspan); current.txtgrp.appendChild(current.txtElement); this.tgrp.appendChild(current.txtElement); }, setLeadingMoveText: function SVGGraphics_setLeadingMoveText(x, y) { this.setLeading(-y); this.moveText(x, y); }, addFontStyle: function SVGGraphics_addFontStyle(fontObj) { if (!this.cssStyle) { this.cssStyle = document.createElementNS(NS, 'svg:style'); this.cssStyle.setAttributeNS(null, 'type', 'text/css'); this.defs.appendChild(this.cssStyle); } var url = PDFJS.createObjectURL(fontObj.data, fontObj.mimetype); this.cssStyle.textContent += '@font-face { font-family: "' + fontObj.loadedName + '";' + ' src: url(' + url + '); }\n'; }, setFont: function SVGGraphics_setFont(details) { var current = this.current; var fontObj = this.commonObjs.get(details[0]); var size = details[1]; this.current.font = fontObj; if (this.embedFonts && fontObj.data && !this.embeddedFonts[fontObj.loadedName]) { this.addFontStyle(fontObj); this.embeddedFonts[fontObj.loadedName] = fontObj; } current.fontMatrix = (fontObj.fontMatrix ? fontObj.fontMatrix : FONT_IDENTITY_MATRIX); var bold = fontObj.black ? (fontObj.bold ? 'bolder' : 'bold') : (fontObj.bold ? 'bold' : 'normal'); var italic = fontObj.italic ? 'italic' : 'normal'; if (size < 0) { size = -size; current.fontDirection = -1; } else { current.fontDirection = 1; } current.fontSize = size; current.fontFamily = fontObj.loadedName; current.fontWeight = bold; current.fontStyle = italic; current.tspan = document.createElementNS(NS, 'svg:tspan'); current.tspan.setAttributeNS(null, 'y', pf(-current.y)); current.xcoords = []; }, endText: function SVGGraphics_endText() { if (this.current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, // Path properties setLineWidth: function SVGGraphics_setLineWidth(width) { this.current.lineWidth = width; }, setLineCap: function SVGGraphics_setLineCap(style) { this.current.lineCap = LINE_CAP_STYLES[style]; }, setLineJoin: function SVGGraphics_setLineJoin(style) { this.current.lineJoin = LINE_JOIN_STYLES[style]; }, setMiterLimit: function SVGGraphics_setMiterLimit(limit) { this.current.miterLimit = limit; }, setStrokeRGBColor: function SVGGraphics_setStrokeRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.strokeColor = color; }, setFillRGBColor: function SVGGraphics_setFillRGBColor(r, g, b) { var color = Util.makeCssRgb(r, g, b); this.current.fillColor = color; this.current.tspan = document.createElementNS(NS, 'svg:tspan'); this.current.xcoords = []; }, setDash: function SVGGraphics_setDash(dashArray, dashPhase) { this.current.dashArray = dashArray; this.current.dashPhase = dashPhase; }, constructPath: function SVGGraphics_constructPath(ops, args) { var current = this.current; var x = current.x, y = current.y; current.path = document.createElementNS(NS, 'svg:path'); var d = []; var opLength = ops.length; for (var i = 0, j = 0; i < opLength; i++) { switch (ops[i] | 0) { case OPS.rectangle: x = args[j++]; y = args[j++]; var width = args[j++]; var height = args[j++]; var xw = x + width; var yh = y + height; d.push('M', pf(x), pf(y), 'L', pf(xw) , pf(y), 'L', pf(xw), pf(yh), 'L', pf(x), pf(yh), 'Z'); break; case OPS.moveTo: x = args[j++]; y = args[j++]; d.push('M', pf(x), pf(y)); break; case OPS.lineTo: x = args[j++]; y = args[j++]; d.push('L', pf(x) , pf(y)); break; case OPS.curveTo: x = args[j + 4]; y = args[j + 5]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3]), pf(x), pf(y)); j += 6; break; case OPS.curveTo2: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(x), pf(y), pf(args[j]), pf(args[j + 1]), pf(args[j + 2]), pf(args[j + 3])); j += 4; break; case OPS.curveTo3: x = args[j + 2]; y = args[j + 3]; d.push('C', pf(args[j]), pf(args[j + 1]), pf(x), pf(y), pf(x), pf(y)); j += 4; break; case OPS.closePath: d.push('Z'); break; } } current.path.setAttributeNS(null, 'd', d.join(' ')); current.path.setAttributeNS(null, 'stroke-miterlimit', pf(current.miterLimit)); current.path.setAttributeNS(null, 'stroke-linecap', current.lineCap); current.path.setAttributeNS(null, 'stroke-linejoin', current.lineJoin); current.path.setAttributeNS(null, 'stroke-width', pf(current.lineWidth) + 'px'); current.path.setAttributeNS(null, 'stroke-dasharray', current.dashArray.map(pf).join(' ')); current.path.setAttributeNS(null, 'stroke-dashoffset', pf(current.dashPhase) + 'px'); current.path.setAttributeNS(null, 'fill', 'none'); this.tgrp.appendChild(current.path); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } // Saving a reference in current.element so that it can be addressed // in 'fill' and 'stroke' current.element = current.path; current.setCurrentPoint(x, y); }, endPath: function SVGGraphics_endPath() { var current = this.current; if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } this.tgrp = document.createElementNS(NS, 'svg:g'); this.tgrp.setAttributeNS(null, 'transform', pm(this.transformMatrix)); }, clip: function SVGGraphics_clip(type) { var current = this.current; // Add current path to clipping path current.clipId = 'clippath' + clipCount; clipCount++; this.clippath = document.createElementNS(NS, 'svg:clipPath'); this.clippath.setAttributeNS(null, 'id', current.clipId); var clipElement = current.element.cloneNode(); if (type === 'evenodd') { clipElement.setAttributeNS(null, 'clip-rule', 'evenodd'); } else { clipElement.setAttributeNS(null, 'clip-rule', 'nonzero'); } this.clippath.setAttributeNS(null, 'transform', pm(this.transformMatrix)); this.clippath.appendChild(clipElement); this.defs.appendChild(this.clippath); // Create a new group with that attribute current.pendingClip = true; this.cgrp = document.createElementNS(NS, 'svg:g'); this.cgrp.setAttributeNS(null, 'clip-path', 'url(#' + current.clipId + ')'); this.pgrp.appendChild(this.cgrp); }, closePath: function SVGGraphics_closePath() { var current = this.current; var d = current.path.getAttributeNS(null, 'd'); d += 'Z'; current.path.setAttributeNS(null, 'd', d); }, setLeading: function SVGGraphics_setLeading(leading) { this.current.leading = -leading; }, setTextRise: function SVGGraphics_setTextRise(textRise) { this.current.textRise = textRise; }, setHScale: function SVGGraphics_setHScale(scale) { this.current.textHScale = scale / 100; }, setGState: function SVGGraphics_setGState(states) { for (var i = 0, ii = states.length; i < ii; i++) { var state = states[i]; var key = state[0]; var value = state[1]; switch (key) { case 'LW': this.setLineWidth(value); break; case 'LC': this.setLineCap(value); break; case 'LJ': this.setLineJoin(value); break; case 'ML': this.setMiterLimit(value); break; case 'D': this.setDash(value[0], value[1]); break; case 'RI': break; case 'FL': break; case 'Font': this.setFont(value); break; case 'CA': break; case 'ca': break; case 'BM': break; case 'SMask': break; } } }, fill: function SVGGraphics_fill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); }, stroke: function SVGGraphics_stroke() { var current = this.current; current.element.setAttributeNS(null, 'stroke', current.strokeColor); current.element.setAttributeNS(null, 'fill', 'none'); }, eoFill: function SVGGraphics_eoFill() { var current = this.current; current.element.setAttributeNS(null, 'fill', current.fillColor); current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); }, fillStroke: function SVGGraphics_fillStroke() { // Order is important since stroke wants fill to be none. // First stroke, then if fill needed, it will be overwritten. this.stroke(); this.fill(); }, eoFillStroke: function SVGGraphics_eoFillStroke() { this.current.element.setAttributeNS(null, 'fill-rule', 'evenodd'); this.fillStroke(); }, closeStroke: function SVGGraphics_closeStroke() { this.closePath(); this.stroke(); }, closeFillStroke: function SVGGraphics_closeFillStroke() { this.closePath(); this.fillStroke(); }, paintSolidColorImageMask: function SVGGraphics_paintSolidColorImageMask() { var current = this.current; var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', '1px'); rect.setAttributeNS(null, 'height', '1px'); rect.setAttributeNS(null, 'fill', current.fillColor); this.tgrp.appendChild(rect); }, paintJpegXObject: function SVGGraphics_paintJpegXObject(objId, w, h) { var current = this.current; var imgObj = this.objs.get(objId); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgObj.src); imgEl.setAttributeNS(null, 'width', imgObj.width + 'px'); imgEl.setAttributeNS(null, 'height', imgObj.height + 'px'); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-h)); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / w) + ' ' + pf(-1 / h) + ')'); this.tgrp.appendChild(imgEl); if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageXObject: function SVGGraphics_paintImageXObject(objId) { var imgData = this.objs.get(objId); if (!imgData) { warn('Dependent image isn\'t ready yet'); return; } this.paintInlineImageXObject(imgData); }, paintInlineImageXObject: function SVGGraphics_paintInlineImageXObject(imgData, mask) { var current = this.current; var width = imgData.width; var height = imgData.height; var imgSrc = convertImgDataToPng(imgData); var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', '0'); cliprect.setAttributeNS(null, 'y', '0'); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); current.element = cliprect; this.clip('nonzero'); var imgEl = document.createElementNS(NS, 'svg:image'); imgEl.setAttributeNS(XLINK_NS, 'xlink:href', imgSrc); imgEl.setAttributeNS(null, 'x', '0'); imgEl.setAttributeNS(null, 'y', pf(-height)); imgEl.setAttributeNS(null, 'width', pf(width) + 'px'); imgEl.setAttributeNS(null, 'height', pf(height) + 'px'); imgEl.setAttributeNS(null, 'transform', 'scale(' + pf(1 / width) + ' ' + pf(-1 / height) + ')'); if (mask) { mask.appendChild(imgEl); } else { this.tgrp.appendChild(imgEl); } if (current.pendingClip) { this.cgrp.appendChild(this.tgrp); this.pgrp.appendChild(this.cgrp); } else { this.pgrp.appendChild(this.tgrp); } }, paintImageMaskXObject: function SVGGraphics_paintImageMaskXObject(imgData) { var current = this.current; var width = imgData.width; var height = imgData.height; var fillColor = current.fillColor; current.maskId = 'mask' + maskCount++; var mask = document.createElementNS(NS, 'svg:mask'); mask.setAttributeNS(null, 'id', current.maskId); var rect = document.createElementNS(NS, 'svg:rect'); rect.setAttributeNS(null, 'x', '0'); rect.setAttributeNS(null, 'y', '0'); rect.setAttributeNS(null, 'width', pf(width)); rect.setAttributeNS(null, 'height', pf(height)); rect.setAttributeNS(null, 'fill', fillColor); rect.setAttributeNS(null, 'mask', 'url(#' + current.maskId +')'); this.defs.appendChild(mask); this.tgrp.appendChild(rect); this.paintInlineImageXObject(imgData, mask); }, paintFormXObjectBegin: function SVGGraphics_paintFormXObjectBegin(matrix, bbox) { this.save(); if (isArray(matrix) && matrix.length === 6) { this.transform(matrix[0], matrix[1], matrix[2], matrix[3], matrix[4], matrix[5]); } if (isArray(bbox) && bbox.length === 4) { var width = bbox[2] - bbox[0]; var height = bbox[3] - bbox[1]; var cliprect = document.createElementNS(NS, 'svg:rect'); cliprect.setAttributeNS(null, 'x', bbox[0]); cliprect.setAttributeNS(null, 'y', bbox[1]); cliprect.setAttributeNS(null, 'width', pf(width)); cliprect.setAttributeNS(null, 'height', pf(height)); this.current.element = cliprect; this.clip('nonzero'); this.endPath(); } }, paintFormXObjectEnd: function SVGGraphics_paintFormXObjectEnd() { this.restore(); } }; return SVGGraphics; })(); PDFJS.SVGGraphics = SVGGraphics; }).call((typeof window === 'undefined') ? this : window); if (!PDFJS.workerSrc && typeof document !== 'undefined') { // workerSrc is not set -- using last script url to define default location PDFJS.workerSrc = (function () { 'use strict'; var pdfJsSrc = document.currentScript.src; return pdfJsSrc && pdfJsSrc.replace(/\.js$/i, '.worker.js'); })(); }
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
services/web/public/js/ace/worker-lua.js
3,633
"no use strict"; ;(function(window) { if (typeof window.window != "undefined" && window.document) return; if (window.require && window.define) return; window.console = function() { var msgs = Array.prototype.slice.call(arguments, 0); postMessage({type: "log", data: msgs}); }; window.console.error = window.console.warn = window.console.log = window.console.trace = window.console; window.window = window; window.ace = window; window.onerror = function(message, file, line, col, err) { postMessage({type: "error", data: { message: message, data: err.data, file: file, line: line, col: col, stack: err.stack }}); }; window.normalizeModule = function(parentId, moduleName) { // normalize plugin requires if (moduleName.indexOf("!") !== -1) { var chunks = moduleName.split("!"); return window.normalizeModule(parentId, chunks[0]) + "!" + window.normalizeModule(parentId, chunks[1]); } // normalize relative requires if (moduleName.charAt(0) == ".") { var base = parentId.split("/").slice(0, -1).join("/"); moduleName = (base ? base + "/" : "") + moduleName; while (moduleName.indexOf(".") !== -1 && previous != moduleName) { var previous = moduleName; moduleName = moduleName.replace(/^\.\//, "").replace(/\/\.\//, "/").replace(/[^\/]+\/\.\.\//, ""); } } return moduleName; }; window.require = function require(parentId, id) { if (!id) { id = parentId; parentId = null; } if (!id.charAt) throw new Error("worker.js require() accepts only (parentId, id) as arguments"); id = window.normalizeModule(parentId, id); var module = window.require.modules[id]; if (module) { if (!module.initialized) { module.initialized = true; module.exports = module.factory().exports; } return module.exports; } if (!window.require.tlns) return console.log("unable to load " + id); var path = resolveModuleId(id, window.require.tlns); if (path.slice(-3) != ".js") path += ".js"; window.require.id = id; window.require.modules[id] = {}; // prevent infinite loop on broken modules importScripts(path); return window.require(parentId, id); }; function resolveModuleId(id, paths) { var testPath = id, tail = ""; while (testPath) { var alias = paths[testPath]; if (typeof alias == "string") { return alias + tail; } else if (alias) { return alias.location.replace(/\/*$/, "/") + (tail || alias.main || alias.name); } else if (alias === false) { return ""; } var i = testPath.lastIndexOf("/"); if (i === -1) break; tail = testPath.substr(i) + tail; testPath = testPath.slice(0, i); } return id; } window.require.modules = {}; window.require.tlns = {}; window.define = function(id, deps, factory) { if (arguments.length == 2) { factory = deps; if (typeof id != "string") { deps = id; id = window.require.id; } } else if (arguments.length == 1) { factory = id; deps = []; id = window.require.id; } if (typeof factory != "function") { window.require.modules[id] = { exports: factory, initialized: true }; return; } if (!deps.length) // If there is no dependencies, we inject "require", "exports" and // "module" as dependencies, to provide CommonJS compatibility. deps = ["require", "exports", "module"]; var req = function(childId) { return window.require(id, childId); }; window.require.modules[id] = { exports: {}, factory: function() { var module = this; var returnExports = factory.apply(this, deps.map(function(dep) { switch (dep) { // Because "require", "exports" and "module" aren't actual // dependencies, we must handle them seperately. case "require": return req; case "exports": return module.exports; case "module": return module; // But for all other dependencies, we can just go ahead and // require them. default: return req(dep); } })); if (returnExports) module.exports = returnExports; return module; } }; }; window.define.amd = {}; require.tlns = {}; window.initBaseUrls = function initBaseUrls(topLevelNamespaces) { for (var i in topLevelNamespaces) require.tlns[i] = topLevelNamespaces[i]; }; window.initSender = function initSender() { var EventEmitter = window.require("ace/lib/event_emitter").EventEmitter; var oop = window.require("ace/lib/oop"); var Sender = function() {}; (function() { oop.implement(this, EventEmitter); this.callback = function(data, callbackId) { postMessage({ type: "call", id: callbackId, data: data }); }; this.emit = function(name, data) { postMessage({ type: "event", name: name, data: data }); }; }).call(Sender.prototype); return new Sender(); }; var main = window.main = null; var sender = window.sender = null; window.onmessage = function(e) { var msg = e.data; if (msg.event && sender) { sender._signal(msg.event, msg.data); } else if (msg.command) { if (main[msg.command]) main[msg.command].apply(main, msg.args); else if (window[msg.command]) window[msg.command].apply(window, msg.args); else throw new Error("Unknown command:" + msg.command); } else if (msg.init) { window.initBaseUrls(msg.tlns); require("ace/lib/es5-shim"); sender = window.sender = window.initSender(); var clazz = require(msg.module)[msg.classname]; main = window.main = new clazz(sender); } }; })(this); ace.define("ace/lib/oop",["require","exports","module"], function(require, exports, module) { "use strict"; exports.inherits = function(ctor, superCtor) { ctor.super_ = superCtor; ctor.prototype = Object.create(superCtor.prototype, { constructor: { value: ctor, enumerable: false, writable: true, configurable: true } }); }; exports.mixin = function(obj, mixin) { for (var key in mixin) { obj[key] = mixin[key]; } return obj; }; exports.implement = function(proto, mixin) { exports.mixin(proto, mixin); }; }); ace.define("ace/range",["require","exports","module"], function(require, exports, module) { "use strict"; var comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; var Range = function(startRow, startColumn, endRow, endColumn) { this.start = { row: startRow, column: startColumn }; this.end = { row: endRow, column: endColumn }; }; (function() { this.isEqual = function(range) { return this.start.row === range.start.row && this.end.row === range.end.row && this.start.column === range.start.column && this.end.column === range.end.column; }; this.toString = function() { return ("Range: [" + this.start.row + "/" + this.start.column + "] -> [" + this.end.row + "/" + this.end.column + "]"); }; this.contains = function(row, column) { return this.compare(row, column) == 0; }; this.compareRange = function(range) { var cmp, end = range.end, start = range.start; cmp = this.compare(end.row, end.column); if (cmp == 1) { cmp = this.compare(start.row, start.column); if (cmp == 1) { return 2; } else if (cmp == 0) { return 1; } else { return 0; } } else if (cmp == -1) { return -2; } else { cmp = this.compare(start.row, start.column); if (cmp == -1) { return -1; } else if (cmp == 1) { return 42; } else { return 0; } } }; this.comparePoint = function(p) { return this.compare(p.row, p.column); }; this.containsRange = function(range) { return this.comparePoint(range.start) == 0 && this.comparePoint(range.end) == 0; }; this.intersects = function(range) { var cmp = this.compareRange(range); return (cmp == -1 || cmp == 0 || cmp == 1); }; this.isEnd = function(row, column) { return this.end.row == row && this.end.column == column; }; this.isStart = function(row, column) { return this.start.row == row && this.start.column == column; }; this.setStart = function(row, column) { if (typeof row == "object") { this.start.column = row.column; this.start.row = row.row; } else { this.start.row = row; this.start.column = column; } }; this.setEnd = function(row, column) { if (typeof row == "object") { this.end.column = row.column; this.end.row = row.row; } else { this.end.row = row; this.end.column = column; } }; this.inside = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column) || this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.insideStart = function(row, column) { if (this.compare(row, column) == 0) { if (this.isEnd(row, column)) { return false; } else { return true; } } return false; }; this.insideEnd = function(row, column) { if (this.compare(row, column) == 0) { if (this.isStart(row, column)) { return false; } else { return true; } } return false; }; this.compare = function(row, column) { if (!this.isMultiLine()) { if (row === this.start.row) { return column < this.start.column ? -1 : (column > this.end.column ? 1 : 0); }; } if (row < this.start.row) return -1; if (row > this.end.row) return 1; if (this.start.row === row) return column >= this.start.column ? 0 : -1; if (this.end.row === row) return column <= this.end.column ? 0 : 1; return 0; }; this.compareStart = function(row, column) { if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.compareEnd = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else { return this.compare(row, column); } }; this.compareInside = function(row, column) { if (this.end.row == row && this.end.column == column) { return 1; } else if (this.start.row == row && this.start.column == column) { return -1; } else { return this.compare(row, column); } }; this.clipRows = function(firstRow, lastRow) { if (this.end.row > lastRow) var end = {row: lastRow + 1, column: 0}; else if (this.end.row < firstRow) var end = {row: firstRow, column: 0}; if (this.start.row > lastRow) var start = {row: lastRow + 1, column: 0}; else if (this.start.row < firstRow) var start = {row: firstRow, column: 0}; return Range.fromPoints(start || this.start, end || this.end); }; this.extend = function(row, column) { var cmp = this.compare(row, column); if (cmp == 0) return this; else if (cmp == -1) var start = {row: row, column: column}; else var end = {row: row, column: column}; return Range.fromPoints(start || this.start, end || this.end); }; this.isEmpty = function() { return (this.start.row === this.end.row && this.start.column === this.end.column); }; this.isMultiLine = function() { return (this.start.row !== this.end.row); }; this.clone = function() { return Range.fromPoints(this.start, this.end); }; this.collapseRows = function() { if (this.end.column == 0) return new Range(this.start.row, 0, Math.max(this.start.row, this.end.row-1), 0) else return new Range(this.start.row, 0, this.end.row, 0) }; this.toScreenRange = function(session) { var screenPosStart = session.documentToScreenPosition(this.start); var screenPosEnd = session.documentToScreenPosition(this.end); return new Range( screenPosStart.row, screenPosStart.column, screenPosEnd.row, screenPosEnd.column ); }; this.moveBy = function(row, column) { this.start.row += row; this.start.column += column; this.end.row += row; this.end.column += column; }; }).call(Range.prototype); Range.fromPoints = function(start, end) { return new Range(start.row, start.column, end.row, end.column); }; Range.comparePoints = comparePoints; Range.comparePoints = function(p1, p2) { return p1.row - p2.row || p1.column - p2.column; }; exports.Range = Range; }); ace.define("ace/apply_delta",["require","exports","module"], function(require, exports, module) { "use strict"; function throwDeltaError(delta, errorText){ console.log("Invalid Delta:", delta); throw "Invalid Delta: " + errorText; } function positionInDocument(docLines, position) { return position.row >= 0 && position.row < docLines.length && position.column >= 0 && position.column <= docLines[position.row].length; } function validateDelta(docLines, delta) { if (delta.action != "insert" && delta.action != "remove") throwDeltaError(delta, "delta.action must be 'insert' or 'remove'"); if (!(delta.lines instanceof Array)) throwDeltaError(delta, "delta.lines must be an Array"); if (!delta.start || !delta.end) throwDeltaError(delta, "delta.start/end must be an present"); var start = delta.start; if (!positionInDocument(docLines, delta.start)) throwDeltaError(delta, "delta.start must be contained in document"); var end = delta.end; if (delta.action == "remove" && !positionInDocument(docLines, end)) throwDeltaError(delta, "delta.end must contained in document for 'remove' actions"); var numRangeRows = end.row - start.row; var numRangeLastLineChars = (end.column - (numRangeRows == 0 ? start.column : 0)); if (numRangeRows != delta.lines.length - 1 || delta.lines[numRangeRows].length != numRangeLastLineChars) throwDeltaError(delta, "delta.range must match delta lines"); } exports.applyDelta = function(docLines, delta, doNotValidate) { var row = delta.start.row; var startColumn = delta.start.column; var line = docLines[row] || ""; switch (delta.action) { case "insert": var lines = delta.lines; if (lines.length === 1) { docLines[row] = line.substring(0, startColumn) + delta.lines[0] + line.substring(startColumn); } else { var args = [row, 1].concat(delta.lines); docLines.splice.apply(docLines, args); docLines[row] = line.substring(0, startColumn) + docLines[row]; docLines[row + delta.lines.length - 1] += line.substring(startColumn); } break; case "remove": var endColumn = delta.end.column; var endRow = delta.end.row; if (row === endRow) { docLines[row] = line.substring(0, startColumn) + line.substring(endColumn); } else { docLines.splice( row, endRow - row + 1, line.substring(0, startColumn) + docLines[endRow].substring(endColumn) ); } break; } } }); ace.define("ace/lib/event_emitter",["require","exports","module"], function(require, exports, module) { "use strict"; var EventEmitter = {}; var stopPropagation = function() { this.propagationStopped = true; }; var preventDefault = function() { this.defaultPrevented = true; }; EventEmitter._emit = EventEmitter._dispatchEvent = function(eventName, e) { this._eventRegistry || (this._eventRegistry = {}); this._defaultHandlers || (this._defaultHandlers = {}); var listeners = this._eventRegistry[eventName] || []; var defaultHandler = this._defaultHandlers[eventName]; if (!listeners.length && !defaultHandler) return; if (typeof e != "object" || !e) e = {}; if (!e.type) e.type = eventName; if (!e.stopPropagation) e.stopPropagation = stopPropagation; if (!e.preventDefault) e.preventDefault = preventDefault; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) { listeners[i](e, this); if (e.propagationStopped) break; } if (defaultHandler && !e.defaultPrevented) return defaultHandler(e, this); }; EventEmitter._signal = function(eventName, e) { var listeners = (this._eventRegistry || {})[eventName]; if (!listeners) return; listeners = listeners.slice(); for (var i=0; i<listeners.length; i++) listeners[i](e, this); }; EventEmitter.once = function(eventName, callback) { var _self = this; callback && this.addEventListener(eventName, function newCallback() { _self.removeEventListener(eventName, newCallback); callback.apply(null, arguments); }); }; EventEmitter.setDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) handlers = this._defaultHandlers = {_disabled_: {}}; if (handlers[eventName]) { var old = handlers[eventName]; var disabled = handlers._disabled_[eventName]; if (!disabled) handlers._disabled_[eventName] = disabled = []; disabled.push(old); var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } handlers[eventName] = callback; }; EventEmitter.removeDefaultHandler = function(eventName, callback) { var handlers = this._defaultHandlers if (!handlers) return; var disabled = handlers._disabled_[eventName]; if (handlers[eventName] == callback) { var old = handlers[eventName]; if (disabled) this.setDefaultHandler(eventName, disabled.pop()); } else if (disabled) { var i = disabled.indexOf(callback); if (i != -1) disabled.splice(i, 1); } }; EventEmitter.on = EventEmitter.addEventListener = function(eventName, callback, capturing) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) listeners = this._eventRegistry[eventName] = []; if (listeners.indexOf(callback) == -1) listeners[capturing ? "unshift" : "push"](callback); return callback; }; EventEmitter.off = EventEmitter.removeListener = EventEmitter.removeEventListener = function(eventName, callback) { this._eventRegistry = this._eventRegistry || {}; var listeners = this._eventRegistry[eventName]; if (!listeners) return; var index = listeners.indexOf(callback); if (index !== -1) listeners.splice(index, 1); }; EventEmitter.removeAllListeners = function(eventName) { if (this._eventRegistry) this._eventRegistry[eventName] = []; }; exports.EventEmitter = EventEmitter; }); ace.define("ace/anchor",["require","exports","module","ace/lib/oop","ace/lib/event_emitter"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var EventEmitter = require("./lib/event_emitter").EventEmitter; var Anchor = exports.Anchor = function(doc, row, column) { this.$onChange = this.onChange.bind(this); this.attach(doc); if (typeof column == "undefined") this.setPosition(row.row, row.column); else this.setPosition(row, column); }; (function() { oop.implement(this, EventEmitter); this.getPosition = function() { return this.$clipPositionToDocument(this.row, this.column); }; this.getDocument = function() { return this.document; }; this.$insertRight = false; this.onChange = function(delta) { if (delta.start.row == delta.end.row && delta.start.row != this.row) return; if (delta.start.row > this.row) return; var point = $getTransformedPoint(delta, {row: this.row, column: this.column}, this.$insertRight); this.setPosition(point.row, point.column, true); }; function $pointsInOrder(point1, point2, equalPointsInOrder) { var bColIsAfter = equalPointsInOrder ? point1.column <= point2.column : point1.column < point2.column; return (point1.row < point2.row) || (point1.row == point2.row && bColIsAfter); } function $getTransformedPoint(delta, point, moveIfEqual) { var deltaIsInsert = delta.action == "insert"; var deltaRowShift = (deltaIsInsert ? 1 : -1) * (delta.end.row - delta.start.row); var deltaColShift = (deltaIsInsert ? 1 : -1) * (delta.end.column - delta.start.column); var deltaStart = delta.start; var deltaEnd = deltaIsInsert ? deltaStart : delta.end; // Collapse insert range. if ($pointsInOrder(point, deltaStart, moveIfEqual)) { return { row: point.row, column: point.column }; } if ($pointsInOrder(deltaEnd, point, !moveIfEqual)) { return { row: point.row + deltaRowShift, column: point.column + (point.row == deltaEnd.row ? deltaColShift : 0) }; } return { row: deltaStart.row, column: deltaStart.column }; } this.setPosition = function(row, column, noClip) { var pos; if (noClip) { pos = { row: row, column: column }; } else { pos = this.$clipPositionToDocument(row, column); } if (this.row == pos.row && this.column == pos.column) return; var old = { row: this.row, column: this.column }; this.row = pos.row; this.column = pos.column; this._signal("change", { old: old, value: pos }); }; this.detach = function() { this.document.removeEventListener("change", this.$onChange); }; this.attach = function(doc) { this.document = doc || this.document; this.document.on("change", this.$onChange); }; this.$clipPositionToDocument = function(row, column) { var pos = {}; if (row >= this.document.getLength()) { pos.row = Math.max(0, this.document.getLength() - 1); pos.column = this.document.getLine(pos.row).length; } else if (row < 0) { pos.row = 0; pos.column = 0; } else { pos.row = row; pos.column = Math.min(this.document.getLine(pos.row).length, Math.max(0, column)); } if (column < 0) pos.column = 0; return pos; }; }).call(Anchor.prototype); }); ace.define("ace/document",["require","exports","module","ace/lib/oop","ace/apply_delta","ace/lib/event_emitter","ace/range","ace/anchor"], function(require, exports, module) { "use strict"; var oop = require("./lib/oop"); var applyDelta = require("./apply_delta").applyDelta; var EventEmitter = require("./lib/event_emitter").EventEmitter; var Range = require("./range").Range; var Anchor = require("./anchor").Anchor; var Document = function(textOrLines) { this.$lines = [""]; if (textOrLines.length === 0) { this.$lines = [""]; } else if (Array.isArray(textOrLines)) { this.insertMergedLines({row: 0, column: 0}, textOrLines); } else { this.insert({row: 0, column:0}, textOrLines); } }; (function() { oop.implement(this, EventEmitter); this.setValue = function(text) { var len = this.getLength() - 1; this.remove(new Range(0, 0, len, this.getLine(len).length)); this.insert({row: 0, column: 0}, text); }; this.getValue = function() { return this.getAllLines().join(this.getNewLineCharacter()); }; this.createAnchor = function(row, column) { return new Anchor(this, row, column); }; if ("aaa".split(/a/).length === 0) { this.$split = function(text) { return text.replace(/\r\n|\r/g, "\n").split("\n"); }; } else { this.$split = function(text) { return text.split(/\r\n|\r|\n/); }; } this.$detectNewLine = function(text) { var match = text.match(/^.*?(\r\n|\r|\n)/m); this.$autoNewLine = match ? match[1] : "\n"; this._signal("changeNewLineMode"); }; this.getNewLineCharacter = function() { switch (this.$newLineMode) { case "windows": return "\r\n"; case "unix": return "\n"; default: return this.$autoNewLine || "\n"; } }; this.$autoNewLine = ""; this.$newLineMode = "auto"; this.setNewLineMode = function(newLineMode) { if (this.$newLineMode === newLineMode) return; this.$newLineMode = newLineMode; this._signal("changeNewLineMode"); }; this.getNewLineMode = function() { return this.$newLineMode; }; this.isNewLine = function(text) { return (text == "\r\n" || text == "\r" || text == "\n"); }; this.getLine = function(row) { return this.$lines[row] || ""; }; this.getLines = function(firstRow, lastRow) { return this.$lines.slice(firstRow, lastRow + 1); }; this.getAllLines = function() { return this.getLines(0, this.getLength()); }; this.getLength = function() { return this.$lines.length; }; this.getTextRange = function(range) { return this.getLinesForRange(range).join(this.getNewLineCharacter()); }; this.getLinesForRange = function(range) { var lines; if (range.start.row === range.end.row) { lines = [this.getLine(range.start.row).substring(range.start.column, range.end.column)]; } else { lines = this.getLines(range.start.row, range.end.row); lines[0] = (lines[0] || "").substring(range.start.column); var l = lines.length - 1; if (range.end.row - range.start.row == l) lines[l] = lines[l].substring(0, range.end.column); } return lines; }; this.insertLines = function(row, lines) { console.warn("Use of document.insertLines is deprecated. Use the insertFullLines method instead."); return this.insertFullLines(row, lines); }; this.removeLines = function(firstRow, lastRow) { console.warn("Use of document.removeLines is deprecated. Use the removeFullLines method instead."); return this.removeFullLines(firstRow, lastRow); }; this.insertNewLine = function(position) { console.warn("Use of document.insertNewLine is deprecated. Use insertMergedLines(position, [\'\', \'\']) instead."); return this.insertMergedLines(position, ["", ""]); }; this.insert = function(position, text) { if (this.getLength() <= 1) this.$detectNewLine(text); return this.insertMergedLines(position, this.$split(text)); }; this.insertInLine = function(position, text) { var start = this.clippedPos(position.row, position.column); var end = this.pos(position.row, position.column + text.length); this.applyDelta({ start: start, end: end, action: "insert", lines: [text] }, true); return this.clonePos(end); }; this.clippedPos = function(row, column) { var length = this.getLength(); if (row === undefined) { row = length; } else if (row < 0) { row = 0; } else if (row >= length) { row = length - 1; column = undefined; } var line = this.getLine(row); if (column == undefined) column = line.length; column = Math.min(Math.max(column, 0), line.length); return {row: row, column: column}; }; this.clonePos = function(pos) { return {row: pos.row, column: pos.column}; }; this.pos = function(row, column) { return {row: row, column: column}; }; this.$clipPosition = function(position) { var length = this.getLength(); if (position.row >= length) { position.row = Math.max(0, length - 1); position.column = this.getLine(length - 1).length; } else { position.row = Math.max(0, position.row); position.column = Math.min(Math.max(position.column, 0), this.getLine(position.row).length); } return position; }; this.insertFullLines = function(row, lines) { row = Math.min(Math.max(row, 0), this.getLength()); var column = 0; if (row < this.getLength()) { lines = lines.concat([""]); column = 0; } else { lines = [""].concat(lines); row--; column = this.$lines[row].length; } this.insertMergedLines({row: row, column: column}, lines); }; this.insertMergedLines = function(position, lines) { var start = this.clippedPos(position.row, position.column); var end = { row: start.row + lines.length - 1, column: (lines.length == 1 ? start.column : 0) + lines[lines.length - 1].length }; this.applyDelta({ start: start, end: end, action: "insert", lines: lines }); return this.clonePos(end); }; this.remove = function(range) { var start = this.clippedPos(range.start.row, range.start.column); var end = this.clippedPos(range.end.row, range.end.column); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }); return this.clonePos(start); }; this.removeInLine = function(row, startColumn, endColumn) { var start = this.clippedPos(row, startColumn); var end = this.clippedPos(row, endColumn); this.applyDelta({ start: start, end: end, action: "remove", lines: this.getLinesForRange({start: start, end: end}) }, true); return this.clonePos(start); }; this.removeFullLines = function(firstRow, lastRow) { firstRow = Math.min(Math.max(0, firstRow), this.getLength() - 1); lastRow = Math.min(Math.max(0, lastRow ), this.getLength() - 1); var deleteFirstNewLine = lastRow == this.getLength() - 1 && firstRow > 0; var deleteLastNewLine = lastRow < this.getLength() - 1; var startRow = ( deleteFirstNewLine ? firstRow - 1 : firstRow ); var startCol = ( deleteFirstNewLine ? this.getLine(startRow).length : 0 ); var endRow = ( deleteLastNewLine ? lastRow + 1 : lastRow ); var endCol = ( deleteLastNewLine ? 0 : this.getLine(endRow).length ); var range = new Range(startRow, startCol, endRow, endCol); var deletedLines = this.$lines.slice(firstRow, lastRow + 1); this.applyDelta({ start: range.start, end: range.end, action: "remove", lines: this.getLinesForRange(range) }); return deletedLines; }; this.removeNewLine = function(row) { if (row < this.getLength() - 1 && row >= 0) { this.applyDelta({ start: this.pos(row, this.getLine(row).length), end: this.pos(row + 1, 0), action: "remove", lines: ["", ""] }); } }; this.replace = function(range, text) { if (!range instanceof Range) range = Range.fromPoints(range.start, range.end); if (text.length === 0 && range.isEmpty()) return range.start; if (text == this.getTextRange(range)) return range.end; this.remove(range); var end; if (text) { end = this.insert(range.start, text); } else { end = range.start; } return end; }; this.applyDeltas = function(deltas) { for (var i=0; i<deltas.length; i++) { this.applyDelta(deltas[i]); } }; this.revertDeltas = function(deltas) { for (var i=deltas.length-1; i>=0; i--) { this.revertDelta(deltas[i]); } }; this.applyDelta = function(delta, doNotValidate) { var isInsert = delta.action == "insert"; if (isInsert ? delta.lines.length <= 1 && !delta.lines[0] : !Range.comparePoints(delta.start, delta.end)) { return; } if (isInsert && delta.lines.length > 20000) this.$splitAndapplyLargeDelta(delta, 20000); applyDelta(this.$lines, delta, doNotValidate); this._signal("change", delta); }; this.$splitAndapplyLargeDelta = function(delta, MAX) { var lines = delta.lines; var l = lines.length; var row = delta.start.row; var column = delta.start.column; var from = 0, to = 0; do { from = to; to += MAX - 1; var chunk = lines.slice(from, to); if (to > l) { delta.lines = chunk; delta.start.row = row + from; delta.start.column = column; break; } chunk.push(""); this.applyDelta({ start: this.pos(row + from, column), end: this.pos(row + to, column = 0), action: delta.action, lines: chunk }, true); } while(true); }; this.revertDelta = function(delta) { this.applyDelta({ start: this.clonePos(delta.start), end: this.clonePos(delta.end), action: (delta.action == "insert" ? "remove" : "insert"), lines: delta.lines.slice() }); }; this.indexToPosition = function(index, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; for (var i = startRow || 0, l = lines.length; i < l; i++) { index -= lines[i].length + newlineLength; if (index < 0) return {row: i, column: index + lines[i].length + newlineLength}; } return {row: l-1, column: lines[l-1].length}; }; this.positionToIndex = function(pos, startRow) { var lines = this.$lines || this.getAllLines(); var newlineLength = this.getNewLineCharacter().length; var index = 0; var row = Math.min(pos.row, lines.length); for (var i = startRow || 0; i < row; ++i) index += lines[i].length + newlineLength; return index + pos.column; }; }).call(Document.prototype); exports.Document = Document; }); ace.define("ace/lib/lang",["require","exports","module"], function(require, exports, module) { "use strict"; exports.last = function(a) { return a[a.length - 1]; }; exports.stringReverse = function(string) { return string.split("").reverse().join(""); }; exports.stringRepeat = function (string, count) { var result = ''; while (count > 0) { if (count & 1) result += string; if (count >>= 1) string += string; } return result; }; var trimBeginRegexp = /^\s\s*/; var trimEndRegexp = /\s\s*$/; exports.stringTrimLeft = function (string) { return string.replace(trimBeginRegexp, ''); }; exports.stringTrimRight = function (string) { return string.replace(trimEndRegexp, ''); }; exports.copyObject = function(obj) { var copy = {}; for (var key in obj) { copy[key] = obj[key]; } return copy; }; exports.copyArray = function(array){ var copy = []; for (var i=0, l=array.length; i<l; i++) { if (array[i] && typeof array[i] == "object") copy[i] = this.copyObject( array[i] ); else copy[i] = array[i]; } return copy; }; exports.deepCopy = function deepCopy(obj) { if (typeof obj !== "object" || !obj) return obj; var copy; if (Array.isArray(obj)) { copy = []; for (var key = 0; key < obj.length; key++) { copy[key] = deepCopy(obj[key]); } return copy; } var cons = obj.constructor; if (cons === RegExp) return obj; copy = cons(); for (var key in obj) { copy[key] = deepCopy(obj[key]); } return copy; }; exports.arrayToMap = function(arr) { var map = {}; for (var i=0; i<arr.length; i++) { map[arr[i]] = 1; } return map; }; exports.createMap = function(props) { var map = Object.create(null); for (var i in props) { map[i] = props[i]; } return map; }; exports.arrayRemove = function(array, value) { for (var i = 0; i <= array.length; i++) { if (value === array[i]) { array.splice(i, 1); } } }; exports.escapeRegExp = function(str) { return str.replace(/([.*+?^${}()|[\]\/\\])/g, '\\$1'); }; exports.escapeHTML = function(str) { return str.replace(/&/g, "&#38;").replace(/"/g, "&#34;").replace(/'/g, "&#39;").replace(/</g, "&#60;"); }; exports.getMatchOffsets = function(string, regExp) { var matches = []; string.replace(regExp, function(str) { matches.push({ offset: arguments[arguments.length-2], length: str.length }); }); return matches; }; exports.deferredCall = function(fcn) { var timer = null; var callback = function() { timer = null; fcn(); }; var deferred = function(timeout) { deferred.cancel(); timer = setTimeout(callback, timeout || 0); return deferred; }; deferred.schedule = deferred; deferred.call = function() { this.cancel(); fcn(); return deferred; }; deferred.cancel = function() { clearTimeout(timer); timer = null; return deferred; }; deferred.isPending = function() { return timer; }; return deferred; }; exports.delayedCall = function(fcn, defaultTimeout) { var timer = null; var callback = function() { timer = null; fcn(); }; var _self = function(timeout) { if (timer == null) timer = setTimeout(callback, timeout || defaultTimeout); }; _self.delay = function(timeout) { timer && clearTimeout(timer); timer = setTimeout(callback, timeout || defaultTimeout); }; _self.schedule = _self; _self.call = function() { this.cancel(); fcn(); }; _self.cancel = function() { timer && clearTimeout(timer); timer = null; }; _self.isPending = function() { return timer; }; return _self; }; }); ace.define("ace/worker/mirror",["require","exports","module","ace/range","ace/document","ace/lib/lang"], function(require, exports, module) { "use strict"; var Range = require("../range").Range; var Document = require("../document").Document; var lang = require("../lib/lang"); var Mirror = exports.Mirror = function(sender) { this.sender = sender; var doc = this.doc = new Document(""); var deferredUpdate = this.deferredUpdate = lang.delayedCall(this.onUpdate.bind(this)); var _self = this; sender.on("change", function(e) { var data = e.data; if (data[0].start) { doc.applyDeltas(data); } else { for (var i = 0; i < data.length; i += 2) { if (Array.isArray(data[i+1])) { var d = {action: "insert", start: data[i], lines: data[i+1]}; } else { var d = {action: "remove", start: data[i], end: data[i+1]}; } doc.applyDelta(d, true); } } if (_self.$timeout) return deferredUpdate.schedule(_self.$timeout); _self.onUpdate(); }); }; (function() { this.$timeout = 500; this.setTimeout = function(timeout) { this.$timeout = timeout; }; this.setValue = function(value) { this.doc.setValue(value); this.deferredUpdate.schedule(this.$timeout); }; this.getValue = function(callbackId) { this.sender.callback(this.doc.getValue(), callbackId); }; this.onUpdate = function() { }; this.isPending = function() { return this.deferredUpdate.isPending(); }; }).call(Mirror.prototype); }); ace.define("ace/mode/lua/luaparse",["require","exports","module"], function(require, exports, module) { (function (root, name, factory) { factory(exports) }(this, 'luaparse', function (exports) { 'use strict'; exports.version = '0.1.4'; var input, options, length; var defaultOptions = exports.defaultOptions = { wait: false , comments: true , scope: false , locations: false , ranges: false }; var EOF = 1, StringLiteral = 2, Keyword = 4, Identifier = 8 , NumericLiteral = 16, Punctuator = 32, BooleanLiteral = 64 , NilLiteral = 128, VarargLiteral = 256; exports.tokenTypes = { EOF: EOF, StringLiteral: StringLiteral , Keyword: Keyword, Identifier: Identifier, NumericLiteral: NumericLiteral , Punctuator: Punctuator, BooleanLiteral: BooleanLiteral , NilLiteral: NilLiteral, VarargLiteral: VarargLiteral }; var errors = exports.errors = { unexpected: 'Unexpected %1 \'%2\' near \'%3\'' , expected: '\'%1\' expected near \'%2\'' , expectedToken: '%1 expected near \'%2\'' , unfinishedString: 'unfinished string near \'%1\'' , malformedNumber: 'malformed number near \'%1\'' }; var ast = exports.ast = { labelStatement: function(label) { return { type: 'LabelStatement' , label: label }; } , breakStatement: function() { return { type: 'BreakStatement' }; } , gotoStatement: function(label) { return { type: 'GotoStatement' , label: label }; } , returnStatement: function(args) { return { type: 'ReturnStatement' , 'arguments': args }; } , ifStatement: function(clauses) { return { type: 'IfStatement' , clauses: clauses }; } , ifClause: function(condition, body) { return { type: 'IfClause' , condition: condition , body: body }; } , elseifClause: function(condition, body) { return { type: 'ElseifClause' , condition: condition , body: body }; } , elseClause: function(body) { return { type: 'ElseClause' , body: body }; } , whileStatement: function(condition, body) { return { type: 'WhileStatement' , condition: condition , body: body }; } , doStatement: function(body) { return { type: 'DoStatement' , body: body }; } , repeatStatement: function(condition, body) { return { type: 'RepeatStatement' , condition: condition , body: body }; } , localStatement: function(variables, init) { return { type: 'LocalStatement' , variables: variables , init: init }; } , assignmentStatement: function(variables, init) { return { type: 'AssignmentStatement' , variables: variables , init: init }; } , callStatement: function(expression) { return { type: 'CallStatement' , expression: expression }; } , functionStatement: function(identifier, parameters, isLocal, body) { return { type: 'FunctionDeclaration' , identifier: identifier , isLocal: isLocal , parameters: parameters , body: body }; } , forNumericStatement: function(variable, start, end, step, body) { return { type: 'ForNumericStatement' , variable: variable , start: start , end: end , step: step , body: body }; } , forGenericStatement: function(variables, iterators, body) { return { type: 'ForGenericStatement' , variables: variables , iterators: iterators , body: body }; } , chunk: function(body) { return { type: 'Chunk' , body: body }; } , identifier: function(name) { return { type: 'Identifier' , name: name }; } , literal: function(type, value, raw) { type = (type === StringLiteral) ? 'StringLiteral' : (type === NumericLiteral) ? 'NumericLiteral' : (type === BooleanLiteral) ? 'BooleanLiteral' : (type === NilLiteral) ? 'NilLiteral' : 'VarargLiteral'; return { type: type , value: value , raw: raw }; } , tableKey: function(key, value) { return { type: 'TableKey' , key: key , value: value }; } , tableKeyString: function(key, value) { return { type: 'TableKeyString' , key: key , value: value }; } , tableValue: function(value) { return { type: 'TableValue' , value: value }; } , tableConstructorExpression: function(fields) { return { type: 'TableConstructorExpression' , fields: fields }; } , binaryExpression: function(operator, left, right) { var type = ('and' === operator || 'or' === operator) ? 'LogicalExpression' : 'BinaryExpression'; return { type: type , operator: operator , left: left , right: right }; } , unaryExpression: function(operator, argument) { return { type: 'UnaryExpression' , operator: operator , argument: argument }; } , memberExpression: function(base, indexer, identifier) { return { type: 'MemberExpression' , indexer: indexer , identifier: identifier , base: base }; } , indexExpression: function(base, index) { return { type: 'IndexExpression' , base: base , index: index }; } , callExpression: function(base, args) { return { type: 'CallExpression' , base: base , 'arguments': args }; } , tableCallExpression: function(base, args) { return { type: 'TableCallExpression' , base: base , 'arguments': args }; } , stringCallExpression: function(base, argument) { return { type: 'StringCallExpression' , base: base , argument: argument }; } , comment: function(value, raw) { return { type: 'Comment' , value: value , raw: raw }; } }; function finishNode(node) { if (trackLocations) { var location = locations.pop(); location.complete(); if (options.locations) node.loc = location.loc; if (options.ranges) node.range = location.range; } return node; } var slice = Array.prototype.slice , toString = Object.prototype.toString , indexOf = function indexOf(array, element) { for (var i = 0, length = array.length; i < length; i++) { if (array[i] === element) return i; } return -1; }; function indexOfObject(array, property, element) { for (var i = 0, length = array.length; i < length; i++) { if (array[i][property] === element) return i; } return -1; } function sprintf(format) { var args = slice.call(arguments, 1); format = format.replace(/%(\d)/g, function (match, index) { return '' + args[index - 1] || ''; }); return format; } function extend() { var args = slice.call(arguments) , dest = {} , src, prop; for (var i = 0, length = args.length; i < length; i++) { src = args[i]; for (prop in src) if (src.hasOwnProperty(prop)) { dest[prop] = src[prop]; } } return dest; } function raise(token) { var message = sprintf.apply(null, slice.call(arguments, 1)) , error, col; if ('undefined' !== typeof token.line) { col = token.range[0] - token.lineStart; error = new SyntaxError(sprintf('[%1:%2] %3', token.line, col, message)); error.line = token.line; error.index = token.range[0]; error.column = col; } else { col = index - lineStart + 1; error = new SyntaxError(sprintf('[%1:%2] %3', line, col, message)); error.index = index; error.line = line; error.column = col; } throw error; } function raiseUnexpectedToken(type, token) { raise(token, errors.expectedToken, type, token.value); } function unexpected(found, near) { if ('undefined' === typeof near) near = lookahead.value; if ('undefined' !== typeof found.type) { var type; switch (found.type) { case StringLiteral: type = 'string'; break; case Keyword: type = 'keyword'; break; case Identifier: type = 'identifier'; break; case NumericLiteral: type = 'number'; break; case Punctuator: type = 'symbol'; break; case BooleanLiteral: type = 'boolean'; break; case NilLiteral: return raise(found, errors.unexpected, 'symbol', 'nil', near); } return raise(found, errors.unexpected, type, found.value, near); } return raise(found, errors.unexpected, 'symbol', found, near); } var index , token , previousToken , lookahead , comments , tokenStart , line , lineStart; exports.lex = lex; function lex() { skipWhiteSpace(); while (45 === input.charCodeAt(index) && 45 === input.charCodeAt(index + 1)) { scanComment(); skipWhiteSpace(); } if (index >= length) return { type : EOF , value: '<eof>' , line: line , lineStart: lineStart , range: [index, index] }; var charCode = input.charCodeAt(index) , next = input.charCodeAt(index + 1); tokenStart = index; if (isIdentifierStart(charCode)) return scanIdentifierOrKeyword(); switch (charCode) { case 39: case 34: // '" return scanStringLiteral(); case 48: case 49: case 50: case 51: case 52: case 53: case 54: case 55: case 56: case 57: return scanNumericLiteral(); case 46: // . if (isDecDigit(next)) return scanNumericLiteral(); if (46 === next) { if (46 === input.charCodeAt(index + 2)) return scanVarargLiteral(); return scanPunctuator('..'); } return scanPunctuator('.'); case 61: // = if (61 === next) return scanPunctuator('=='); return scanPunctuator('='); case 62: // > if (61 === next) return scanPunctuator('>='); return scanPunctuator('>'); case 60: // < if (61 === next) return scanPunctuator('<='); return scanPunctuator('<'); case 126: // ~ if (61 === next) return scanPunctuator('~='); return raise({}, errors.expected, '=', '~'); case 58: // : if (58 === next) return scanPunctuator('::'); return scanPunctuator(':'); case 91: // [ if (91 === next || 61 === next) return scanLongStringLiteral(); return scanPunctuator('['); case 42: case 47: case 94: case 37: case 44: case 123: case 125: case 93: case 40: case 41: case 59: case 35: case 45: case 43: return scanPunctuator(input.charAt(index)); } return unexpected(input.charAt(index)); } function skipWhiteSpace() { while (index < length) { var charCode = input.charCodeAt(index); if (isWhiteSpace(charCode)) { index++; } else if (isLineTerminator(charCode)) { line++; lineStart = ++index; } else { break; } } } function scanIdentifierOrKeyword() { var value, type; while (isIdentifierPart(input.charCodeAt(++index))); value = input.slice(tokenStart, index); if (isKeyword(value)) { type = Keyword; } else if ('true' === value || 'false' === value) { type = BooleanLiteral; value = ('true' === value); } else if ('nil' === value) { type = NilLiteral; value = null; } else { type = Identifier; } return { type: type , value: value , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanPunctuator(value) { index += value.length; return { type: Punctuator , value: value , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanVarargLiteral() { index += 3; return { type: VarargLiteral , value: '...' , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanStringLiteral() { var delimiter = input.charCodeAt(index++) , stringStart = index , string = '' , charCode; while (index < length) { charCode = input.charCodeAt(index++); if (delimiter === charCode) break; if (92 === charCode) { // \ string += input.slice(stringStart, index - 1) + readEscapeSequence(); stringStart = index; } else if (index >= length || isLineTerminator(charCode)) { string += input.slice(stringStart, index - 1); raise({}, errors.unfinishedString, string + String.fromCharCode(charCode)); } } string += input.slice(stringStart, index - 1); return { type: StringLiteral , value: string , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanLongStringLiteral() { var string = readLongString(); if (false === string) raise(token, errors.expected, '[', token.value); return { type: StringLiteral , value: string , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function scanNumericLiteral() { var character = input.charAt(index) , next = input.charAt(index + 1); var value = ('0' === character && 'xX'.indexOf(next || null) >= 0) ? readHexLiteral() : readDecLiteral(); return { type: NumericLiteral , value: value , line: line , lineStart: lineStart , range: [tokenStart, index] }; } function readHexLiteral() { var fraction = 0 // defaults to 0 as it gets summed , binaryExponent = 1 // defaults to 1 as it gets multiplied , binarySign = 1 // positive , digit, fractionStart, exponentStart, digitStart; digitStart = index += 2; // Skip 0x part if (!isHexDigit(input.charCodeAt(index))) raise({}, errors.malformedNumber, input.slice(tokenStart, index)); while (isHexDigit(input.charCodeAt(index))) index++; digit = parseInt(input.slice(digitStart, index), 16); if ('.' === input.charAt(index)) { fractionStart = ++index; while (isHexDigit(input.charCodeAt(index))) index++; fraction = input.slice(fractionStart, index); fraction = (fractionStart === index) ? 0 : parseInt(fraction, 16) / Math.pow(16, index - fractionStart); } if ('pP'.indexOf(input.charAt(index) || null) >= 0) { index++; if ('+-'.indexOf(input.charAt(index) || null) >= 0) binarySign = ('+' === input.charAt(index++)) ? 1 : -1; exponentStart = index; if (!isDecDigit(input.charCodeAt(index))) raise({}, errors.malformedNumber, input.slice(tokenStart, index)); while (isDecDigit(input.charCodeAt(index))) index++; binaryExponent = input.slice(exponentStart, index); binaryExponent = Math.pow(2, binaryExponent * binarySign); } return (digit + fraction) * binaryExponent; } function readDecLiteral() { while (isDecDigit(input.charCodeAt(index))) index++; if ('.' === input.charAt(index)) { index++; while (isDecDigit(input.charCodeAt(index))) index++; } if ('eE'.indexOf(input.charAt(index) || null) >= 0) { index++; if ('+-'.indexOf(input.charAt(index) || null) >= 0) index++; if (!isDecDigit(input.charCodeAt(index))) raise({}, errors.malformedNumber, input.slice(tokenStart, index)); while (isDecDigit(input.charCodeAt(index))) index++; } return parseFloat(input.slice(tokenStart, index)); } function readEscapeSequence() { var sequenceStart = index; switch (input.charAt(index)) { case 'n': index++; return '\n'; case 'r': index++; return '\r'; case 't': index++; return '\t'; case 'v': index++; return '\x0B'; case 'b': index++; return '\b'; case 'f': index++; return '\f'; case 'z': index++; skipWhiteSpace(); return ''; case 'x': if (isHexDigit(input.charCodeAt(index + 1)) && isHexDigit(input.charCodeAt(index + 2))) { index += 3; return '\\' + input.slice(sequenceStart, index); } return '\\' + input.charAt(index++); default: if (isDecDigit(input.charCodeAt(index))) { while (isDecDigit(input.charCodeAt(++index))); return '\\' + input.slice(sequenceStart, index); } return input.charAt(index++); } } function scanComment() { tokenStart = index; index += 2; // -- var character = input.charAt(index) , content = '' , isLong = false , commentStart = index , lineStartComment = lineStart , lineComment = line; if ('[' === character) { content = readLongString(); if (false === content) content = character; else isLong = true; } if (!isLong) { while (index < length) { if (isLineTerminator(input.charCodeAt(index))) break; index++; } if (options.comments) content = input.slice(commentStart, index); } if (options.comments) { var node = ast.comment(content, input.slice(tokenStart, index)); if (options.locations) { node.loc = { start: { line: lineComment, column: tokenStart - lineStartComment } , end: { line: line, column: index - lineStart } }; } if (options.ranges) { node.range = [tokenStart, index]; } comments.push(node); } } function readLongString() { var level = 0 , content = '' , terminator = false , character, stringStart; index++; // [ while ('=' === input.charAt(index + level)) level++; if ('[' !== input.charAt(index + level)) return false; index += level + 1; if (isLineTerminator(input.charCodeAt(index))) { line++; lineStart = index++; } stringStart = index; while (index < length) { character = input.charAt(index++); if (isLineTerminator(character.charCodeAt(0))) { line++; lineStart = index; } if (']' === character) { terminator = true; for (var i = 0; i < level; i++) { if ('=' !== input.charAt(index + i)) terminator = false; } if (']' !== input.charAt(index + level)) terminator = false; } if (terminator) break; } content += input.slice(stringStart, index - 1); index += level + 1; return content; } function next() { previousToken = token; token = lookahead; lookahead = lex(); } function consume(value) { if (value === token.value) { next(); return true; } return false; } function expect(value) { if (value === token.value) next(); else raise(token, errors.expected, value, token.value); } function isWhiteSpace(charCode) { return 9 === charCode || 32 === charCode || 0xB === charCode || 0xC === charCode; } function isLineTerminator(charCode) { return 10 === charCode || 13 === charCode; } function isDecDigit(charCode) { return charCode >= 48 && charCode <= 57; } function isHexDigit(charCode) { return (charCode >= 48 && charCode <= 57) || (charCode >= 97 && charCode <= 102) || (charCode >= 65 && charCode <= 70); } function isIdentifierStart(charCode) { return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode; } function isIdentifierPart(charCode) { return (charCode >= 65 && charCode <= 90) || (charCode >= 97 && charCode <= 122) || 95 === charCode || (charCode >= 48 && charCode <= 57); } function isKeyword(id) { switch (id.length) { case 2: return 'do' === id || 'if' === id || 'in' === id || 'or' === id; case 3: return 'and' === id || 'end' === id || 'for' === id || 'not' === id; case 4: return 'else' === id || 'goto' === id || 'then' === id; case 5: return 'break' === id || 'local' === id || 'until' === id || 'while' === id; case 6: return 'elseif' === id || 'repeat' === id || 'return' === id; case 8: return 'function' === id; } return false; } function isUnary(token) { if (Punctuator === token.type) return '#-'.indexOf(token.value) >= 0; if (Keyword === token.type) return 'not' === token.value; return false; } function isCallExpression(expression) { switch (expression.type) { case 'CallExpression': case 'TableCallExpression': case 'StringCallExpression': return true; } return false; } function isBlockFollow(token) { if (EOF === token.type) return true; if (Keyword !== token.type) return false; switch (token.value) { case 'else': case 'elseif': case 'end': case 'until': return true; default: return false; } } var scopes , scopeDepth , globals; function createScope() { scopes.push(Array.apply(null, scopes[scopeDepth++])); } function exitScope() { scopes.pop(); scopeDepth--; } function scopeIdentifierName(name) { if (-1 !== indexOf(scopes[scopeDepth], name)) return; scopes[scopeDepth].push(name); } function scopeIdentifier(node) { scopeIdentifierName(node.name); attachScope(node, true); } function attachScope(node, isLocal) { if (!isLocal && -1 === indexOfObject(globals, 'name', node.name)) globals.push(node); node.isLocal = isLocal; } function scopeHasName(name) { return (-1 !== indexOf(scopes[scopeDepth], name)); } var locations = [] , trackLocations; function createLocationMarker() { return new Marker(token); } function Marker(token) { if (options.locations) { this.loc = { start: { line: token.line , column: token.range[0] - token.lineStart } , end: { line: 0 , column: 0 } }; } if (options.ranges) this.range = [token.range[0], 0]; } Marker.prototype.complete = function() { if (options.locations) { this.loc.end.line = previousToken.line; this.loc.end.column = previousToken.range[1] - previousToken.lineStart; } if (options.ranges) { this.range[1] = previousToken.range[1]; } }; function markLocation() { if (trackLocations) locations.push(createLocationMarker()); } function pushLocation(marker) { if (trackLocations) locations.push(marker); } function parseChunk() { next(); markLocation(); var body = parseBlock(); if (EOF !== token.type) unexpected(token); if (trackLocations && !body.length) previousToken = token; return finishNode(ast.chunk(body)); } function parseBlock(terminator) { var block = [] , statement; if (options.scope) createScope(); while (!isBlockFollow(token)) { if ('return' === token.value) { block.push(parseStatement()); break; } statement = parseStatement(); if (statement) block.push(statement); } if (options.scope) exitScope(); return block; } function parseStatement() { markLocation(); if (Keyword === token.type) { switch (token.value) { case 'local': next(); return parseLocalStatement(); case 'if': next(); return parseIfStatement(); case 'return': next(); return parseReturnStatement(); case 'function': next(); var name = parseFunctionName(); return parseFunctionDeclaration(name); case 'while': next(); return parseWhileStatement(); case 'for': next(); return parseForStatement(); case 'repeat': next(); return parseRepeatStatement(); case 'break': next(); return parseBreakStatement(); case 'do': next(); return parseDoStatement(); case 'goto': next(); return parseGotoStatement(); } } if (Punctuator === token.type) { if (consume('::')) return parseLabelStatement(); } if (trackLocations) locations.pop(); if (consume(';')) return; return parseAssignmentOrCallStatement(); } function parseLabelStatement() { var name = token.value , label = parseIdentifier(); if (options.scope) { scopeIdentifierName('::' + name + '::'); attachScope(label, true); } expect('::'); return finishNode(ast.labelStatement(label)); } function parseBreakStatement() { return finishNode(ast.breakStatement()); } function parseGotoStatement() { var name = token.value , label = parseIdentifier(); if (options.scope) label.isLabel = scopeHasName('::' + name + '::'); return finishNode(ast.gotoStatement(label)); } function parseDoStatement() { var body = parseBlock(); expect('end'); return finishNode(ast.doStatement(body)); } function parseWhileStatement() { var condition = parseExpectedExpression(); expect('do'); var body = parseBlock(); expect('end'); return finishNode(ast.whileStatement(condition, body)); } function parseRepeatStatement() { var body = parseBlock(); expect('until'); var condition = parseExpectedExpression(); return finishNode(ast.repeatStatement(condition, body)); } function parseReturnStatement() { var expressions = []; if ('end' !== token.value) { var expression = parseExpression(); if (null != expression) expressions.push(expression); while (consume(',')) { expression = parseExpectedExpression(); expressions.push(expression); } consume(';'); // grammar tells us ; is optional here. } return finishNode(ast.returnStatement(expressions)); } function parseIfStatement() { var clauses = [] , condition , body , marker; if (trackLocations) { marker = locations[locations.length - 1]; locations.push(marker); } condition = parseExpectedExpression(); expect('then'); body = parseBlock(); clauses.push(finishNode(ast.ifClause(condition, body))); if (trackLocations) marker = createLocationMarker(); while (consume('elseif')) { pushLocation(marker); condition = parseExpectedExpression(); expect('then'); body = parseBlock(); clauses.push(finishNode(ast.elseifClause(condition, body))); if (trackLocations) marker = createLocationMarker(); } if (consume('else')) { if (trackLocations) { marker = new Marker(previousToken); locations.push(marker); } body = parseBlock(); clauses.push(finishNode(ast.elseClause(body))); } expect('end'); return finishNode(ast.ifStatement(clauses)); } function parseForStatement() { var variable = parseIdentifier() , body; if (options.scope) scopeIdentifier(variable); if (consume('=')) { var start = parseExpectedExpression(); expect(','); var end = parseExpectedExpression(); var step = consume(',') ? parseExpectedExpression() : null; expect('do'); body = parseBlock(); expect('end'); return finishNode(ast.forNumericStatement(variable, start, end, step, body)); } else { var variables = [variable]; while (consume(',')) { variable = parseIdentifier(); if (options.scope) scopeIdentifier(variable); variables.push(variable); } expect('in'); var iterators = []; do { var expression = parseExpectedExpression(); iterators.push(expression); } while (consume(',')); expect('do'); body = parseBlock(); expect('end'); return finishNode(ast.forGenericStatement(variables, iterators, body)); } } function parseLocalStatement() { var name; if (Identifier === token.type) { var variables = [] , init = []; do { name = parseIdentifier(); variables.push(name); } while (consume(',')); if (consume('=')) { do { var expression = parseExpectedExpression(); init.push(expression); } while (consume(',')); } if (options.scope) { for (var i = 0, l = variables.length; i < l; i++) { scopeIdentifier(variables[i]); } } return finishNode(ast.localStatement(variables, init)); } if (consume('function')) { name = parseIdentifier(); if (options.scope) scopeIdentifier(name); return parseFunctionDeclaration(name, true); } else { raiseUnexpectedToken('<name>', token); } } function parseAssignmentOrCallStatement() { var previous = token , expression, marker; if (trackLocations) marker = createLocationMarker(); expression = parsePrefixExpression(); if (null == expression) return unexpected(token); if (',='.indexOf(token.value) >= 0) { var variables = [expression] , init = [] , exp; while (consume(',')) { exp = parsePrefixExpression(); if (null == exp) raiseUnexpectedToken('<expression>', token); variables.push(exp); } expect('='); do { exp = parseExpectedExpression(); init.push(exp); } while (consume(',')); pushLocation(marker); return finishNode(ast.assignmentStatement(variables, init)); } if (isCallExpression(expression)) { pushLocation(marker); return finishNode(ast.callStatement(expression)); } return unexpected(previous); } function parseIdentifier() { markLocation(); var identifier = token.value; if (Identifier !== token.type) raiseUnexpectedToken('<name>', token); next(); return finishNode(ast.identifier(identifier)); } function parseFunctionDeclaration(name, isLocal) { var parameters = []; expect('('); if (!consume(')')) { while (true) { if (Identifier === token.type) { var parameter = parseIdentifier(); if (options.scope) scopeIdentifier(parameter); parameters.push(parameter); if (consume(',')) continue; else if (consume(')')) break; } else if (VarargLiteral === token.type) { parameters.push(parsePrimaryExpression()); expect(')'); break; } else { raiseUnexpectedToken('<name> or \'...\'', token); } } } var body = parseBlock(); expect('end'); isLocal = isLocal || false; return finishNode(ast.functionStatement(name, parameters, isLocal, body)); } function parseFunctionName() { var base, name, marker; if (trackLocations) marker = createLocationMarker(); base = parseIdentifier(); if (options.scope) attachScope(base, false); while (consume('.')) { pushLocation(marker); name = parseIdentifier(); if (options.scope) attachScope(name, false); base = finishNode(ast.memberExpression(base, '.', name)); } if (consume(':')) { pushLocation(marker); name = parseIdentifier(); if (options.scope) attachScope(name, false); base = finishNode(ast.memberExpression(base, ':', name)); } return base; } function parseTableConstructor() { var fields = [] , key, value; while (true) { markLocation(); if (Punctuator === token.type && consume('[')) { key = parseExpectedExpression(); expect(']'); expect('='); value = parseExpectedExpression(); fields.push(finishNode(ast.tableKey(key, value))); } else if (Identifier === token.type) { key = parseExpectedExpression(); if (consume('=')) { value = parseExpectedExpression(); fields.push(finishNode(ast.tableKeyString(key, value))); } else { fields.push(finishNode(ast.tableValue(key))); } } else { if (null == (value = parseExpression())) { locations.pop(); break; } fields.push(finishNode(ast.tableValue(value))); } if (',;'.indexOf(token.value) >= 0) { next(); continue; } if ('}' === token.value) break; } expect('}'); return finishNode(ast.tableConstructorExpression(fields)); } function parseExpression() { var expression = parseSubExpression(0); return expression; } function parseExpectedExpression() { var expression = parseExpression(); if (null == expression) raiseUnexpectedToken('<expression>', token); else return expression; } function binaryPrecedence(operator) { var charCode = operator.charCodeAt(0) , length = operator.length; if (1 === length) { switch (charCode) { case 94: return 10; // ^ case 42: case 47: case 37: return 7; // * / % case 43: case 45: return 6; // + - case 60: case 62: return 3; // < > } } else if (2 === length) { switch (charCode) { case 46: return 5; // .. case 60: case 62: case 61: case 126: return 3; // <= >= == ~= case 111: return 1; // or } } else if (97 === charCode && 'and' === operator) return 2; return 0; } function parseSubExpression(minPrecedence) { var operator = token.value , expression, marker; if (trackLocations) marker = createLocationMarker(); if (isUnary(token)) { markLocation(); next(); var argument = parseSubExpression(8); if (argument == null) raiseUnexpectedToken('<expression>', token); expression = finishNode(ast.unaryExpression(operator, argument)); } if (null == expression) { expression = parsePrimaryExpression(); if (null == expression) { expression = parsePrefixExpression(); } } if (null == expression) return null; var precedence; while (true) { operator = token.value; precedence = (Punctuator === token.type || Keyword === token.type) ? binaryPrecedence(operator) : 0; if (precedence === 0 || precedence <= minPrecedence) break; if ('^' === operator || '..' === operator) precedence--; next(); var right = parseSubExpression(precedence); if (null == right) raiseUnexpectedToken('<expression>', token); if (trackLocations) locations.push(marker); expression = finishNode(ast.binaryExpression(operator, expression, right)); } return expression; } function parsePrefixExpression() { var base, name, marker , isLocal; if (trackLocations) marker = createLocationMarker(); if (Identifier === token.type) { name = token.value; base = parseIdentifier(); if (options.scope) attachScope(base, isLocal = scopeHasName(name)); } else if (consume('(')) { base = parseExpectedExpression(); expect(')'); if (options.scope) isLocal = base.isLocal; } else { return null; } var expression, identifier; while (true) { if (Punctuator === token.type) { switch (token.value) { case '[': pushLocation(marker); next(); expression = parseExpectedExpression(); base = finishNode(ast.indexExpression(base, expression)); expect(']'); break; case '.': pushLocation(marker); next(); identifier = parseIdentifier(); if (options.scope) attachScope(identifier, isLocal); base = finishNode(ast.memberExpression(base, '.', identifier)); break; case ':': pushLocation(marker); next(); identifier = parseIdentifier(); if (options.scope) attachScope(identifier, isLocal); base = finishNode(ast.memberExpression(base, ':', identifier)); pushLocation(marker); base = parseCallExpression(base); break; case '(': case '{': // args pushLocation(marker); base = parseCallExpression(base); break; default: return base; } } else if (StringLiteral === token.type) { pushLocation(marker); base = parseCallExpression(base); } else { break; } } return base; } function parseCallExpression(base) { if (Punctuator === token.type) { switch (token.value) { case '(': next(); var expressions = []; var expression = parseExpression(); if (null != expression) expressions.push(expression); while (consume(',')) { expression = parseExpectedExpression(); expressions.push(expression); } expect(')'); return finishNode(ast.callExpression(base, expressions)); case '{': markLocation(); next(); var table = parseTableConstructor(); return finishNode(ast.tableCallExpression(base, table)); } } else if (StringLiteral === token.type) { return finishNode(ast.stringCallExpression(base, parsePrimaryExpression())); } raiseUnexpectedToken('function arguments', token); } function parsePrimaryExpression() { var literals = StringLiteral | NumericLiteral | BooleanLiteral | NilLiteral | VarargLiteral , value = token.value , type = token.type , marker; if (trackLocations) marker = createLocationMarker(); if (type & literals) { pushLocation(marker); var raw = input.slice(token.range[0], token.range[1]); next(); return finishNode(ast.literal(type, value, raw)); } else if (Keyword === type && 'function' === value) { pushLocation(marker); next(); return parseFunctionDeclaration(null); } else if (consume('{')) { pushLocation(marker); return parseTableConstructor(); } } exports.parse = parse; function parse(_input, _options) { if ('undefined' === typeof _options && 'object' === typeof _input) { _options = _input; _input = undefined; } if (!_options) _options = {}; input = _input || ''; options = extend(defaultOptions, _options); index = 0; line = 1; lineStart = 0; length = input.length; scopes = [[]]; scopeDepth = 0; globals = []; locations = []; if (options.comments) comments = []; if (!options.wait) return end(); return exports; } exports.write = write; function write(_input) { input += String(_input); length = input.length; return exports; } exports.end = end; function end(_input) { if ('undefined' !== typeof _input) write(_input); length = input.length; trackLocations = options.locations || options.ranges; lookahead = lex(); var chunk = parseChunk(); if (options.comments) chunk.comments = comments; if (options.scope) chunk.globals = globals; if (locations.length > 0) throw new Error('Location tracking failed. This is most likely a bug in luaparse'); return chunk; } })); }); ace.define("ace/mode/lua_worker",["require","exports","module","ace/lib/oop","ace/worker/mirror","ace/mode/lua/luaparse"], function(require, exports, module) { "use strict"; var oop = require("../lib/oop"); var Mirror = require("../worker/mirror").Mirror; var luaparse = require("../mode/lua/luaparse"); var Worker = exports.Worker = function(sender) { Mirror.call(this, sender); this.setTimeout(500); }; oop.inherits(Worker, Mirror); (function() { this.onUpdate = function() { var value = this.doc.getValue(); var errors = []; try { luaparse.parse(value); } catch(e) { if (e instanceof SyntaxError) { errors.push({ row: e.line - 1, column: e.column, text: e.message, type: "error" }); } } this.sender.emit("annotate", errors); }; }).call(Worker.prototype); }); ace.define("ace/lib/es5-shim",["require","exports","module"], function(require, exports, module) { function Empty() {} if (!Function.prototype.bind) { Function.prototype.bind = function bind(that) { // .length is 1 var target = this; if (typeof target != "function") { throw new TypeError("Function.prototype.bind called on incompatible " + target); } var args = slice.call(arguments, 1); // for normal call var bound = function () { if (this instanceof bound) { var result = target.apply( this, args.concat(slice.call(arguments)) ); if (Object(result) === result) { return result; } return this; } else { return target.apply( that, args.concat(slice.call(arguments)) ); } }; if(target.prototype) { Empty.prototype = target.prototype; bound.prototype = new Empty(); Empty.prototype = null; } return bound; }; } var call = Function.prototype.call; var prototypeOfArray = Array.prototype; var prototypeOfObject = Object.prototype; var slice = prototypeOfArray.slice; var _toString = call.bind(prototypeOfObject.toString); var owns = call.bind(prototypeOfObject.hasOwnProperty); var defineGetter; var defineSetter; var lookupGetter; var lookupSetter; var supportsAccessors; if ((supportsAccessors = owns(prototypeOfObject, "__defineGetter__"))) { defineGetter = call.bind(prototypeOfObject.__defineGetter__); defineSetter = call.bind(prototypeOfObject.__defineSetter__); lookupGetter = call.bind(prototypeOfObject.__lookupGetter__); lookupSetter = call.bind(prototypeOfObject.__lookupSetter__); } if ([1,2].splice(0).length != 2) { if(function() { // test IE < 9 to splice bug - see issue #138 function makeArray(l) { var a = new Array(l+2); a[0] = a[1] = 0; return a; } var array = [], lengthBefore; array.splice.apply(array, makeArray(20)); array.splice.apply(array, makeArray(26)); lengthBefore = array.length; //46 array.splice(5, 0, "XXX"); // add one element lengthBefore + 1 == array.length if (lengthBefore + 1 == array.length) { return true;// has right splice implementation without bugs } }()) {//IE 6/7 var array_splice = Array.prototype.splice; Array.prototype.splice = function(start, deleteCount) { if (!arguments.length) { return []; } else { return array_splice.apply(this, [ start === void 0 ? 0 : start, deleteCount === void 0 ? (this.length - start) : deleteCount ].concat(slice.call(arguments, 2))) } }; } else {//IE8 Array.prototype.splice = function(pos, removeCount){ var length = this.length; if (pos > 0) { if (pos > length) pos = length; } else if (pos == void 0) { pos = 0; } else if (pos < 0) { pos = Math.max(length + pos, 0); } if (!(pos+removeCount < length)) removeCount = length - pos; var removed = this.slice(pos, pos+removeCount); var insert = slice.call(arguments, 2); var add = insert.length; if (pos === length) { if (add) { this.push.apply(this, insert); } } else { var remove = Math.min(removeCount, length - pos); var tailOldPos = pos + remove; var tailNewPos = tailOldPos + add - remove; var tailCount = length - tailOldPos; var lengthAfterRemove = length - remove; if (tailNewPos < tailOldPos) { // case A for (var i = 0; i < tailCount; ++i) { this[tailNewPos+i] = this[tailOldPos+i]; } } else if (tailNewPos > tailOldPos) { // case B for (i = tailCount; i--; ) { this[tailNewPos+i] = this[tailOldPos+i]; } } // else, add == remove (nothing to do) if (add && pos === lengthAfterRemove) { this.length = lengthAfterRemove; // truncate array this.push.apply(this, insert); } else { this.length = lengthAfterRemove + add; // reserves space for (i = 0; i < add; ++i) { this[pos+i] = insert[i]; } } } return removed; }; } } if (!Array.isArray) { Array.isArray = function isArray(obj) { return _toString(obj) == "[object Array]"; }; } var boxedString = Object("a"), splitString = boxedString[0] != "a" || !(0 in boxedString); if (!Array.prototype.forEach) { Array.prototype.forEach = function forEach(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, thisp = arguments[1], i = -1, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(); // TODO message } while (++i < length) { if (i in self) { fun.call(thisp, self[i], i, object); } } }; } if (!Array.prototype.map) { Array.prototype.map = function map(fun /*, thisp*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = Array(length), thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) result[i] = fun.call(thisp, self[i], i, object); } return result; }; } if (!Array.prototype.filter) { Array.prototype.filter = function filter(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, result = [], value, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self) { value = self[i]; if (fun.call(thisp, value, i, object)) { result.push(value); } } } return result; }; } if (!Array.prototype.every) { Array.prototype.every = function every(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && !fun.call(thisp, self[i], i, object)) { return false; } } return true; }; } if (!Array.prototype.some) { Array.prototype.some = function some(fun /*, thisp */) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0, thisp = arguments[1]; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } for (var i = 0; i < length; i++) { if (i in self && fun.call(thisp, self[i], i, object)) { return true; } } return false; }; } if (!Array.prototype.reduce) { Array.prototype.reduce = function reduce(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduce of empty array with no initial value"); } var i = 0; var result; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i++]; break; } if (++i >= length) { throw new TypeError("reduce of empty array with no initial value"); } } while (true); } for (; i < length; i++) { if (i in self) { result = fun.call(void 0, result, self[i], i, object); } } return result; }; } if (!Array.prototype.reduceRight) { Array.prototype.reduceRight = function reduceRight(fun /*, initial*/) { var object = toObject(this), self = splitString && _toString(this) == "[object String]" ? this.split("") : object, length = self.length >>> 0; if (_toString(fun) != "[object Function]") { throw new TypeError(fun + " is not a function"); } if (!length && arguments.length == 1) { throw new TypeError("reduceRight of empty array with no initial value"); } var result, i = length - 1; if (arguments.length >= 2) { result = arguments[1]; } else { do { if (i in self) { result = self[i--]; break; } if (--i < 0) { throw new TypeError("reduceRight of empty array with no initial value"); } } while (true); } do { if (i in this) { result = fun.call(void 0, result, self[i], i, object); } } while (i--); return result; }; } if (!Array.prototype.indexOf || ([0, 1].indexOf(1, 2) != -1)) { Array.prototype.indexOf = function indexOf(sought /*, fromIndex */ ) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = 0; if (arguments.length > 1) { i = toInteger(arguments[1]); } i = i >= 0 ? i : Math.max(0, length + i); for (; i < length; i++) { if (i in self && self[i] === sought) { return i; } } return -1; }; } if (!Array.prototype.lastIndexOf || ([0, 1].lastIndexOf(0, -3) != -1)) { Array.prototype.lastIndexOf = function lastIndexOf(sought /*, fromIndex */) { var self = splitString && _toString(this) == "[object String]" ? this.split("") : toObject(this), length = self.length >>> 0; if (!length) { return -1; } var i = length - 1; if (arguments.length > 1) { i = Math.min(i, toInteger(arguments[1])); } i = i >= 0 ? i : length - Math.abs(i); for (; i >= 0; i--) { if (i in self && sought === self[i]) { return i; } } return -1; }; } if (!Object.getPrototypeOf) { Object.getPrototypeOf = function getPrototypeOf(object) { return object.__proto__ || ( object.constructor ? object.constructor.prototype : prototypeOfObject ); }; } if (!Object.getOwnPropertyDescriptor) { var ERR_NON_OBJECT = "Object.getOwnPropertyDescriptor called on a " + "non-object: "; Object.getOwnPropertyDescriptor = function getOwnPropertyDescriptor(object, property) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT + object); if (!owns(object, property)) return; var descriptor, getter, setter; descriptor = { enumerable: true, configurable: true }; if (supportsAccessors) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; var getter = lookupGetter(object, property); var setter = lookupSetter(object, property); object.__proto__ = prototype; if (getter || setter) { if (getter) descriptor.get = getter; if (setter) descriptor.set = setter; return descriptor; } } descriptor.value = object[property]; return descriptor; }; } if (!Object.getOwnPropertyNames) { Object.getOwnPropertyNames = function getOwnPropertyNames(object) { return Object.keys(object); }; } if (!Object.create) { var createEmpty; if (Object.prototype.__proto__ === null) { createEmpty = function () { return { "__proto__": null }; }; } else { createEmpty = function () { var empty = {}; for (var i in empty) empty[i] = null; empty.constructor = empty.hasOwnProperty = empty.propertyIsEnumerable = empty.isPrototypeOf = empty.toLocaleString = empty.toString = empty.valueOf = empty.__proto__ = null; return empty; } } Object.create = function create(prototype, properties) { var object; if (prototype === null) { object = createEmpty(); } else { if (typeof prototype != "object") throw new TypeError("typeof prototype["+(typeof prototype)+"] != 'object'"); var Type = function () {}; Type.prototype = prototype; object = new Type(); object.__proto__ = prototype; } if (properties !== void 0) Object.defineProperties(object, properties); return object; }; } function doesDefinePropertyWork(object) { try { Object.defineProperty(object, "sentinel", {}); return "sentinel" in object; } catch (exception) { } } if (Object.defineProperty) { var definePropertyWorksOnObject = doesDefinePropertyWork({}); var definePropertyWorksOnDom = typeof document == "undefined" || doesDefinePropertyWork(document.createElement("div")); if (!definePropertyWorksOnObject || !definePropertyWorksOnDom) { var definePropertyFallback = Object.defineProperty; } } if (!Object.defineProperty || definePropertyFallback) { var ERR_NON_OBJECT_DESCRIPTOR = "Property description must be an object: "; var ERR_NON_OBJECT_TARGET = "Object.defineProperty called on non-object: " var ERR_ACCESSORS_NOT_SUPPORTED = "getters & setters can not be defined " + "on this javascript engine"; Object.defineProperty = function defineProperty(object, property, descriptor) { if ((typeof object != "object" && typeof object != "function") || object === null) throw new TypeError(ERR_NON_OBJECT_TARGET + object); if ((typeof descriptor != "object" && typeof descriptor != "function") || descriptor === null) throw new TypeError(ERR_NON_OBJECT_DESCRIPTOR + descriptor); if (definePropertyFallback) { try { return definePropertyFallback.call(Object, object, property, descriptor); } catch (exception) { } } if (owns(descriptor, "value")) { if (supportsAccessors && (lookupGetter(object, property) || lookupSetter(object, property))) { var prototype = object.__proto__; object.__proto__ = prototypeOfObject; delete object[property]; object[property] = descriptor.value; object.__proto__ = prototype; } else { object[property] = descriptor.value; } } else { if (!supportsAccessors) throw new TypeError(ERR_ACCESSORS_NOT_SUPPORTED); if (owns(descriptor, "get")) defineGetter(object, property, descriptor.get); if (owns(descriptor, "set")) defineSetter(object, property, descriptor.set); } return object; }; } if (!Object.defineProperties) { Object.defineProperties = function defineProperties(object, properties) { for (var property in properties) { if (owns(properties, property)) Object.defineProperty(object, property, properties[property]); } return object; }; } if (!Object.seal) { Object.seal = function seal(object) { return object; }; } if (!Object.freeze) { Object.freeze = function freeze(object) { return object; }; } try { Object.freeze(function () {}); } catch (exception) { Object.freeze = (function freeze(freezeObject) { return function freeze(object) { if (typeof object == "function") { return object; } else { return freezeObject(object); } }; })(Object.freeze); } if (!Object.preventExtensions) { Object.preventExtensions = function preventExtensions(object) { return object; }; } if (!Object.isSealed) { Object.isSealed = function isSealed(object) { return false; }; } if (!Object.isFrozen) { Object.isFrozen = function isFrozen(object) { return false; }; } if (!Object.isExtensible) { Object.isExtensible = function isExtensible(object) { if (Object(object) === object) { throw new TypeError(); // TODO message } var name = ''; while (owns(object, name)) { name += '?'; } object[name] = true; var returnValue = owns(object, name); delete object[name]; return returnValue; }; } if (!Object.keys) { var hasDontEnumBug = true, dontEnums = [ "toString", "toLocaleString", "valueOf", "hasOwnProperty", "isPrototypeOf", "propertyIsEnumerable", "constructor" ], dontEnumsLength = dontEnums.length; for (var key in {"toString": null}) { hasDontEnumBug = false; } Object.keys = function keys(object) { if ( (typeof object != "object" && typeof object != "function") || object === null ) { throw new TypeError("Object.keys called on a non-object"); } var keys = []; for (var name in object) { if (owns(object, name)) { keys.push(name); } } if (hasDontEnumBug) { for (var i = 0, ii = dontEnumsLength; i < ii; i++) { var dontEnum = dontEnums[i]; if (owns(object, dontEnum)) { keys.push(dontEnum); } } } return keys; }; } if (!Date.now) { Date.now = function now() { return new Date().getTime(); }; } var ws = "\x09\x0A\x0B\x0C\x0D\x20\xA0\u1680\u180E\u2000\u2001\u2002\u2003" + "\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u3000\u2028" + "\u2029\uFEFF"; if (!String.prototype.trim || ws.trim()) { ws = "[" + ws + "]"; var trimBeginRegexp = new RegExp("^" + ws + ws + "*"), trimEndRegexp = new RegExp(ws + ws + "*$"); String.prototype.trim = function trim() { return String(this).replace(trimBeginRegexp, "").replace(trimEndRegexp, ""); }; } function toInteger(n) { n = +n; if (n !== n) { // isNaN n = 0; } else if (n !== 0 && n !== (1/0) && n !== -(1/0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } return n; } function isPrimitive(input) { var type = typeof input; return ( input === null || type === "undefined" || type === "boolean" || type === "number" || type === "string" ); } function toPrimitive(input) { var val, valueOf, toString; if (isPrimitive(input)) { return input; } valueOf = input.valueOf; if (typeof valueOf === "function") { val = valueOf.call(input); if (isPrimitive(val)) { return val; } } toString = input.toString; if (typeof toString === "function") { val = toString.call(input); if (isPrimitive(val)) { return val; } } throw new TypeError(); } var toObject = function (o) { if (o == null) { // this matches both null and undefined throw new TypeError("can't convert "+o+" to object"); } return Object(o); }; });
overleaf_overleaf
2017-01-27
30618d33db61295a9c0c9f2467a80a25fe74abb7
todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksFragment.java
329
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.tasks; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.support.v4.content.ContextCompat; import android.support.v4.widget.SwipeRefreshLayout; import android.support.v7.widget.PopupMenu; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.BaseAdapter; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.TextView; import com.example.android.architecture.blueprints.todoapp.R; import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskActivity; import com.example.android.architecture.blueprints.todoapp.data.Task; import com.example.android.architecture.blueprints.todoapp.taskdetail.TaskDetailActivity; import java.util.ArrayList; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; /** * Display a grid of {@link Task}s. User can choose to view all, active or completed tasks. */ public class TasksFragment extends Fragment implements TasksContract.View { private TasksContract.Presenter mPresenter; private TasksAdapter mListAdapter; private View mNoTasksView; private ImageView mNoTaskIcon; private TextView mNoTaskMainView; private TextView mNoTaskAddView; private LinearLayout mTasksView; private TextView mFilteringLabelView; public TasksFragment() { // Requires empty public constructor } public static TasksFragment newInstance() { return new TasksFragment(); } @Override public void onCreate(@Nullable Bundle savedInstanceState) { super.onCreate(savedInstanceState); mListAdapter = new TasksAdapter(new ArrayList<Task>(0), mItemListener); } @Override public void onResume() { super.onResume(); mPresenter.start(); } @Override public void setPresenter(@NonNull TasksContract.Presenter presenter) { mPresenter = checkNotNull(presenter); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { mPresenter.result(requestCode, resultCode); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.tasks_frag, container, false); // Set up tasks view ListView listView = (ListView) root.findViewById(R.id.tasks_list); listView.setAdapter(mListAdapter); mFilteringLabelView = (TextView) root.findViewById(R.id.filteringLabel); mTasksView = (LinearLayout) root.findViewById(R.id.tasksLL); // Set up no tasks view mNoTasksView = root.findViewById(R.id.noTasks); mNoTaskIcon = (ImageView) root.findViewById(R.id.noTasksIcon); mNoTaskMainView = (TextView) root.findViewById(R.id.noTasksMain); mNoTaskAddView = (TextView) root.findViewById(R.id.noTasksAdd); mNoTaskAddView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { showAddTask(); } }); // Set up floating action button FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab_add_task); fab.setImageResource(R.drawable.ic_add); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.addNewTask(); } }); // Set up progress indicator final ScrollChildSwipeRefreshLayout swipeRefreshLayout = (ScrollChildSwipeRefreshLayout) root.findViewById(R.id.refresh_layout); swipeRefreshLayout.setColorSchemeColors( ContextCompat.getColor(getActivity(), R.color.colorPrimary), ContextCompat.getColor(getActivity(), R.color.colorAccent), ContextCompat.getColor(getActivity(), R.color.colorPrimaryDark) ); // Set the scrolling view in the custom SwipeRefreshLayout. swipeRefreshLayout.setScrollUpChild(listView); swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() { @Override public void onRefresh() { mPresenter.loadTasks(false); } }); setHasOptionsMenu(true); return root; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_clear: mPresenter.clearCompletedTasks(); break; case R.id.menu_filter: showFilteringPopUpMenu(); break; case R.id.menu_refresh: mPresenter.loadTasks(true); break; } return true; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.tasks_fragment_menu, menu); } @Override public void showFilteringPopUpMenu() { PopupMenu popup = new PopupMenu(getContext(), getActivity().findViewById(R.id.menu_filter)); popup.getMenuInflater().inflate(R.menu.filter_tasks, popup.getMenu()); popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() { public boolean onMenuItemClick(MenuItem item) { switch (item.getItemId()) { case R.id.active: mPresenter.setFiltering(TasksFilterType.ACTIVE_TASKS); break; case R.id.completed: mPresenter.setFiltering(TasksFilterType.COMPLETED_TASKS); break; default: mPresenter.setFiltering(TasksFilterType.ALL_TASKS); break; } mPresenter.loadTasks(false); return true; } }); popup.show(); } /** * Listener for clicks on tasks in the ListView. */ TaskItemListener mItemListener = new TaskItemListener() { @Override public void onTaskClick(Task clickedTask) { mPresenter.openTaskDetails(clickedTask); } @Override public void onCompleteTaskClick(Task completedTask) { mPresenter.completeTask(completedTask); } @Override public void onActivateTaskClick(Task activatedTask) { mPresenter.activateTask(activatedTask); } }; @Override public void setLoadingIndicator(final boolean active) { if (getView() == null) { return; } final SwipeRefreshLayout srl = (SwipeRefreshLayout) getView().findViewById(R.id.refresh_layout); // Make sure setRefreshing() is called after the layout is done with everything else. srl.post(new Runnable() { @Override public void run() { srl.setRefreshing(active); } }); } @Override public void showTasks(List<Task> tasks) { mListAdapter.replaceData(tasks); mTasksView.setVisibility(View.VISIBLE); mNoTasksView.setVisibility(View.GONE); } @Override public void showNoActiveTasks() { showNoTasksViews( getResources().getString(R.string.no_tasks_active), R.drawable.ic_check_circle_24dp, false ); } @Override public void showNoTasks() { showNoTasksViews( getResources().getString(R.string.no_tasks_all), R.drawable.ic_assignment_turned_in_24dp, false ); } @Override public void showNoCompletedTasks() { showNoTasksViews( getResources().getString(R.string.no_tasks_completed), R.drawable.ic_verified_user_24dp, false ); } @Override public void showSuccessfullySavedMessage() { showMessage(getString(R.string.successfully_saved_task_message)); } private void showNoTasksViews(String mainText, int iconRes, boolean showAddView) { mTasksView.setVisibility(View.GONE); mNoTasksView.setVisibility(View.VISIBLE); mNoTaskMainView.setText(mainText); mNoTaskIcon.setImageDrawable(getResources().getDrawable(iconRes)); mNoTaskAddView.setVisibility(showAddView ? View.VISIBLE : View.GONE); } @Override public void showActiveFilterLabel() { mFilteringLabelView.setText(getResources().getString(R.string.label_active)); } @Override public void showCompletedFilterLabel() { mFilteringLabelView.setText(getResources().getString(R.string.label_completed)); } @Override public void showAllFilterLabel() { mFilteringLabelView.setText(getResources().getString(R.string.label_all)); } @Override public void showAddTask() { Intent intent = new Intent(getContext(), AddEditTaskActivity.class); startActivityForResult(intent, AddEditTaskActivity.REQUEST_ADD_TASK); } @Override public void showTaskDetailsUi(String taskId) { // in it's own Activity, since it makes more sense that way and it gives us the flexibility // to show some Intent stubbing. Intent intent = new Intent(getContext(), TaskDetailActivity.class); intent.putExtra(TaskDetailActivity.EXTRA_TASK_ID, taskId); startActivity(intent); } @Override public void showTaskMarkedComplete() { showMessage(getString(R.string.task_marked_complete)); } @Override public void showTaskMarkedActive() { showMessage(getString(R.string.task_marked_active)); } @Override public void showCompletedTasksCleared() { showMessage(getString(R.string.completed_tasks_cleared)); } @Override public void showLoadingTasksError() { showMessage(getString(R.string.loading_tasks_error)); } private void showMessage(String message) { Snackbar.make(getView(), message, Snackbar.LENGTH_LONG).show(); } @Override public boolean isActive() { return isAdded(); } private static class TasksAdapter extends BaseAdapter { private List<Task> mTasks; private TaskItemListener mItemListener; public TasksAdapter(List<Task> tasks, TaskItemListener itemListener) { setList(tasks); mItemListener = itemListener; } public void replaceData(List<Task> tasks) { setList(tasks); notifyDataSetChanged(); } private void setList(List<Task> tasks) { mTasks = checkNotNull(tasks); } @Override public int getCount() { return mTasks.size(); } @Override public Task getItem(int i) { return mTasks.get(i); } @Override public long getItemId(int i) { return i; } @Override public View getView(int i, View view, ViewGroup viewGroup) { View rowView = view; if (rowView == null) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); rowView = inflater.inflate(R.layout.task_item, viewGroup, false); } final Task task = getItem(i); TextView titleTV = (TextView) rowView.findViewById(R.id.title); titleTV.setText(task.getTitleForList()); CheckBox completeCB = (CheckBox) rowView.findViewById(R.id.complete); // Active/completed task UI completeCB.setChecked(task.isCompleted()); if (task.isCompleted()) { rowView.setBackgroundDrawable(viewGroup.getContext() .getResources().getDrawable(R.drawable.list_completed_touch_feedback)); } else { rowView.setBackgroundDrawable(viewGroup.getContext() .getResources().getDrawable(R.drawable.touch_feedback)); } completeCB.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (!task.isCompleted()) { mItemListener.onCompleteTaskClick(task); } else { mItemListener.onActivateTaskClick(task); } } }); rowView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { mItemListener.onTaskClick(task); } }); return rowView; } } public interface TaskItemListener { void onTaskClick(Task clickedTask); void onCompleteTaskClick(Task completedTask); void onActivateTaskClick(Task activatedTask); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailPresenter.java
146
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.taskdetail; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.example.android.architecture.blueprints.todoapp.data.Task; import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource; import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository; import com.google.common.base.Strings; import static com.google.common.base.Preconditions.checkNotNull; /** * Listens to user actions from the UI ({@link TaskDetailFragment}), retrieves the data and updates * the UI as required. */ public class TaskDetailPresenter implements TaskDetailContract.Presenter { private final TasksRepository mTasksRepository; private final TaskDetailContract.View mTaskDetailView; @Nullable private String mTaskId; public TaskDetailPresenter(@Nullable String taskId, @NonNull TasksRepository tasksRepository, @NonNull TaskDetailContract.View taskDetailView) { mTaskId = taskId; mTasksRepository = checkNotNull(tasksRepository, "tasksRepository cannot be null!"); mTaskDetailView = checkNotNull(taskDetailView, "taskDetailView cannot be null!"); mTaskDetailView.setPresenter(this); } @Override public void start() { openTask(); } private void openTask() { if (Strings.isNullOrEmpty(mTaskId)) { mTaskDetailView.showMissingTask(); return; } mTaskDetailView.setLoadingIndicator(true); mTasksRepository.getTask(mTaskId, new TasksDataSource.GetTaskCallback() { @Override public void onTaskLoaded(Task task) { // The view may not be able to handle UI updates anymore if (!mTaskDetailView.isActive()) { return; } mTaskDetailView.setLoadingIndicator(false); if (null == task) { mTaskDetailView.showMissingTask(); } else { showTask(task); } } @Override public void onDataNotAvailable() { // The view may not be able to handle UI updates anymore if (!mTaskDetailView.isActive()) { return; } mTaskDetailView.showMissingTask(); } }); } @Override public void editTask() { if (Strings.isNullOrEmpty(mTaskId)) { mTaskDetailView.showMissingTask(); return; } mTaskDetailView.showEditTask(mTaskId); } @Override public void deleteTask() { if (Strings.isNullOrEmpty(mTaskId)) { mTaskDetailView.showMissingTask(); return; } mTasksRepository.deleteTask(mTaskId); mTaskDetailView.showTaskDeleted(); } @Override public void completeTask() { if (Strings.isNullOrEmpty(mTaskId)) { mTaskDetailView.showMissingTask(); return; } mTasksRepository.completeTask(mTaskId); mTaskDetailView.showTaskMarkedComplete(); } @Override public void activateTask() { if (Strings.isNullOrEmpty(mTaskId)) { mTaskDetailView.showMissingTask(); return; } mTasksRepository.activateTask(mTaskId); mTaskDetailView.showTaskMarkedActive(); } private void showTask(@NonNull Task task) { String title = task.getTitle(); String description = task.getDescription(); if (Strings.isNullOrEmpty(title)) { mTaskDetailView.hideTitle(); } else { mTaskDetailView.showTitle(title); } if (Strings.isNullOrEmpty(description)) { mTaskDetailView.hideDescription(); } else { mTaskDetailView.showDescription(description); } mTaskDetailView.showCompletionStatus(task.isCompleted()); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/test/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailPresenterTest.java
203
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.taskdetail; import com.example.android.architecture.blueprints.todoapp.data.Task; import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource; import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import static org.mockito.Matchers.eq; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Unit tests for the implementation of {@link TaskDetailPresenter} */ public class TaskDetailPresenterTest { public static final String TITLE_TEST = "title"; public static final String DESCRIPTION_TEST = "description"; public static final String INVALID_TASK_ID = ""; public static final Task ACTIVE_TASK = new Task(TITLE_TEST, DESCRIPTION_TEST); public static final Task COMPLETED_TASK = new Task(TITLE_TEST, DESCRIPTION_TEST, true); @Mock private TasksRepository mTasksRepository; @Mock private TaskDetailContract.View mTaskDetailView; /** * {@link ArgumentCaptor} is a powerful Mockito API to capture argument values and use them to * perform further actions or assertions on them. */ @Captor private ArgumentCaptor<TasksDataSource.GetTaskCallback> mGetTaskCallbackCaptor; private TaskDetailPresenter mTaskDetailPresenter; @Before public void setup() { // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To // inject the mocks in the test the initMocks method needs to be called. MockitoAnnotations.initMocks(this); // The presenter won't update the view unless it's active. when(mTaskDetailView.isActive()).thenReturn(true); } @Test public void getActiveTaskFromRepositoryAndLoadIntoView() { // When tasks presenter is asked to open a task mTaskDetailPresenter = new TaskDetailPresenter( ACTIVE_TASK.getId(), mTasksRepository, mTaskDetailView); mTaskDetailPresenter.start(); // Then task is loaded from model, callback is captured and progress indicator is shown verify(mTasksRepository).getTask(eq(ACTIVE_TASK.getId()), mGetTaskCallbackCaptor.capture()); InOrder inOrder = inOrder(mTaskDetailView); inOrder.verify(mTaskDetailView).setLoadingIndicator(true); // When task is finally loaded mGetTaskCallbackCaptor.getValue().onTaskLoaded(ACTIVE_TASK); // Trigger callback // Then progress indicator is hidden and title, description and completion status are shown // in UI inOrder.verify(mTaskDetailView).setLoadingIndicator(false); verify(mTaskDetailView).showTitle(TITLE_TEST); verify(mTaskDetailView).showDescription(DESCRIPTION_TEST); verify(mTaskDetailView).showCompletionStatus(false); } @Test public void getCompletedTaskFromRepositoryAndLoadIntoView() { mTaskDetailPresenter = new TaskDetailPresenter( COMPLETED_TASK.getId(), mTasksRepository, mTaskDetailView); mTaskDetailPresenter.start(); // Then task is loaded from model, callback is captured and progress indicator is shown verify(mTasksRepository).getTask( eq(COMPLETED_TASK.getId()), mGetTaskCallbackCaptor.capture()); InOrder inOrder = inOrder(mTaskDetailView); inOrder.verify(mTaskDetailView).setLoadingIndicator(true); // When task is finally loaded mGetTaskCallbackCaptor.getValue().onTaskLoaded(COMPLETED_TASK); // Trigger callback // Then progress indicator is hidden and title, description and completion status are shown // in UI inOrder.verify(mTaskDetailView).setLoadingIndicator(false); verify(mTaskDetailView).showTitle(TITLE_TEST); verify(mTaskDetailView).showDescription(DESCRIPTION_TEST); verify(mTaskDetailView).showCompletionStatus(true); } @Test public void getUnknownTaskFromRepositoryAndLoadIntoView() { // When loading of a task is requested with an invalid task ID. mTaskDetailPresenter = new TaskDetailPresenter( INVALID_TASK_ID, mTasksRepository, mTaskDetailView); mTaskDetailPresenter.start(); verify(mTaskDetailView).showMissingTask(); } @Test public void deleteTask() { // Given an initialized TaskDetailPresenter with stubbed task Task task = new Task(TITLE_TEST, DESCRIPTION_TEST); // When the deletion of a task is requested mTaskDetailPresenter = new TaskDetailPresenter( task.getId(), mTasksRepository, mTaskDetailView); mTaskDetailPresenter.deleteTask(); // Then the repository and the view are notified verify(mTasksRepository).deleteTask(task.getId()); verify(mTaskDetailView).showTaskDeleted(); } @Test public void completeTask() { // Given an initialized presenter with an active task Task task = new Task(TITLE_TEST, DESCRIPTION_TEST); mTaskDetailPresenter = new TaskDetailPresenter( task.getId(), mTasksRepository, mTaskDetailView); mTaskDetailPresenter.start(); // When the presenter is asked to complete the task mTaskDetailPresenter.completeTask(); // Then a request is sent to the task repository and the UI is updated verify(mTasksRepository).completeTask(task.getId()); verify(mTaskDetailView).showTaskMarkedComplete(); } @Test public void activateTask() { // Given an initialized presenter with a completed task Task task = new Task(TITLE_TEST, DESCRIPTION_TEST, true); mTaskDetailPresenter = new TaskDetailPresenter( task.getId(), mTasksRepository, mTaskDetailView); mTaskDetailPresenter.start(); // When the presenter is asked to activate the task mTaskDetailPresenter.activateTask(); // Then a request is sent to the task repository and the UI is updated verify(mTasksRepository).activateTask(task.getId()); verify(mTaskDetailView).showTaskMarkedActive(); } @Test public void activeTaskIsShownWhenEditing() { // When the edit of an ACTIVE_TASK is requested mTaskDetailPresenter = new TaskDetailPresenter( ACTIVE_TASK.getId(), mTasksRepository, mTaskDetailView); mTaskDetailPresenter.editTask(); // Then the view is notified verify(mTaskDetailView).showEditTask(ACTIVE_TASK.getId()); } @Test public void invalidTaskIsNotShownWhenEditing() { // When the edit of an invalid task id is requested mTaskDetailPresenter = new TaskDetailPresenter( INVALID_TASK_ID, mTasksRepository, mTaskDetailView); mTaskDetailPresenter.editTask(); // Then the edit mode is never started verify(mTaskDetailView, never()).showEditTask(INVALID_TASK_ID); // instead, the error is shown. verify(mTaskDetailView).showMissingTask(); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/test/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksPresenterTest.java
197
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.tasks; import com.example.android.architecture.blueprints.todoapp.data.Task; import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource.LoadTasksCallback; import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository; import com.google.common.collect.Lists; import org.junit.Before; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Captor; import org.mockito.InOrder; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.List; import static org.junit.Assert.assertTrue; import static org.mockito.Matchers.any; import static org.mockito.Mockito.inOrder; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Unit tests for the implementation of {@link TasksPresenter} */ public class TasksPresenterTest { private static List<Task> TASKS; @Mock private TasksRepository mTasksRepository; @Mock private TasksContract.View mTasksView; /** * {@link ArgumentCaptor} is a powerful Mockito API to capture argument values and use them to * perform further actions or assertions on them. */ @Captor private ArgumentCaptor<LoadTasksCallback> mLoadTasksCallbackCaptor; private TasksPresenter mTasksPresenter; @Before public void setupTasksPresenter() { // Mockito has a very convenient way to inject mocks by using the @Mock annotation. To // inject the mocks in the test the initMocks method needs to be called. MockitoAnnotations.initMocks(this); // Get a reference to the class under test mTasksPresenter = new TasksPresenter(mTasksRepository, mTasksView); // The presenter won't update the view unless it's active. when(mTasksView.isActive()).thenReturn(true); // We start the tasks to 3, with one active and two completed TASKS = Lists.newArrayList(new Task("Title1", "Description1"), new Task("Title2", "Description2", true), new Task("Title3", "Description3", true)); } @Test public void loadAllTasksFromRepositoryAndLoadIntoView() { // Given an initialized TasksPresenter with initialized tasks // When loading of Tasks is requested mTasksPresenter.setFiltering(TasksFilterType.ALL_TASKS); mTasksPresenter.loadTasks(true); // Callback is captured and invoked with stubbed tasks verify(mTasksRepository).getTasks(mLoadTasksCallbackCaptor.capture()); mLoadTasksCallbackCaptor.getValue().onTasksLoaded(TASKS); // Then progress indicator is shown InOrder inOrder = inOrder(mTasksView); inOrder.verify(mTasksView).setLoadingIndicator(true); // Then progress indicator is hidden and all tasks are shown in UI inOrder.verify(mTasksView).setLoadingIndicator(false); ArgumentCaptor<List> showTasksArgumentCaptor = ArgumentCaptor.forClass(List.class); verify(mTasksView).showTasks(showTasksArgumentCaptor.capture()); assertTrue(showTasksArgumentCaptor.getValue().size() == 3); } @Test public void loadActiveTasksFromRepositoryAndLoadIntoView() { // Given an initialized TasksPresenter with initialized tasks // When loading of Tasks is requested mTasksPresenter.setFiltering(TasksFilterType.ACTIVE_TASKS); mTasksPresenter.loadTasks(true); // Callback is captured and invoked with stubbed tasks verify(mTasksRepository).getTasks(mLoadTasksCallbackCaptor.capture()); mLoadTasksCallbackCaptor.getValue().onTasksLoaded(TASKS); // Then progress indicator is hidden and active tasks are shown in UI verify(mTasksView).setLoadingIndicator(false); ArgumentCaptor<List> showTasksArgumentCaptor = ArgumentCaptor.forClass(List.class); verify(mTasksView).showTasks(showTasksArgumentCaptor.capture()); assertTrue(showTasksArgumentCaptor.getValue().size() == 1); } @Test public void loadCompletedTasksFromRepositoryAndLoadIntoView() { // Given an initialized TasksPresenter with initialized tasks // When loading of Tasks is requested mTasksPresenter.setFiltering(TasksFilterType.COMPLETED_TASKS); mTasksPresenter.loadTasks(true); // Callback is captured and invoked with stubbed tasks verify(mTasksRepository).getTasks(mLoadTasksCallbackCaptor.capture()); mLoadTasksCallbackCaptor.getValue().onTasksLoaded(TASKS); // Then progress indicator is hidden and completed tasks are shown in UI verify(mTasksView).setLoadingIndicator(false); ArgumentCaptor<List> showTasksArgumentCaptor = ArgumentCaptor.forClass(List.class); verify(mTasksView).showTasks(showTasksArgumentCaptor.capture()); assertTrue(showTasksArgumentCaptor.getValue().size() == 2); } @Test public void clickOnFab_ShowsAddTaskUi() { // When adding a new task mTasksPresenter.addNewTask(); // Then add task UI is shown verify(mTasksView).showAddTask(); } @Test public void clickOnTask_ShowsDetailUi() { // Given a stubbed active task Task requestedTask = new Task("Details Requested", "For this task"); // When open task details is requested mTasksPresenter.openTaskDetails(requestedTask); // Then task detail UI is shown verify(mTasksView).showTaskDetailsUi(any(String.class)); } @Test public void completeTask_ShowsTaskMarkedComplete() { // Given a stubbed task Task task = new Task("Details Requested", "For this task"); // When task is marked as complete mTasksPresenter.completeTask(task); // Then repository is called and task marked complete UI is shown verify(mTasksRepository).completeTask(task); verify(mTasksView).showTaskMarkedComplete(); } @Test public void activateTask_ShowsTaskMarkedActive() { // Given a stubbed completed task Task task = new Task("Details Requested", "For this task", true); mTasksPresenter.loadTasks(true); // When task is marked as activated mTasksPresenter.activateTask(task); // Then repository is called and task marked active UI is shown verify(mTasksRepository).activateTask(task); verify(mTasksView).showTaskMarkedActive(); } @Test public void unavailableTasks_ShowsError() { // When tasks are loaded mTasksPresenter.setFiltering(TasksFilterType.ALL_TASKS); mTasksPresenter.loadTasks(true); // And the tasks aren't available in the repository verify(mTasksRepository).getTasks(mLoadTasksCallbackCaptor.capture()); mLoadTasksCallbackCaptor.getValue().onDataNotAvailable(); // Then an error message is shown verify(mTasksView).showLoadingTasksError(); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/addedittask/AddEditTaskPresenter.java
129
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.addedittask; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import com.example.android.architecture.blueprints.todoapp.data.Task; import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource; import static com.google.common.base.Preconditions.checkNotNull; /** * Listens to user actions from the UI ({@link AddEditTaskFragment}), retrieves the data and updates * the UI as required. */ public class AddEditTaskPresenter implements AddEditTaskContract.Presenter, TasksDataSource.GetTaskCallback { @NonNull private final TasksDataSource mTasksRepository; @NonNull private final AddEditTaskContract.View mAddTaskView; @Nullable private String mTaskId; private boolean mIsDataMissing; /** * Creates a presenter for the add/edit view. * * @param taskId ID of the task to edit or null for a new task * @param tasksRepository a repository of data for tasks * @param addTaskView the add/edit view * @param shouldLoadDataFromRepo whether data needs to be loaded or not (for config changes) */ public AddEditTaskPresenter(@Nullable String taskId, @NonNull TasksDataSource tasksRepository, @NonNull AddEditTaskContract.View addTaskView, boolean shouldLoadDataFromRepo) { mTaskId = taskId; mTasksRepository = checkNotNull(tasksRepository); mAddTaskView = checkNotNull(addTaskView); mIsDataMissing = shouldLoadDataFromRepo; } @Override public void start() { if (!isNewTask() && mIsDataMissing) { populateTask(); } } @Override public void saveTask(String title, String description) { if (isNewTask()) { createTask(title, description); } else { updateTask(title, description); } } @Override public void populateTask() { if (isNewTask()) { throw new RuntimeException("populateTask() was called but task is new."); } mTasksRepository.getTask(mTaskId, this); } @Override public void onTaskLoaded(Task task) { // The view may not be able to handle UI updates anymore if (mAddTaskView.isActive()) { mAddTaskView.setTitle(task.getTitle()); mAddTaskView.setDescription(task.getDescription()); } mIsDataMissing = false; } @Override public void onDataNotAvailable() { // The view may not be able to handle UI updates anymore if (mAddTaskView.isActive()) { mAddTaskView.showEmptyTaskError(); } } @Override public boolean isDataMissing() { return mIsDataMissing; } private boolean isNewTask() { return mTaskId == null; } private void createTask(String title, String description) { Task newTask = new Task(title, description); if (newTask.isEmpty()) { mAddTaskView.showEmptyTaskError(); } else { mTasksRepository.saveTask(newTask); mAddTaskView.showTasksList(); } } private void updateTask(String title, String description) { if (isNewTask()) { throw new RuntimeException("updateTask() was called but task is new."); } mTasksRepository.saveTask(new Task(title, description, mTaskId)); mAddTaskView.showTasksList(); // After an edit, go back to the list. } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsPresenter.java
100
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.statistics; import android.support.annotation.NonNull; import com.example.android.architecture.blueprints.todoapp.data.Task; import com.example.android.architecture.blueprints.todoapp.data.source.TasksDataSource; import com.example.android.architecture.blueprints.todoapp.data.source.TasksRepository; import com.example.android.architecture.blueprints.todoapp.util.EspressoIdlingResource; import java.util.List; import static com.google.common.base.Preconditions.checkNotNull; /** * Listens to user actions from the UI ({@link StatisticsFragment}), retrieves the data and updates * the UI as required. */ public class StatisticsPresenter implements StatisticsContract.Presenter { private final TasksRepository mTasksRepository; private final StatisticsContract.View mStatisticsView; public StatisticsPresenter(@NonNull TasksRepository tasksRepository, @NonNull StatisticsContract.View statisticsView) { mTasksRepository = checkNotNull(tasksRepository, "tasksRepository cannot be null"); mStatisticsView = checkNotNull(statisticsView, "StatisticsView cannot be null!"); mStatisticsView.setPresenter(this); } @Override public void start() { loadStatistics(); } private void loadStatistics() { mStatisticsView.setProgressIndicator(true); // The network request might be handled in a different thread so make sure Espresso knows // that the app is busy until the response is handled. EspressoIdlingResource.increment(); // App is busy until further notice mTasksRepository.getTasks(new TasksDataSource.LoadTasksCallback() { @Override public void onTasksLoaded(List<Task> tasks) { int activeTasks = 0; int completedTasks = 0; // This callback may be called twice, once for the cache and once for loading // the data from the server API, so we check before decrementing, otherwise // it throws "Counter has been corrupted!" exception. if (!EspressoIdlingResource.getIdlingResource().isIdleNow()) { EspressoIdlingResource.decrement(); // Set app as idle. } // We calculate number of active and completed tasks for (Task task : tasks) { if (task.isCompleted()) { completedTasks += 1; } else { activeTasks += 1; } } // The view may not be able to handle UI updates anymore if (!mStatisticsView.isActive()) { return; } mStatisticsView.setProgressIndicator(false); mStatisticsView.showStatistics(activeTasks, completedTasks); } @Override public void onDataNotAvailable() { // The view may not be able to handle UI updates anymore if (!mStatisticsView.isActive()) { return; } mStatisticsView.showLoadingStatisticsError(); } }); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailFragment.java
143
/* * Copyright (C) 2015 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.taskdetail; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.CompoundButton; import android.widget.TextView; import com.example.android.architecture.blueprints.todoapp.R; import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskActivity; import com.example.android.architecture.blueprints.todoapp.addedittask.AddEditTaskFragment; import com.google.common.base.Preconditions; import static com.google.common.base.Preconditions.checkNotNull; /** * Main UI for the task detail screen. */ public class TaskDetailFragment extends Fragment implements TaskDetailContract.View { @NonNull private static final String ARGUMENT_TASK_ID = "TASK_ID"; @NonNull private static final int REQUEST_EDIT_TASK = 1; private TaskDetailContract.Presenter mPresenter; private TextView mDetailTitle; private TextView mDetailDescription; private CheckBox mDetailCompleteStatus; public static TaskDetailFragment newInstance(@Nullable String taskId) { Bundle arguments = new Bundle(); arguments.putString(ARGUMENT_TASK_ID, taskId); TaskDetailFragment fragment = new TaskDetailFragment(); fragment.setArguments(arguments); return fragment; } @Override public void onResume() { super.onResume(); mPresenter.start(); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.taskdetail_frag, container, false); setHasOptionsMenu(true); mDetailTitle = (TextView) root.findViewById(R.id.task_detail_title); mDetailDescription = (TextView) root.findViewById(R.id.task_detail_description); mDetailCompleteStatus = (CheckBox) root.findViewById(R.id.task_detail_complete); // Set up floating action button FloatingActionButton fab = (FloatingActionButton) getActivity().findViewById(R.id.fab_edit_task); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { mPresenter.editTask(); } }); return root; } @Override public void setPresenter(@NonNull TaskDetailContract.Presenter presenter) { mPresenter = checkNotNull(presenter); } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.menu_delete: mPresenter.deleteTask(); return true; } return false; } @Override public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) { inflater.inflate(R.menu.taskdetail_fragment_menu, menu); } @Override public void setLoadingIndicator(boolean active) { if (active) { mDetailTitle.setText(""); mDetailDescription.setText(getString(R.string.loading)); } } @Override public void hideDescription() { mDetailDescription.setVisibility(View.GONE); } @Override public void hideTitle() { mDetailTitle.setVisibility(View.GONE); } @Override public void showDescription(@NonNull String description) { mDetailDescription.setVisibility(View.VISIBLE); mDetailDescription.setText(description); } @Override public void showCompletionStatus(final boolean complete) { Preconditions.checkNotNull(mDetailCompleteStatus); mDetailCompleteStatus.setChecked(complete); mDetailCompleteStatus.setOnCheckedChangeListener( new CompoundButton.OnCheckedChangeListener() { @Override public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { if (isChecked) { mPresenter.completeTask(); } else { mPresenter.activateTask(); } } }); } @Override public void showEditTask(@NonNull String taskId) { Intent intent = new Intent(getContext(), AddEditTaskActivity.class); intent.putExtra(AddEditTaskFragment.ARGUMENT_EDIT_TASK_ID, taskId); startActivityForResult(intent, REQUEST_EDIT_TASK); } @Override public void showTaskDeleted() { getActivity().finish(); } public void showTaskMarkedComplete() { Snackbar.make(getView(), getString(R.string.task_marked_complete), Snackbar.LENGTH_LONG) .show(); } @Override public void showTaskMarkedActive() { Snackbar.make(getView(), getString(R.string.task_marked_active), Snackbar.LENGTH_LONG) .show(); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == REQUEST_EDIT_TASK) { // If the task was edited successfully, go back to the list. if (resultCode == Activity.RESULT_OK) { getActivity().finish(); } } } @Override public void showTitle(@NonNull String title) { mDetailTitle.setVisibility(View.VISIBLE); mDetailTitle.setText(title); } @Override public void showMissingTask() { mDetailTitle.setText(""); mDetailDescription.setText(getString(R.string.no_data)); } @Override public boolean isActive() { return isAdded(); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/tasks/TasksContract.java
89
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.tasks; import android.support.annotation.NonNull; import com.example.android.architecture.blueprints.todoapp.BaseView; import com.example.android.architecture.blueprints.todoapp.data.Task; import com.example.android.architecture.blueprints.todoapp.BasePresenter; import java.util.List; /** * This specifies the contract between the view and the presenter. */ public interface TasksContract { interface View extends BaseView<Presenter> { void setLoadingIndicator(boolean active); void showTasks(List<Task> tasks); void showAddTask(); void showTaskDetailsUi(String taskId); void showTaskMarkedComplete(); void showTaskMarkedActive(); void showCompletedTasksCleared(); void showLoadingTasksError(); void showNoTasks(); void showActiveFilterLabel(); void showCompletedFilterLabel(); void showAllFilterLabel(); void showNoActiveTasks(); void showNoCompletedTasks(); void showSuccessfullySavedMessage(); boolean isActive(); void showFilteringPopUpMenu(); } interface Presenter extends BasePresenter { void result(int requestCode, int resultCode); void loadTasks(boolean forceUpdate); void addNewTask(); void openTaskDetails(@NonNull Task requestedTask); void completeTask(@NonNull Task completedTask); void activateTask(@NonNull Task activeTask); void clearCompletedTasks(); void setFiltering(TasksFilterType requestType); TasksFilterType getFiltering(); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/statistics/StatisticsFragment.java
41
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.statistics; import android.os.Bundle; import android.support.annotation.NonNull; import android.support.annotation.Nullable; import android.support.v4.app.Fragment; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.TextView; import com.example.android.architecture.blueprints.todoapp.R; import static com.google.common.base.Preconditions.checkNotNull; /** * Main UI for the statistics screen. */ public class StatisticsFragment extends Fragment implements StatisticsContract.View { private TextView mStatisticsTV; private StatisticsContract.Presenter mPresenter; public static StatisticsFragment newInstance() { return new StatisticsFragment(); } @Override public void setPresenter(@NonNull StatisticsContract.Presenter presenter) { mPresenter = checkNotNull(presenter); } @Nullable @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View root = inflater.inflate(R.layout.statistics_frag, container, false); mStatisticsTV = (TextView) root.findViewById(R.id.statistics); return root; } @Override public void onResume() { super.onResume(); mPresenter.start(); } @Override public void setProgressIndicator(boolean active) { if (active) { mStatisticsTV.setText(getString(R.string.loading)); } else { mStatisticsTV.setText(""); } } @Override public void showStatistics(int numberOfIncompleteTasks, int numberOfCompletedTasks) { if (numberOfCompletedTasks == 0 && numberOfIncompleteTasks == 0) { mStatisticsTV.setText(getResources().getString(R.string.statistics_no_tasks)); } else { String displayString = getResources().getString(R.string.statistics_active_tasks) + " " + numberOfIncompleteTasks + "\n" + getResources().getString( R.string.statistics_completed_tasks) + " " + numberOfCompletedTasks; mStatisticsTV.setText(displayString); } } @Override public void showLoadingStatisticsError() { mStatisticsTV.setText(getResources().getString(R.string.statistics_error)); } @Override public boolean isActive() { return isAdded(); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
todoapp/app/src/main/java/com/example/android/architecture/blueprints/todoapp/taskdetail/TaskDetailContract.java
64
/* * Copyright 2016, The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.android.architecture.blueprints.todoapp.taskdetail; import com.example.android.architecture.blueprints.todoapp.BasePresenter; import com.example.android.architecture.blueprints.todoapp.BaseView; /** * This specifies the contract between the view and the presenter. */ public interface TaskDetailContract { interface View extends BaseView<Presenter> { void setLoadingIndicator(boolean active); void showMissingTask(); void hideTitle(); void showTitle(String title); void hideDescription(); void showDescription(String description); void showCompletionStatus(boolean complete); void showEditTask(String taskId); void showTaskDeleted(); void showTaskMarkedComplete(); void showTaskMarkedActive(); boolean isActive(); } interface Presenter extends BasePresenter { void editTask(); void deleteTask(); void completeTask(); void activateTask(); } }
android_architecture-samples
2017-01-27
06a71078fafeb6cf8bf43b5cd166295be4405407
caffe2/python/hypothesis_test.py
2,093
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import copy from functools import reduce from hypothesis import assume, given, settings import hypothesis.strategies as st from functools import partial import unittest from caffe2.python import core, workspace, tt_core, dyndep import caffe2.python.hypothesis_test_util as hu from caffe2.proto.caffe2_pb2 import TensorProto dyndep.InitOpsLibrary('@/caffe2/caffe2/fb/optimizers:sgd_simd_ops') def sigmoid(x): return 1.0 / (1.0 + np.exp(-x)) @st.composite def _tensor_and_prefix(draw, dtype, elements, min_dim=1, max_dim=4, **kwargs): dims_ = draw( st.lists(hu.dims(**kwargs), min_size=min_dim, max_size=max_dim)) extra_ = draw( st.lists(hu.dims(**kwargs), min_size=min_dim, max_size=max_dim)) return (draw(hu.arrays(dims_ + extra_, dtype, elements)), draw(hu.arrays(extra_, dtype, elements))) _NUMPY_TYPE_TO_ENUM = { np.float32: core.DataType.FLOAT, np.int32: core.DataType.INT32, np.bool: core.DataType.BOOL, np.uint8: core.DataType.UINT8, np.int8: core.DataType.INT8, np.uint16: core.DataType.UINT16, np.int16: core.DataType.INT16, np.int64: core.DataType.INT64, np.float64: core.DataType.DOUBLE, } def _dtypes(dtypes=None): dtypes = dtypes if dtypes else [np.int32, np.int64, np.float32] return st.sampled_from(dtypes) def _test_binary(name, ref, filter_=None, gcs=hu.gcs, test_gradient=False, allow_inplace=False, dtypes=_dtypes): @given( inputs=dtypes().flatmap( lambda dtype: hu.tensors( n=2, dtype=dtype, elements=hu.elements_of_type(dtype, filter_=filter_))), out=st.sampled_from(('Y', 'X1', 'X2') if allow_inplace else ('Y',)), **gcs) @settings(max_examples=3, timeout=100) def test_binary(self, inputs, out, gc, dc): op = core.CreateOperator(name, ["X1", "X2"], [out]) X1, X2 = inputs self.assertDeviceChecks(dc, op, [X1, X2], [0]) # We only do gradient check with float32 types. if test_gradient and X1.dtype == np.float32: self.assertGradientChecks(gc, op, [X1, X2], 0, [0]) self.assertReferenceChecks(gc, op, [X1, X2], ref) return test_binary def _test_binary_broadcast(name, ref, filter_=None, gcs=hu.gcs, allow_inplace=False, dtypes=_dtypes): @given( inputs=dtypes().flatmap(lambda dtype: _tensor_and_prefix( dtype=dtype, elements=hu.elements_of_type(dtype, filter_=filter_))), in_place=(st.booleans() if allow_inplace else st.just(False)), **gcs) @settings(max_examples=3, timeout=100) def test_binary_broadcast(self, inputs, in_place, gc, dc): op = core.CreateOperator( name, ["X1", "X2"], ["X1" if in_place else "Y"], broadcast=1) X1, X2 = inputs self.assertDeviceChecks(dc, op, [X1, X2], [0]) def cast_ref(x, y): return (np.array(ref(x, y)[0], dtype=x.dtype), ) # gradient not implemented yet # self.assertGradientChecks(gc, op, [X1, X2], 0, [0]) self.assertReferenceChecks(gc, op, [X1, X2], cast_ref) return test_binary_broadcast class TestOperators(hu.HypothesisTestCase): def test_comparison_ops(self): ops = {"LT": lambda x1, x2: [x1 < x2], "LE": lambda x1, x2: [x1 <= x2], "GT": lambda x1, x2: [x1 > x2], "GE": lambda x1, x2: [x1 >= x2]} for name, ref in ops.items(): _test_binary(name, ref, gcs=hu.gcs_cpu_only)(self) _test_binary_broadcast(name, ref, gcs=hu.gcs_cpu_only)(self) @given(inputs=hu.tensors(n=2), in_place=st.booleans(), **hu.gcs) def test_sum(self, inputs, in_place, gc, dc): op = core.CreateOperator("Sum", ["X1", "X2"], ["Y" if not in_place else "X1"]) X1, X2 = inputs self.assertDeviceChecks(dc, op, [X1, X2], [0]) self.assertGradientChecks(gc, op, [X1, X2], 0, [0]) @given(inputs=hu.tensors(n=2, min_dim=2, max_dim=2), **hu.gcs_cpu_only) def test_row_mul(self, inputs, gc, dc): op = core.CreateOperator("RowMul", ["X1", "X2"], ["Y"]) X1, Xtmp = inputs X2 = Xtmp[:, 0] def ref(x, y): ret = np.zeros(shape=x.shape, dtype=x.dtype) for i in range(y.size): ret[i, ] = x[i, ] * y[i] return [ret] self.assertDeviceChecks(dc, op, [X1, X2], [0]) for i in range(2): self.assertGradientChecks(gc, op, [X1, X2], i, [0]) self.assertReferenceChecks(gc, op, [X1, X2], ref) @given(inputs=hu.tensors(n=2), **hu.gcs_cpu_only) def test_max(self, inputs, gc, dc): op = core.CreateOperator("Max", ["X1", "X2"], ["Y"]) X1, X2 = inputs # Make X1 and X2 far from each other, since X1=X2 is not differentiable # and the step size of gradient checker is 0.05 X1[np.logical_and(X1 >= X2 - 0.05, X1 <= X2)] -= 0.05 X1[np.logical_and(X1 <= X2 + 0.05, X1 >= X2)] += 0.05 self.assertDeviceChecks(dc, op, [X1, X2], [0]) for i in range(2): self.assertGradientChecks(gc, op, [X1, X2], i, [0]) def elementwise_max(X, Y): return [np.maximum(X, Y)] self.assertReferenceChecks(gc, op, [X1, X2], elementwise_max) def test_add(self): def ref(x, y): return (x + y, ) _test_binary("Add", ref, test_gradient=True)(self) _test_binary_broadcast("Add", ref)(self) def test_sub(self): def ref(x, y): return (x - y, ) # TODO(jiayq): enable gradient test when implemented. _test_binary("Sub", ref, test_gradient=True)(self) _test_binary_broadcast("Sub", ref)(self) def test_mul(self): def ref(x, y): return (x * y, ) _test_binary("Mul", ref, test_gradient=True)(self) _test_binary_broadcast("Mul", ref)(self) def test_div(self): def ref(x, y): return (x / y, ) def non_zero(x): return abs(x) > 10e-5 def div_dtypes(): return st.sampled_from([np.float32, np.float64]) _test_binary( "Div", ref, filter_=non_zero, test_gradient=True, dtypes=div_dtypes, gcs=hu.gcs_cpu_only )(self) _test_binary( "Div", ref, filter_=non_zero, test_gradient=False, dtypes=div_dtypes )(self) _test_binary_broadcast( "Div", ref, filter_=non_zero, dtypes=div_dtypes)(self) @given(X=hu.tensor(), in_place=st.booleans(), **hu.gcs) def test_negative(self, X, in_place, gc, dc): op = core.CreateOperator("Negative", ["X"], ["Y" if not in_place else "X"]) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(X=hu.tensor(), **hu.gcs) def test_tanh(self, X, gc, dc): op = core.CreateOperator("Tanh", "X", "Y") self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(X=hu.tensor(), **hu.gcs) def test_averaged_loss(self, X, gc, dc): op = core.CreateOperator("AveragedLoss", ["X"], ["loss"]) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(X=hu.tensor(), inplace=st.booleans(), **hu.gcs) def test_softsign(self, X, inplace, gc, dc): op = core.CreateOperator("Softsign", ["X"], ["X" if inplace else "Y"]) def softsign(X): return (X / (1 + np.abs(X)),) self.assertDeviceChecks(dc, op, [X], [0]) self.assertReferenceChecks(gc, op, [X], softsign) if inplace: with self.assertRaises(Exception): self.assertGradientChecks(gc, op, [X], 0, [0]) else: self.assertGradientChecks(gc, op, [X], 0, [0]) @given( device_options=st.lists( min_size=2, max_size=4, elements=st.sampled_from(hu.expanded_device_options)), set_seed=st.booleans()) def test_random_seed_behaviour(self, device_options, set_seed): # Assume we are always operating on CUDA or CPU, since RNG is # inconsistent between CPU and GPU. device_options = copy.deepcopy(device_options) assume(len({do.device_type for do in device_options}) == 1) if set_seed: for do in device_options: do.random_seed = 1000 def run(do): op = core.CreateOperator( "XavierFill", [], ["Y"], device_option=do, shape=[2]) self.ws.run(op) return self.ws.blobs["Y"].fetch() ys = [run(do) for do in device_options] for y in ys[1:]: if set_seed: np.testing.assert_array_equal(ys[0], y) else: with self.assertRaises(AssertionError): np.testing.assert_array_equal(ys[0], y) @given(axis=st.integers(min_value=1, max_value=4), num_output=st.integers(min_value=4, max_value=8), engine=st.sampled_from(["", "PACKED"]), **hu.gcs) def test_fully_connected_axis(self, axis, num_output, engine, gc, dc): np.random.seed(1) X = np.random.randn(1, 2, 3, 2, 1).astype(np.float32) def prod(xs): p = 1 for x in xs: p *= x return p K = prod(list(X.shape)[axis:]) N = num_output W = np.random.randn(N, K).astype(np.float32) b = np.random.randn(N).astype(np.float32) op = core.CreateOperator( "FC", ["X", "W", "b"], ["Y"], engine=engine, axis=axis) for name, param in [("X", X), ("W", W), ("b", b)]: self.ws.create_blob(name).feed(param) self.ws.run(op) Y = self.ws.blobs["Y"].fetch() self.assertEqual(list(Y.shape), list(X.shape)[:axis] + [N]) inputs = [X, W, b] self.assertDeviceChecks(dc, op, inputs, [0]) for param, _ in enumerate(inputs): self.assertGradientChecks(gc, op, inputs, param, [0]) @unittest.skipIf(not workspace.has_gpu_support, "Skipping test due to no gpu present.") @given(hidden_size=st.integers(min_value=1, max_value=3), num_layers=st.integers(min_value=1, max_value=3), bidirectional=st.booleans(), rnn_mode=st.sampled_from(["gru", "lstm"]), input_mode=st.sampled_from(["linear"]), dropout=st.floats(min_value=0.0, max_value=0.0), T=st.integers(min_value=1, max_value=4), N=st.integers(min_value=1, max_value=4), D=st.integers(min_value=1, max_value=4)) def test_recurrent(self, hidden_size, num_layers, bidirectional, rnn_mode, input_mode, dropout, T, N, D): init_op = core.CreateOperator( "RecurrentInit", ["INPUT"], ["WEIGHT", "DROPOUT_STATES"], hidden_size=hidden_size, bidirectional=bidirectional, rnn_mode=rnn_mode, dropout=dropout, input_mode=input_mode, num_layers=num_layers, device_option=hu.gpu_do, engine="CUDNN") op = core.CreateOperator( "Recurrent", ["INPUT", "HIDDEN_INPUT", "CELL_INPUT", "WEIGHT"], ["OUTPUT", "HIDDEN_OUTPUT", "CELL_OUTPUT", "RNN_SCRATCH", "DROPOUT_STATES"], hidden_size=hidden_size, bidirectional=bidirectional, rnn_mode=rnn_mode, dropout=dropout, input_mode=input_mode, num_layers=num_layers, engine="CUDNN") num_directions = 2 if bidirectional else 1 X = np.random.randn(T, N, D).astype(np.float32) self.ws.create_blob("INPUT").feed(X, device_option=hu.gpu_do) self.ws.run(init_op) W = self.ws.blobs["WEIGHT"].fetch() H = np.random.randn( hidden_size, N, num_layers * num_directions).astype( np.float32) C = np.random.randn( hidden_size, N, num_layers * num_directions).astype( np.float32) if rnn_mode == "lstm" else \ np.empty((1,)).astype(np.float32) # unused in GRU inputs = [X, H, C, W] input_idxs = [i for (i, _) in enumerate(inputs)] \ if rnn_mode == "lstm" else [0, 1, 3] # ignore C for input_idx in input_idxs: self.assertGradientChecks( hu.gpu_do, op, inputs, input_idx, [0, 1, 2]) @given(ndim=st.integers(1, 4), axis=st.integers(0, 3), num_inputs=st.integers(2, 4), **hu.gcs) def test_depth_concat(self, ndim, axis, num_inputs, gc, dc): assume(axis < ndim) input_names = ['X0', 'X1', 'X2', 'X3'][:num_inputs] shape = [2, 3, 5, 7][:ndim] individual_dims = [1, 2, 3, 4, 5][:num_inputs] inputs = [] for i in range(num_inputs): # Sets a unique dim and create the input. shape[axis] = individual_dims[i] inputs.append(np.random.randn(*shape).astype(np.float32)) op = core.CreateOperator("Concat", input_names, ["Y", "Y_dims"], axis=axis) self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(num_inputs): self.assertGradientChecks(gc, op, inputs, i, [0]) @given(num_inputs=st.integers(2, 4), order=st.sampled_from([("NCHW", 1), ("NHWC", 3)]), **hu.gcs) def test_depth_concat_with_order(self, num_inputs, order, gc, dc): input_names = ['X0', 'X1', 'X2', 'X3'][:num_inputs] shape = [2, 3, 5, 7] individual_dims = [1, 2, 3, 4][:num_inputs] inputs = [] for i in range(num_inputs): # Sets a unique dim and create the input. shape[order[1]] = individual_dims[i] inputs.append(np.random.rand(*shape).astype(np.float32)) op = core.CreateOperator("Concat", input_names, ["Y", "Y_dims"], order=order[0]) self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(num_inputs): self.assertGradientChecks(gc, op, inputs, i, [0]) @given(X=hu.arrays(dims=[5, 2], elements=st.floats(min_value=0.0, max_value=10.0)), **hu.gcs_cpu_only) def test_last_n_windows(self, X, gc, dc): workspace.FeedBlob('input', X) collect_net = core.Net('collect_net') collect_net.LastNWindowCollector( ['input'], ['output'], num_to_collect=7, ) plan = core.Plan('collect_data') plan.AddStep(core.execution_step('collect_data', [collect_net], num_iter=2)) workspace.RunPlan(plan) output = workspace.FetchBlob('output') inputs = workspace.FetchBlob('input') new_output = np.zeros([7, inputs.shape[1]]) for i in range(inputs.shape[0] * 2): new_output[i % 7] = inputs[i % inputs.shape[0]] import numpy.testing as npt npt.assert_almost_equal(output, new_output, decimal=5) @given(batch_size=st.integers(1, 3), stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), dilation=st.integers(1, 3), size=st.integers(7, 10), channels=st.integers(1, 8), **hu.gcs) def test_im2col_layout(self, batch_size, stride, pad, kernel, dilation, size, channels, gc, dc): dkernel = (dilation * (kernel - 1) + 1) assume(size >= dkernel) NCHW_TO_NHWC = (0, 2, 3, 1) NHWC_TO_NCHW = (0, 3, 1, 2) COL_NHWC_TO_NCHW = (4, 2, 3, 0, 1) N = batch_size C = channels H = size W = size out_h = int((H + (2 * pad) - dkernel) / stride + 1) out_w = int((W + (2 * pad) - dkernel) / stride + 1) im_nchw = np.random.rand(N, C, H, W).astype(np.float32) - 0.5 im_nhwc = im_nchw.transpose(NCHW_TO_NHWC) op_im2col_nchw = core.CreateOperator( "Im2Col", ["im_nchw"], ["col_nchw"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order="NCHW", device_option=gc) op_im2col_nhwc = core.CreateOperator( "Im2Col", ["im_nhwc"], ["col_nhwc"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order="NHWC", device_option=gc) self.ws.create_blob("im_nchw").feed(im_nchw, device_option=gc) self.ws.create_blob("im_nhwc").feed(im_nhwc, device_option=gc) self.ws.run(op_im2col_nchw) self.ws.run(op_im2col_nhwc) # there is probably a clever way to spell this in np col_nchw = self.ws.blobs["col_nchw"].fetch() col_nhwc = self.ws.blobs["col_nhwc"].fetch() col_nchw_ = col_nchw.reshape(N, C, kernel, kernel, out_h, out_w) col_nhwc_ = col_nhwc.reshape(N, out_h, out_w, kernel, kernel, C) for i in range(0, N): np.testing.assert_allclose( col_nchw_[i], col_nhwc_[i].transpose(COL_NHWC_TO_NCHW), atol=1e-4, rtol=1e-4) op_col2im_nchw = core.CreateOperator( "Col2Im", ["col_nchw", "im_nchw"], ["out_nchw"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order="NCHW", device_option=gc) op_col2im_nhwc = core.CreateOperator( "Col2Im", ["col_nhwc", "im_nhwc"], ["out_nhwc"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order="NHWC", device_option=gc) self.ws.run(op_col2im_nchw) self.ws.run(op_col2im_nhwc) out_nchw = self.ws.blobs["out_nchw"].fetch() out_nhwc = self.ws.blobs["out_nhwc"].fetch() np.testing.assert_allclose( out_nchw, out_nhwc.transpose(NHWC_TO_NCHW), atol=1e-4, rtol=1e-4) @given(dtype=st.sampled_from([np.float32, np.float64, np.int32, np.bool])) def test_print(self, dtype): data = np.random.permutation(6).astype(dtype) self.ws.create_blob("data").feed(data) op = core.CreateOperator("Print", "data", []) self.ws.run(op) @given(inputs=hu.tensors(n=2), in_place=st.booleans(), momentum=st.floats(min_value=0.1, max_value=0.9), nesterov=st.booleans(), lr=st.floats(min_value=0.1, max_value=0.9), **hu.gcs) def test_momentum_sgd( self, inputs, in_place, momentum, nesterov, lr, gc, dc): grad, m = inputs lr = np.asarray([lr], dtype=np.float32) op = core.CreateOperator( "MomentumSGD", ["grad", "m", "lr"], ["grad" if in_place else "grad_o", "m" if in_place else "m_o"], momentum=momentum, nesterov=int(nesterov), device_option=gc) self.assertDeviceChecks( dc, op, [grad, m, lr], [0]) # Reference def momentum_sgd(grad, m, lr): lr = lr[0] if not nesterov: adjusted_gradient = lr * grad + momentum * m return (adjusted_gradient, adjusted_gradient) else: m_new = momentum * m + lr * grad return ((1 + momentum) * m_new - momentum * m, m_new) self.assertReferenceChecks(gc, op, [grad, m, lr], momentum_sgd) @given(inputs=hu.tensors(n=3), in_place=st.booleans(), decay=st.floats(min_value=0.1, max_value=0.9), momentum=st.floats(min_value=0.1, max_value=0.9), lr=st.floats(min_value=0.1, max_value=0.9), epsilon=st.floats(min_value=1e-5, max_value=1e-2), **hu.gcs) def test_rmsprop_sgd(self, inputs, in_place, decay, momentum, lr, epsilon, gc, dc): grad, ms, mom = inputs ms = np.abs(ms) + 0.01 lr = np.asarray([lr], dtype=np.float32) op = core.CreateOperator( "RmsProp", ["grad", "ms", "mom", "lr"], ["grad" if in_place else "grad_o", "ms" if in_place else "ms_o", "mom" if in_place else "mom_o"], momentum=momentum, decay=decay, epsilon=epsilon, device_option=gc) self.assertDeviceChecks(dc, op, [grad, ms, mom, lr], [0]) def rmsprop(grad, ms, mom, lr): lr = lr[0] ms_o = ms + (1. - decay) * (np.square(grad) - ms) mom_o = momentum * mom + lr * grad / np.sqrt(epsilon + ms_o) grad_o = mom_o return (grad_o, ms_o, mom_o) self.assertReferenceChecks(gc, op, [grad, ms, mom, lr], rmsprop) # Reference @staticmethod def _dense_adagrad(epsilon, w, h, grad, lr): lr = lr[0] h_o = h + np.square(grad) grad_o = lr * grad / (np.sqrt(h_o) + epsilon) w_o = w + grad_o return (w_o, h_o) # Reference @staticmethod def _dense_adam(epsilon, beta1, beta2, w, m1, m2, grad, lr, iters): lr = lr[0] iters = iters[0] t = iters + 1 corrected_local_rate = lr * np.sqrt(1. - np.power(beta2, t)) / \ (1. - np.power(beta1, t)) m1_o = (beta1 * m1) + (1. - beta1) * grad m2_o = (beta2 * m2) + (1. - beta2) * np.square(grad) grad_o = corrected_local_rate * m1_o / \ (np.sqrt(m2_o) + epsilon) w_o = w + grad_o return (w_o, m1_o, m2_o) @given(inputs=hu.tensors(n=3), in_place=st.booleans(), lr=st.floats(min_value=0.1, max_value=0.9), epsilon=st.floats(min_value=1e-5, max_value=1e-2), engine=st.sampled_from([None, "SIMD"]), **hu.gcs_cpu_only) def test_adagrad_sgd(self, inputs, in_place, lr, epsilon, engine, gc, dc): w, grad, h = inputs h = np.abs(h) + 0.01 lr = np.asarray([lr], dtype=np.float32) op = core.CreateOperator( "Adagrad", ["w", "h", "grad", "lr"], ["w" if in_place else "grad_o", "h" if in_place else "h_o"], epsilon=epsilon, engine=engine, device_option=gc) self.assertDeviceChecks(dc, op, [w, h, grad, lr], [0]) self.assertReferenceChecks(gc, op, [w, h, grad, lr], partial(self._dense_adagrad, epsilon)) @given(inputs=hu.tensors(n=3), lr=st.floats(min_value=0.1, max_value=0.9), epsilon=st.floats(min_value=1e-5, max_value=1e-2), engine=st.sampled_from([None, "SIMD"]), **hu.gcs_cpu_only) def test_sparse_adagrad_sgd(self, inputs, lr, epsilon, engine, gc, dc): w, grad, h = inputs indices = np.arange(h.shape[0]) indices = indices[indices % 2 == 0] grad = grad[indices] h = np.abs(h) lr = np.asarray([lr], dtype=np.float32) op = core.CreateOperator( "SparseAdagrad", ["param", "h", "indices", "grad", "lr"], ["param", "h"], epsilon=epsilon, engine=engine, device_option=gc) self.assertDeviceChecks( dc, op, [w, h, indices, grad, lr], [0]) def adagrad(param, h, i, grad, lr): sw, sh = self._dense_adagrad(epsilon, param[i], h[i], grad, lr) h[i] = sh param[i] = sw return (param, h) self.assertReferenceChecks(gc, op, [w, h, indices, grad, lr], adagrad) @given(inputs=hu.tensors(n=4), in_place=st.booleans(), beta1=st.floats(min_value=0.1, max_value=0.9), beta2=st.floats(min_value=0.1, max_value=0.9), lr=st.floats(min_value=0.1, max_value=0.9), iters=st.integers(min_value=1, max_value=10000), epsilon=st.floats(min_value=1e-5, max_value=1e-2), **hu.gcs_cpu_only) def test_adam_sgd(self, inputs, in_place, beta1, beta2, lr, iters, epsilon, gc, dc): w, grad, m1, m2 = inputs m2 += np.abs(m2) + 0.01 lr = np.asarray([lr], dtype=np.float32) iters = np.asarray([iters], dtype=np.int64) op = core.CreateOperator( "Adam", ["w", "m1", "m2", "grad", "lr", "iters"], ["w" if in_place else "w_o", "m1" if in_place else "m1_o", "m2" if in_place else "m2_o"], beta1=beta1, beta2=beta2, epsilon=epsilon, device_option=gc) input_device_options = {"iters": hu.cpu_do} inputs = [w, m1, m2, grad, lr, iters] self.assertDeviceChecks( dc, op, inputs, [0], input_device_options=input_device_options) self.assertReferenceChecks(gc, op, inputs, partial(self._dense_adam, epsilon, beta1, beta2), input_device_options=input_device_options) @given(inputs=hu.tensors(n=4), beta1=st.floats(min_value=0.1, max_value=0.9), beta2=st.floats(min_value=0.1, max_value=0.9), lr=st.floats(min_value=0.1, max_value=0.9), iters=st.integers(min_value=1, max_value=10000), epsilon=st.floats(min_value=1e-5, max_value=1e-2), **hu.gcs_cpu_only) def test_sparse_adam_sgd(self, inputs, beta1, beta2, lr, iters, epsilon, gc, dc): w, grad, m1, m2 = inputs indices = np.arange(m1.shape[0]) indices = indices[indices % 2 == 0] grad = grad[indices] m2 += np.abs(m2) + 0.01 lr = np.asarray([lr], dtype=np.float32) iters = np.asarray([iters], dtype=np.int64) op = core.CreateOperator( "SparseAdam", ["w", "m1", "m2", "indices", "grad", "lr", "iters"], ["w", "m1", "m2"], beta1=beta1, beta2=beta2, epsilon=epsilon, device_option=gc) input_device_options = {"iters": hu.cpu_do} inputs = [w, m1, m2, indices, grad, lr, iters] self.assertDeviceChecks( dc, op, inputs, [0], input_device_options=input_device_options) def adam(w, m1, m2, i, grad, lr, iters): nw, nm1, nm2 = self._dense_adam(epsilon, beta1, beta2, w[i], m1[i], m2[i], grad, lr, iters) w[i] = nw m1[i] = nm1 m2[i] = nm2 return (w, m1, m2) self.assertReferenceChecks(gc, op, inputs, adam) # Reference @staticmethod def _dense_ftrl(alpha, beta, lambda1, lambda2, w, nz, g): n = np.take(nz, 0, axis=-1) z = np.take(nz, 1, axis=-1) # python port of Sigrid's implementation g2 = g * g sigma = (np.sqrt(n + g2) - np.sqrt(n)) / alpha z += g - sigma * w n += g2 w = (np.sign(z) * lambda1 - z) / ( (beta + np.sqrt(n)) / alpha + lambda2) w[np.abs(z) <= lambda1] = 0 return (w, np.stack([n, z], axis=-1)) @given(inputs=hu.tensors(n=4), in_place=st.booleans(), alpha=st.floats(min_value=0.01, max_value=0.1), beta=st.floats(min_value=0.1, max_value=0.9), lambda1=st.floats(min_value=0.001, max_value=0.1), lambda2=st.floats(min_value=0.001, max_value=0.1), engine=st.sampled_from([None, "SIMD"]), **hu.gcs_cpu_only) def test_ftrl_sgd(self, inputs, in_place, alpha, beta, lambda1, lambda2, engine, gc, dc): var, n, z, grad = inputs n = np.abs(n) nz = np.stack([n, z], axis=-1) op = core.CreateOperator( "Ftrl", ["var", "nz", "grad"], ["var" if in_place else "var_o", "nz" if in_place else "nz_o"], alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2, engine=engine, device_option=gc) self.assertDeviceChecks( dc, op, [var, nz, grad], [0]) self.assertReferenceChecks( gc, op, [var, nz, grad], partial(self._dense_ftrl, alpha, beta, lambda1, lambda2)) @given(inputs=hu.tensors(n=4), alpha=st.floats(min_value=0.01, max_value=0.1), beta=st.floats(min_value=0.1, max_value=0.9), lambda1=st.floats(min_value=0.001, max_value=0.1), lambda2=st.floats(min_value=0.001, max_value=0.1), engine=st.sampled_from([None, "SIMD"]), **hu.gcs_cpu_only) def test_sparse_ftrl_sgd(self, inputs, alpha, beta, lambda1, lambda2, engine, gc, dc): var, n, z, grad = inputs # generate fake subset manually because hypothesis is too complicated :) indices = np.arange(var.shape[0]) indices = indices[indices % 2 == 0] grad = grad[indices] n = np.abs(n) nz = np.stack([n, z], axis=-1) op = core.CreateOperator( "SparseFtrl", ["var", "nz", "indices", "grad"], ["var", "nz"], alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2, engine=engine, device_option=gc) self.assertDeviceChecks( dc, op, [var, nz, indices, grad], [0]) # Reference def ftrl(w, nz, i, g): sw, snz = self._dense_ftrl(alpha, beta, lambda1, lambda2, w[i], nz[i], g) w[i] = sw nz[i] = snz return (w, nz) self.assertReferenceChecks(gc, op, [var, nz, indices, grad], ftrl) @given(input=hu.tensor(max_value=20, max_dim=1, dtype=np.int32, elements=st.integers(min_value=0, max_value=10)), with_remapping=st.booleans(), **hu.gcs_cpu_only) def test_unique(self, input, with_remapping, gc, dc): op = core.CreateOperator( "Unique", ["input"], ["unique"] + (["remapping"] if with_remapping else []), device_option=gc) self.assertDeviceChecks(dc, op, [input], [0]) # Validator def unique_valid(input, unique, remapping=None): self.assertEqual(unique.size, len(set(input))) self.assertEqual(sorted(unique), sorted(set(input))) if with_remapping: self.assertEqual(remapping.shape, input.shape) remapped = [unique[remapping[i]] for i in range(len(input))] np.testing.assert_array_equal(remapped, input) self.assertValidationChecks(gc, op, [input], unique_valid) @given(prediction=hu.arrays(dims=[10, 3], elements=st.floats(allow_nan=False, allow_infinity=False, min_value=0, max_value=1)), labels=hu.arrays(dims=[10], dtype=np.int32, elements=st.integers(min_value=0, max_value=3 - 1)), top_k=st.integers(min_value=1, max_value=3), **hu.gcs) def test_accuracy(self, prediction, labels, top_k, gc, dc): if(top_k > 1): gc = hu.cpu_do op = core.CreateOperator( "Accuracy", ["prediction", "labels"], ["accuracy"], top_k=top_k, device_option=gc ) def op_ref(prediction, labels, top_k): N = prediction.shape[0] correct = 0 for i in range(0, len(prediction)): pred_sorted = sorted([[item,j] for j,item in enumerate(prediction[i])], cmp=lambda x,y: cmp(y[0], x[0])) max_ids = [x[1] for x in pred_sorted[0:top_k]] for m in max_ids: if m == labels[i]: correct += 1 accuracy = correct / N return (accuracy,) self.assertReferenceChecks( device_option=gc, op=op, inputs=[prediction, labels, top_k], reference=op_ref) @given(target_probabilities=hu.arrays( dims=[10], elements=st.floats(allow_nan=False, allow_infinity=False, min_value=0.01, max_value=1)), **hu.gcs) def test_perplexity(self, target_probabilities, gc, dc): op = core.CreateOperator( "Perplexity", ["target_probabilities"], ["perplexity"] ) def op_ref(target_probabilities): N = target_probabilities.shape[0] perplexities = np.power(target_probabilities, -1.0 / N) perplexity = reduce(lambda x, y: x * y, perplexities) return (perplexity,) self.assertReferenceChecks( device_option=gc, op=op, inputs=[target_probabilities], reference=op_ref) @given(lengths=st.lists(st.integers(min_value=0, max_value=10), min_size=0, max_size=10), **hu.gcs_cpu_only) def test_lengths_to_segment_ids(self, lengths, gc, dc): op = core.CreateOperator( "LengthsToSegmentIds", ["lengths"], ["segment_ids"]) def op_ref(lengths): sids = [] for i, l in enumerate(lengths): sids.extend(l * [i]) return (np.array(sids, dtype=np.int32), ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[np.array(lengths, dtype=np.int32)], reference=op_ref) @given(lengths=st.lists(st.integers(min_value=0, max_value=10), min_size=0, max_size=10), **hu.gcs_cpu_only) def test_lengths_range_fill(self, lengths, gc, dc): op = core.CreateOperator( "LengthsRangeFill", ["lengths"], ["increasing_seq"]) def op_ref(lengths): sids = [] for i, l in enumerate(lengths): sids.extend(range(l)) return (np.array(sids, dtype=np.int32), ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[np.array(lengths, dtype=np.int32)], reference=op_ref) @given(**hu.gcs_cpu_only) def test_segment_ids_to_ranges(self, gc, dc): lengths = [4, 6, 3, 2, 0, 4] op = core.CreateOperator( "SegmentIdsToRanges", ["segment_ids"], ["ranges"]) def op_ref(segment_ids): ranges = [np.array([0, 0], dtype=np.int32)] prev = 0 for i, sid in enumerate(segment_ids): while sid != prev: prev += 1 ranges.append(np.array([i, 0], dtype=np.int32)) ranges[-1][1] += 1 return (np.array(ranges, dtype=np.int32), ) def lengths_to_segment_ids(lengths): sids = [] for i, l in enumerate(lengths): sids.extend(l * [i]) return (np.array(sids, dtype=np.int32), ) self.assertReferenceChecks( device_option=gc, op=op, inputs=np.array(lengths_to_segment_ids(lengths), dtype=np.int32), reference=op_ref) @given(lengths=st.lists(st.integers(min_value=0, max_value=10), min_size=0, max_size=10), **hu.gcs_cpu_only) def test_lengths_to_ranges(self, lengths, gc, dc): op = core.CreateOperator( "LengthsToRanges", ["lengths"], ["ranges"]) def op_ref(x): if not x.size: return (x.reshape((0, 2)), ) return (np.column_stack((np.concatenate(([0], np.cumsum(x)[:-1])), x)), ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[np.array(lengths, dtype=np.int32)], reference=op_ref) @given(prediction=hu.arrays(dims=[10, 3], elements=st.floats(allow_nan=False, allow_infinity=False, min_value=0, max_value=1)), labels=hu.arrays(dims=[10], dtype=np.int32, elements=st.integers(min_value=0, max_value=3 - 1)), **hu.gcs) def test_multi_class_accuracy(self, prediction, labels, gc, dc): op = core.CreateOperator( "MultiClassAccuracy", ["prediction", "labels"], ["accuracies", "amounts"] ) def op_ref(prediction, labels): N = prediction.shape[0] D = prediction.shape[1] accuracies = np.empty(D, dtype=float) accuracies.fill(0) amounts = np.empty(D, dtype=int) amounts.fill(0) max_ids = np.argmax(prediction, axis=1) for i in range(0, N): max_id = max_ids[i] label_id = labels[i] if max_id == label_id: accuracies[label_id] += 1 amounts[label_id] += 1 for i in range(0, D): amount = amounts[i] if amount: accuracies[i] /= amount return (accuracies, amounts,) self.assertReferenceChecks( device_option=gc, op=op, inputs=[prediction, labels], reference=op_ref) @given(lengths=st.lists(st.integers(min_value=0, max_value=10), min_size=0, max_size=10), **hu.gcs_cpu_only) def test_segment_ids_to_lengths(self, lengths, gc, dc): op = core.CreateOperator( "SegmentIdsToLengths", ["segment_ids"], ["lengths"]) def lengths_to_ids(lengths): sids = [] for i, l in enumerate(lengths): sids.extend(l * [i]) return sids segment_ids = lengths_to_ids(lengths) def ids_to_lengths(ids): ids_length = len(ids) if ids_length == 0: return (np.array([], dtype=np.int32),) lengths = [] # segment id starts with 0 prev_id = -1 tmp_length = 0 for idx in range(ids_length): cur_id = ids[idx] if cur_id != prev_id: if idx != 0: lengths.append(tmp_length) while prev_id + 1 != cur_id: lengths.append(0) prev_id += 1 prev_id = cur_id tmp_length = 0 tmp_length += 1 lengths.append(tmp_length) return (np.array(lengths, dtype=np.int32),) self.assertReferenceChecks( device_option=gc, op=op, inputs=[np.array(segment_ids, dtype=np.int32)], reference=ids_to_lengths) @given(lengths=st.lists(st.integers(min_value=1, max_value=10), min_size=0, max_size=10), power=st.sampled_from([0.5, 1.0, 1.5, 2.0]), **hu.gcs_cpu_only) def test_lengths_to_weights(self, lengths, power, gc, dc): op = core.CreateOperator( "LengthsToWeights", ["lengths"], ["weights"], power=power) def lengths_to_weights(lengths): weighted_length = [] for l in lengths: weighted_length.extend(l * [1 / pow(l, power)]) return (np.array(weighted_length, dtype=float),) self.assertReferenceChecks( device_option=gc, op=op, inputs=[np.array(lengths, dtype=np.int32)], reference=lengths_to_weights) @given(input_tensor=hu.arrays( dims=[10], elements=st.floats(allow_nan=False, allow_infinity=False)), **hu.gcs) def test_exp(self, input_tensor, gc, dc): op = core.CreateOperator( "Exp", ["input"], ["output"] ) def exp_ref(input_tensor): return (np.exp(input_tensor),) self.assertReferenceChecks( device_option=gc, op=op, inputs=[input_tensor], reference=exp_ref) @given(num_threads=st.integers(1, 10), # noqa num_elements=st.integers(1, 100), capacity=st.integers(1, 5), num_blobs=st.integers(1, 3), do=st.sampled_from(hu.device_options)) def test_blobs_queue_threading(self, num_threads, num_elements, capacity, num_blobs, do): """ - Construct matrices of size N x D - Start K threads - Push all N rows into the queue of capacity C - Pull all N rows out of the queue. - Verify that the output matrices are permutation of the rows of the original matrices. """ import threading import Queue op = core.CreateOperator( "CreateBlobsQueue", [], ["queue"], capacity=capacity, num_blobs=num_blobs, device_option=do) self.ws.run(op) xs = [np.random.randn(num_elements, 5).astype(np.float32) for _ in range(num_blobs)] q = Queue.Queue() for i in range(num_elements): q.put([x[i] for x in xs]) def enqueue(t): while True: feed_blobs = ["x_{}_{}".format(i, t) for i in range(num_blobs)] op = core.CreateOperator( "EnqueueBlobs", ["queue"] + feed_blobs, feed_blobs, device_option=do) try: elems = q.get_nowait() for elem, feed_blob in zip(elems, feed_blobs): self.ws.create_blob(feed_blob).feed( elem, device_option=do) self.ws.run(op) except Queue.Empty: return # Create all blobs before racing on multiple threads # (blob creation is not threadsafe) for t in range(num_threads): for i in range(num_blobs): self.ws.create_blob("x_{}_{}".format(i, t)) threads = [threading.Thread(target=enqueue, args=(t,)) for t in range(num_threads)] for thread in threads: thread.start() for n in range(num_elements): dequeue_blobs = ["y_{}_{}".format(i, n) for i in range(num_blobs)] op = core.CreateOperator( "DequeueBlobs", ["queue"], dequeue_blobs, device_option=do) self.ws.run(op) for thread in threads: thread.join() op = core.CreateOperator("CloseBlobsQueue", ["queue"], []) self.ws.run(op) ys = [np.vstack([self.ws.blobs["y_{}_{}".format(i, n)].fetch() for n in range(num_elements)]) for i in range(num_blobs)] for i in range(num_blobs): self.assertEqual(ys[i].shape, xs[i].shape) for j in range(num_elements): # Verify that the rows of the returned blob are a # permutation. The order may be different due to # different threads racing. self.assertTrue( any(np.array_equal(xs[i][j], ys[i][k]) for k in range(num_elements))) @given(num_producers=st.integers(1, 10), num_consumers=st.integers(1, 10), capacity=st.integers(1, 5), num_blobs=st.integers(1, 3), do=st.sampled_from(hu.device_options)) def test_safe_blobs_queue(self, num_producers, num_consumers, capacity, num_blobs, do): init_net = core.Net('init_net') queue = init_net.CreateBlobsQueue( [], 1, capacity=capacity, num_blobs=num_blobs) producer_steps = [] truth = 0 for i in range(num_producers): name = 'producer_%d' % i net = core.Net(name) blobs = [net.ConstantFill([], 1, value=1.0, run_once=False) for times in range(num_blobs)] status = net.NextName() net.SafeEnqueueBlobs([queue] + blobs, blobs + [status]) count = (i + 1) * 10 step = core.execution_step(name, net, num_iter=count) truth += count producer_steps.append(step) producer_exit_net = core.Net('producer_exit_net') producer_exit_net.CloseBlobsQueue([queue], 0) producer_step = core.execution_step('producer', [ core.execution_step( 'producers', producer_steps, concurrent_substeps=True), core.execution_step('producer_exit', producer_exit_net)] ) consumer_steps = [] counters = [] const_1 = init_net.ConstantFill([], 1, value=1.0) for i in range(num_consumers): name = 'consumer_%d' % i net1 = core.Net(name) blobs = net1.SafeDequeueBlobs([queue], num_blobs + 1) status = blobs[-1] net2 = core.Net(name + '_counter') counter = init_net.ConstantFill([], 1, value=0.0) counters.append(counter) net2.Add([counter, const_1], counter) consumer_steps.append(core.execution_step( name, [net1, net2], should_stop_blob=status)) consumer_step = core.execution_step( 'consumer', consumer_steps, concurrent_substeps=True) init_step = core.execution_step('init', init_net) worker_step = core.execution_step( 'worker', [consumer_step, producer_step], concurrent_substeps=True) plan = core.Plan('test') plan.AddStep(init_step) plan.AddStep(worker_step) self.ws.run(plan) v = 0 for counter in counters: v += self.ws.blobs[str(counter)].fetch().tolist() self.assertEqual(v, truth) @given( data=hu.tensor(), **hu.gcs_cpu_only) def test_squeeze_expand_dims(self, data, gc, dc): dims = [0, 0] if len(data.shape) > 2: dims.append(2) op = core.CreateOperator( "ExpandDims", ["data"], ["expanded"], dims=dims) def expand_dims_ref(data, *args, **kw): inc_dims = list(set(dims)) inc_dims.sort() r = data for dim in inc_dims: r = np.expand_dims(r, axis=dim) return (r, ) def squeeze_ref(data, *args, **kw): dec_dims = list(set(dims)) dec_dims.sort(reverse=True) r = data for dim in dec_dims: r = np.squeeze(r, axis=dim) return (r, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data], reference=expand_dims_ref, output_to_grad='expanded', grad_reference=squeeze_ref) @given(**hu.gcs_cpu_only) def test_tt_layer(self, gc, dc): seed = 1234 np.random.seed(seed) inp_sizes = [2, 2, 2, 2] out_sizes = [2, 2, 2, 2] tt_ranks = [1, 3, 3, 3, 1] op = core.CreateOperator( "TT", ["X", "b", "cores"], ["Y"], inp_sizes=inp_sizes, out_sizes=out_sizes, tt_ranks=tt_ranks, ) X = np.expand_dims( np.random.rand(16).astype(np.float32), axis=0) b = np.array([0] * 16).astype(np.float32) cores = tt_core.init_tt_cores(inp_sizes, out_sizes, tt_ranks) self.ws.create_blob("X").feed(X) self.ws.create_blob("b").feed(b) self.ws.create_blob("cores").feed(cores) self.ws.run(op) Y = self.ws.blobs[("Y")].fetch() Y = Y.reshape([16]) golden = np.array([-9.51763490e-07, -1.28442286e-06, -2.86281141e-07, 2.28865644e-07, -1.96180017e-06, -1.78920531e-06, 9.31094666e-07, -2.04273989e-07, 1.70017107e-06, 1.64845711e-06, -1.06099132e-06, -4.69111137e-07, 6.57552358e-08, -1.28942040e-08, -2.29114004e-07, -1.04262714e-06]) # This golden array is dependent on the specified inp_sizes, out_sizes, # tt_ranks, and seed. Changing these will cause the test to fail. self.assertAlmostEqual(np.linalg.norm(golden - Y), 0, delta=1e-12) @given(num_workers=st.integers(1, 10), net_type=st.sampled_from( ["simple", "dag"] + (["async_dag"] if workspace.has_gpu_support else [])), do=st.sampled_from(hu.device_options)) def test_dag_net_forking(self, net_type, num_workers, do): from caffe2.python.cnn import CNNModelHelper m = CNNModelHelper() n = 10 d = 2 depth = 2 iters = 5 np.random.seed(1701) # Build a binary tree of FC layers, summing at each node. for i in reversed(range(depth)): for j in range(2 ** i): bottom_1 = "{}_{}".format(i + 1, 2 * j) bottom_2 = "{}_{}".format(i + 1, 2 * j + 1) mid_1 = "{}_{}_m".format(i + 1, 2 * j) mid_2 = "{}_{}_m".format(i + 1, 2 * j + 1) top = "{}_{}".format(i, j) m.FC( bottom_1, mid_1, dim_in=d, dim_out=d, weight_init=m.ConstantInit(np.random.randn()), bias_init=m.ConstantInit(np.random.randn())) m.FC( bottom_2, mid_2, dim_in=d, dim_out=d, weight_init=m.ConstantInit(np.random.randn()), bias_init=m.ConstantInit(np.random.randn())) m.net.Sum([mid_1, mid_2], top) m.net.SquaredL2Distance(["0_0", "label"], "xent") m.net.AveragedLoss("xent", "loss") input_to_grad = m.AddGradientOperators(["loss"]) m.Proto().device_option.CopyFrom(do) m.param_init_net.Proto().device_option.CopyFrom(do) m.Proto().type = net_type m.Proto().num_workers = num_workers self.ws.run(m.param_init_net) print(str(m.Proto())) def run(): import numpy as np np.random.seed(1701) input_blobs = ["{}_{}".format(depth, j) for j in range(2 ** depth)] for input_blob in input_blobs: self.ws.create_blob(input_blob).feed( np.random.randn(n, d).astype(np.float32), device_option=do) self.ws.create_blob("label").feed( np.random.randn(n, d).astype(np.float32), device_option=do) self.ws.run(m.net) gradients = [ self.ws.blobs[str(input_to_grad[input_blob])].fetch() for input_blob in input_blobs] return gradients outputs = [run() for _ in range(iters)] for output in outputs[1:]: np.testing.assert_array_equal(outputs[0], output) self.assertAlmostEqual(np.sum(np.square(output)), 91.81752, delta=1e-2) @given(input=hu.tensor(min_dim=2, max_dim=6, dtype=np.int32, elements=st.integers(min_value=0, max_value=2**32 - 1)), slice_dim=st.integers(), a=st.integers(), b=st.integers(), is_empty=st.booleans(), **hu.gcs_cpu_only) def test_slice(self, input, slice_dim, a, b, is_empty, gc, dc): slice_dim = slice_dim % len(input.shape) if (is_empty): input = np.random.rand(*([0] + list(input.shape))).astype(np.int32) slice_dim += 1 a = a % input.shape[slice_dim] b = b % input.shape[slice_dim] + 1 start_vec = np.zeros(len(input.shape), dtype=np.int32) end_vec = np.ones(len(input.shape), dtype=np.int32) * -1 start_vec[slice_dim] = min(a, b) end_vec[slice_dim] = max(a, b) op = core.CreateOperator( "Slice", ["input", "start", "end"], ["output"]) def slice_ref(x, s, e): if len(s.shape) == 0: return x slc = [slice(si, None if ei == -1 else ei) for si, ei in zip(s, e)] return (x[slc], ) self.assertReferenceChecks(gc, op, [input, start_vec, end_vec], slice_ref) @given(data=hu.tensor(), **hu.gcs_cpu_only) def test_shape(self, data, gc, dc): op = core.CreateOperator("Shape", ["data"], ["shape"]) self.assertReferenceChecks(gc, op, [data], lambda x: (x.shape, )) @given(data=hu.tensor(), **hu.gcs_cpu_only) def test_has_elements(self, data, gc, dc): op = core.CreateOperator("HasElements", ["data"], ["has_elements"]) self.assertReferenceChecks(gc, op, [data], lambda x: (len(x) > 0, )) op = core.CreateOperator("IsEmpty", ["data"], ["is_empty"]) self.assertReferenceChecks(gc, op, [data], lambda x: (len(x) == 0, )) @given(initial_iters=st.integers(0, 100), max_iters=st.integers(0, 100)) def test_should_stop_as_criteria_net_execution_step( self, initial_iters, max_iters): net = core.Net("net") net.Iter(["iter"], ["iter"]) self.ws.create_blob("iter").feed( np.asarray([initial_iters]).astype(np.int64)) self.ws.create_blob("num_iters").feed( np.asarray([max_iters]).astype(np.int64)) criteria_net = core.Net("criteria") criteria_net.GE(["iter", "num_iters"], ["stop"]) criteria_net.Proto().external_output.extend(["stop"]) plan = core.Plan('plan') plan.AddStep(core.execution_step( 'step', [criteria_net, net], should_stop_blob=core.BlobReference("stop"))) self.ws.run(plan) iters = self.ws.blobs[("iter")].fetch() self.assertEqual(iters.dtype, np.int64) self.assertEqual(iters[0], max(initial_iters, max_iters)) def test_disabled_execution_step(self): def createNets(i, disabled): should_stop = 'should_stop_{}'.format(i) output = 'output_{}'.format(i) # init content and stop signal init = core.Net("init_{}".format(i)) init.ConstantFill( [], [output], shape=[1], value=0.0 ) init.Cast([output], [should_stop], to='bool') # decide if disabled or not criterion = core.Net("criterion_{}".format(i)) tmp = criterion.ConstantFill( [], shape=[1], value=1.0 if disabled else 0.0 ) criterion.Cast([tmp], [should_stop], to='bool') criterion.Proto().external_output.extend([should_stop]) # the body net is just to turn a 0 blob to 1 net = core.Net("net_{}".format(i)) net.ConstantFill( [], [output], shape=[1], value=1.0 ) # always end the loop ender = core.Net("ender_{}".format(i)) tmp = ender.ConstantFill( [], shape=[1], value=1.0 ) ender.Cast([tmp], [should_stop], to='bool') ender.Proto().external_output.extend([should_stop]) return [init, criterion, net, ender] nets = [createNets(1, False), createNets(2, True), createNets(3, False)] steps = [ core.execution_step( 'step_1', nets[0], should_stop_blob=core.BlobReference('should_stop_1')), core.execution_step( 'step_2', nets[1], should_stop_blob=core.BlobReference('should_stop_2')), core.execution_step('step_3', nets[2]) ] expected = [1.0, 0.0, 1.0] plan = core.Plan('plan') plan.AddStep(core.execution_step('all_steps', steps, num_iter=3)) self.ws.run(plan) for i, net in enumerate(nets): self.assertEqual( self.ws.blobs['output_{}'.format(i + 1)].fetch()[0], expected[i]) @given(initial_iters=st.integers(0, 100), num_iters=st.integers(0, 100)) def test_iter_count_with_execution_step(self, initial_iters, num_iters): net = core.Net("net") net.Iter(["iter"], ["iter"]) self.ws.create_blob("iter").feed( np.asarray([initial_iters]).astype(np.int64)) step = core.ExecutionStep("step", [net]) step.SetIter(num_iters) plan = core.Plan("plan") plan.AddStep(step) self.ws.run(plan) iters = self.ws.blobs[("iter")].fetch() self.assertEqual(iters.dtype, np.int64) self.assertEqual(iters[0], initial_iters + num_iters) @given(initial_iters=st.integers(0, 100), num_iters=st.integers(0, 100), num_nets=st.integers(0, 5)) def test_atomic_iter_with_concurrent_steps(self, initial_iters, num_iters, num_nets): init_net = core.Net("init_net") iter_mutex = init_net.CreateMutex([], ["iter_mutex"]) self.ws.create_blob("iter").feed( np.asarray([initial_iters]).astype(np.int64)) concurrent_steps = core.ExecutionStep("concurrent_steps", num_iter=num_iters) for i in range(num_nets): net = core.Net("net_{}".format(i)) net.AtomicIter([iter_mutex, "iter"], ["iter"]) step = core.ExecutionStep("step", [net]) concurrent_steps.AddSubstep(step) concurrent_steps.SetConcurrentSubsteps(True) plan = core.Plan("plan") plan.AddStep(concurrent_steps) self.ws.run(init_net) self.ws.run(plan) iters = self.ws.blobs[("iter")].fetch() self.assertEqual(iters.dtype, np.int64) self.assertEqual(iters[0], initial_iters + num_iters * num_nets) @given(a=hu.tensor(), src=st.sampled_from(_NUMPY_TYPE_TO_ENUM.keys()), dst=st.sampled_from(_NUMPY_TYPE_TO_ENUM.keys()), use_name=st.booleans(), **hu.gcs) def test_cast(self, a, src, dst, use_name, gc, dc): a = a.astype(src) # Casting from a float type outside the range of the integral # type is UB. ftypes = [np.float32, np.float64] if src in ftypes and dst not in ftypes and dst is not np.bool: info = np.iinfo(dst) a = np.clip(a, info.min, info.max) def ref(data): return [data.astype(dst)] to = _NUMPY_TYPE_TO_ENUM[dst] if use_name: to = TensorProto.DataType.Name(to).lower() op = core.CreateOperator('Cast', ["X"], ["Y"], to=to) self.assertDeviceChecks(dc, op, [a], [0]) out, = self.assertReferenceChecks(gc, op, [a], ref) self.assertEqual(dst, out.dtype) @given(data=_dtypes(dtypes=[np.int32, np.int64, np.float32, np.bool]). flatmap(lambda dtype: hu.tensor( min_dim=1, dtype=dtype, elements=hu.elements_of_type(dtype))), has_input=st.booleans(), has_extra_shape=st.booleans(), extra_shape=st.lists( min_size=1, max_size=5, elements=st.integers(1, 5)), **hu.gcs) def test_constant_fill(self, data, has_input, has_extra_shape, extra_shape, gc, dc): dtype = data.dtype.type # in opt mode, np.bool is converted into np.bool_ if data.dtype == np.dtype(np.bool): dtype = np.bool value = data.item(0) gt_shape = data.shape inputs = [data] enum_type = _NUMPY_TYPE_TO_ENUM[dtype] if has_input: if has_extra_shape: op = core.CreateOperator('ConstantFill', ["X"], ["Y"], dtype=enum_type, extra_shape=extra_shape, value=value) gt_shape += tuple(extra_shape) else: op = core.CreateOperator('ConstantFill', ["X"], ["Y"], dtype=enum_type, value=value) else: op = core.CreateOperator('ConstantFill', [], ["Y"], dtype=enum_type, value=value, shape=list(gt_shape)) inputs = [] def ref(inputs=None): outputs = np.full(shape=gt_shape, fill_value=value, dtype=dtype) return [outputs] self.assertDeviceChecks(dc, op, inputs, [0]) out, = self.assertReferenceChecks(gc, op, inputs, ref) self.assertEqual(dtype, out.dtype) @given(t=st.integers(1, 5), n=st.integers(1, 5), d=st.integers(1, 5)) def test_elman_recurrent_network(self, t, n, d): from caffe2.python import cnn np.random.seed(1701) step_net = cnn.CNNModelHelper(name="Elman") # TODO: name scope external inputs and outputs step_net.Proto().external_input.extend( ["input_t", "seq_lengths", "timestep", "hidden_t_prev", "gates_t_w", "gates_t_b"]) step_net.Proto().type = "simple" step_net.Proto().external_output.extend(["hidden_t", "gates_t"]) step_net.FC("hidden_t_prev", "gates_t", dim_in=d, dim_out=d, axis=2) step_net.net.Sum(["gates_t", "input_t"], ["gates_t"]) step_net.net.Sigmoid(["gates_t"], ["hidden_t"]) # Initialize params for step net in the parent net for op in step_net.param_init_net.Proto().op: workspace.RunOperatorOnce(op) backward_ops, backward_mapping = core.GradientRegistry.GetBackwardPass( step_net.Proto().op, {"hidden_t": "hidden_t_grad"}) backward_mapping = {str(k): str(v) for k, v in backward_mapping.items()} backward_step_net = core.Net("ElmanBackward") del backward_step_net.Proto().op[:] backward_step_net.Proto().op.extend(backward_ops) assert backward_mapping["input_t"] == "gates_t_grad" links = [ ("hidden_t_prev", "hidden", 0), ("hidden_t", "hidden", 1), ("input_t", "input", 0), ] link_internal, link_external, link_offset = zip(*links) backward_links = [ ("hidden_t_prev_grad", "hidden_grad", 0), ("hidden_t_grad", "hidden_grad", 1), ("gates_t_grad", "input_grad", 0), ] backward_link_internal, backward_link_external, backward_link_offset = \ zip(*backward_links) backward_step_net.Proto().external_input.extend(["hidden_t_grad"]) backward_step_net.Proto().external_input.extend( step_net.Proto().external_input) backward_step_net.Proto().external_input.extend( step_net.Proto().external_output) inputs = ["input", "seq_lengths", "gates_t_w", "gates_t_b", "hidden_input"] recurrent_inputs = ["hidden_input"] op = core.CreateOperator( "RecurrentNetwork", inputs, ["output", "hidden", "hidden_output", "step_workspaces"], alias_src=["hidden", "hidden"], alias_dst=["output", "hidden_output"], alias_offset=[1, -1], recurrent_states=["hidden"], recurrent_inputs=recurrent_inputs, recurrent_input_pos=map(inputs.index, recurrent_inputs), link_internal=link_internal, link_external=link_external, link_offset=link_offset, backward_link_internal=backward_link_internal, backward_link_external=backward_link_external, backward_link_offset=backward_link_offset, param=map(inputs.index, step_net.params), step_net=str(step_net.Proto()), backward_step_net=str(backward_step_net.Proto())) workspace.FeedBlob( "input", np.random.randn(t, n, d).astype(np.float32)) workspace.FeedBlob( "hidden_input", np.random.randn(1, n, d).astype(np.float32)) workspace.FeedBlob( "seq_lengths", np.random.randint(0, t, size=(n,)).astype(np.int32)) def reference(input, seq_lengths, gates_w, gates_b, hidden_input): T = input.shape[0] N = input.shape[1] D = input.shape[2] hidden = np.zeros(shape=(T + 1, N, D)) assert hidden.shape[0] == T + 1 assert hidden.shape[1] == N assert hidden.shape[2] == D hidden[0, :, :] = hidden_input for t in range(T): input_t = input[t].reshape(1, N, D) hidden_t_prev = hidden[t].reshape(1, N, D) gates = np.dot(hidden_t_prev, gates_w.T) gates = gates.reshape(1, N, D) + input_t.reshape(1, N, D) hidden[t + 1] = sigmoid(gates) return hidden[1:], hidden, hidden[-1].reshape(1, N, D) self.assertReferenceChecks( hu.cpu_do, op, [workspace.FetchBlob(name) for name in ["input", "seq_lengths", "gates_t_w", "gates_t_b", "hidden_input"]], reference, outputs_to_check=[0, 1, 2]) for param in [0, 2, 3]: self.assertGradientChecks( hu.cpu_do, op, [workspace.FetchBlob(name) for name in ["input", "seq_lengths", "gates_t_w", "gates_t_b", "hidden_input"]], param, [0]) @given(n=st.integers(1, 5), c=st.integers(1, 5), h=st.integers(1, 5), w=st.integers(1, 5), pad=st.integers(0, 2), block_size=st.integers(2, 3), **hu.gcs) def test_space_to_batch(self, n, c, h, w, pad, block_size, gc, dc): assume((h + 2 * pad) % block_size == 0) assume((w + 2 * pad) % block_size == 0) X = np.random.randn(n, c, h, w).astype(np.float32) op = core.CreateOperator("SpaceToBatch", ["X"], ["Y"], pad=pad, block_size=block_size) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(n=st.integers(1, 5), c=st.integers(1, 5), h=st.integers(1, 5), w=st.integers(1, 5), pad=st.integers(0, 2), block_size=st.integers(2, 3), **hu.gcs) def test_batch_to_space(self, n, c, h, w, pad, block_size, gc, dc): assume((h + 2 * pad) % block_size == 0) assume((w + 2 * pad) % block_size == 0) X = np.random.randn( n * block_size * block_size, c, (h + 2 * pad) / block_size, (w + 2 * pad) / block_size).astype(np.float32) op = core.CreateOperator("BatchToSpace", ["X"], ["Y"], pad=pad, block_size=block_size) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(X=hu.tensor(), in_place=st.booleans(), scale=st.floats(min_value=-2.0, max_value=2.0), **hu.gcs) def test_scale(self, X, in_place, scale, gc, dc): op = core.CreateOperator( "Scale", ["X"], ["Y" if not in_place else "X"], scale=scale) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(X=_dtypes().flatmap(lambda dtype: hu.tensor(dtype=dtype)), seed=st.integers(min_value=0, max_value=65536), null_axes=st.booleans(), **hu.gcs) @settings(max_examples=2, timeout=100) def test_transpose(self, X, seed, null_axes, gc, dc): if null_axes: axes = None op = core.CreateOperator("Transpose", "input", "output") else: np.random.seed(int(seed)) axes = [int(v) for v in list(np.random.permutation(X.ndim))] op = core.CreateOperator( "Transpose", "input", "output", axes=axes) def transpose_ref(x, axes): return (np.transpose(x, axes),) self.assertReferenceChecks(gc, op, [X, axes], transpose_ref) if X.dtype != np.int32 and X.dtype != np.int64: self.assertGradientChecks(gc, op, [X], 0, [0]) @given(s=st.text()) def test_string_serde(self, s): s = s.encode('ascii', 'ignore') self.ws.create_blob("a").feed(s) serialized = self.ws.blobs["a"].serialize("a") self.ws.create_blob("b").deserialize(serialized) self.assertEqual(s, self.ws.blobs[("a")].fetch()) self.assertEqual(s, self.ws.blobs[("b")].fetch()) @given(n=st.integers(1, 3), dim=st.integers(4, 16), **hu.gcs_cpu_only) def test_distances(self, n, dim, gc, dc): X = np.random.uniform(-1, 1, (n, dim)).astype(np.float32) Y = np.random.uniform(-1, 1, (n, dim)).astype(np.float32) self.ws.create_blob("X").feed(X) self.ws.create_blob("Y").feed(Y) def check_grad(op): self.assertGradientChecks(gc, op, [X, Y], 0, [0], stepsize=1e-2, threshold=1e-2) self.assertGradientChecks(gc, op, [X, Y], 1, [0], stepsize=1e-2, threshold=1e-2) l2_op = core.CreateOperator("SquaredL2Distance", ["X", "Y"], ["l2_dist"]) self.ws.run(l2_op) np.testing.assert_allclose(self.ws.blobs[("l2_dist")].fetch(), np.square(X - Y).sum(axis=1) * 0.5, rtol=1e-4, atol=1e-4) check_grad(l2_op) dot_op = core.CreateOperator("DotProduct", ["X", "Y"], ["dot"]) self.ws.run(dot_op) np.testing.assert_allclose(self.ws.blobs[("dot")].fetch(), np.multiply(X, Y).sum(axis=1), rtol=1e-4, atol=1e-4) check_grad(dot_op) kEps = 1e-12 cos_op = core.CreateOperator("CosineSimilarity", ["X", "Y"], ["cos"]) self.ws.run(cos_op) cos = np.divide(np.multiply(X, Y).sum(axis=1), np.multiply(np.linalg.norm(X, axis=1) + kEps, np.linalg.norm(Y, axis=1) + kEps)) np.testing.assert_allclose(self.ws.blobs[("cos")].fetch(), cos, rtol=1e-4, atol=1e-4) check_grad(cos_op) @given(pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), size=st.integers(1, 10), input_channels=st.integers(1, 5), batch_size=st.integers(1, 5), order=st.sampled_from(["NCHW", "NHWC"]), mode=st.sampled_from(["constant", "reflect", "edge"]), **hu.gcs) def test_pad_image(self, pad_t, pad_l, pad_b, pad_r, size, input_channels, batch_size, order, mode, gc, dc): assume(size > max(pad_b, pad_r, pad_t, pad_l)) op = core.CreateOperator( "PadImage", ["X"], ["Y"], pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, mode=mode, order=order, ) if order == "NHWC": X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 def numpy_pad_ref(x): return (np.pad( x, ((0, 0), (pad_t, pad_b), (pad_l, pad_r), (0, 0)), mode),) else: X = np.random.rand( batch_size, input_channels, size, size).astype(np.float32) - 0.5 def numpy_pad_ref(x): return (np.pad( x, ((0, 0), (0, 0), (pad_t, pad_b), (pad_l, pad_r)), mode),) self.assertReferenceChecks(gc, op, [X], numpy_pad_ref) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(size=st.integers(7, 10), input_channels=st.integers(1, 10), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), epsilon=st.floats(min_value=1e-4, max_value=1e-2), **hu.gcs_cpu_only) def test_instance_norm(self, size, input_channels, batch_size, order, epsilon, gc, dc): op = core.CreateOperator( "InstanceNorm", ["X", "scale", "bias"], ["Y"], order=order, epsilon=epsilon, ) np.random.seed(1701) scale = np.random.rand(input_channels).astype(np.float32) + 0.5 bias = np.random.rand(input_channels).astype(np.float32) - 0.5 X = np.random.rand( batch_size, input_channels, size, size).astype(np.float32) - 0.5 if order == "NHWC": X = X.swapaxes(1, 2).swapaxes(2, 3) def ref_nchw(x, scale, bias): x = x.reshape(batch_size * input_channels, size * size) y = (x - x.mean(1)[:, np.newaxis]) y /= np.sqrt(x.var(1) + epsilon)[:, np.newaxis] y = y.reshape(batch_size, input_channels, size, size) y = y * scale.reshape(1, input_channels, 1, 1) y = y + bias.reshape(1, input_channels, 1, 1) return (y, ) def ref_nhwc(x, scale, bias): x = x.swapaxes(2, 3).swapaxes(1, 2) y = ref_nchw(x, scale, bias)[0] return (y.swapaxes(1, 2).swapaxes(2, 3), ) self.assertReferenceChecks( gc, op, [X, scale, bias], ref_nchw if order == "NCHW" else ref_nhwc) # TODO(jiayq): when there are backward and GPU implementations, enable # these two. # self.assertDeviceChecks(dc, op, [X, scale, bias], [0]) # self.assertGradientChecks(gc, op, [X, scale, bias], 0, [0]) ws = workspace.C.Workspace() feeds = [("X", X), ("scale", scale), ("bias", bias)] for blob, arr in feeds: ws.create_blob(blob).feed(arr) for i in range(100): ws.run(op) for blob, arr in feeds: np.testing.assert_array_equal(ws.blobs[blob].fetch(), arr) @given(sizes=st.lists(st.integers(1, 100), min_size=1), in_place=st.booleans(), **hu.gcs) def test_unsafe_coalesce(self, sizes, in_place, gc, dc): gAlignment = 32 Xs = [np.random.randn(size) .astype(np.random.choice([np.float32, np.float64, np.uint8])) for size in sizes] op = core.CreateOperator( "UnsafeCoalesce", ["X_{}".format(i) for i, _ in enumerate(sizes)], [("X_{}" if in_place else "Y_{}").format(i) for i, _ in enumerate(sizes)] + ["coalesced"]) self.assertDeviceChecks(dc, op, Xs, list(range(len(sizes) + 1))) def unsafe_coalesce(*xs): def to_uint8(x): x_aligned_bytes = ((x.nbytes + gAlignment - 1) // gAlignment) \ * gAlignment x_aligned = np.zeros( shape=(x_aligned_bytes // x.dtype.itemsize, ), dtype=x.dtype) x_aligned[:x.size] = x x_cast = np.fromstring(x_aligned.tobytes(), dtype='<u1') return x_cast flat = [to_uint8(x) for x in xs] coalesced = np.concatenate(flat) return list(xs) + [coalesced] self.assertReferenceChecks(gc, op, Xs, unsafe_coalesce) @given(X=hu.tensor(min_dim=2, max_dim=2, elements=st.floats(min_value=0.5, max_value=1.0)), **hu.gcs_cpu_only) def test_normalize(self, X, gc, dc): op = core.CreateOperator("Normalize", "X", "Y") def ref_normalize(X): x_normed = X / ( np.sqrt((X**2).sum(-1))[:, np.newaxis] + np.finfo(X.dtype).tiny) return (x_normed,) self.assertReferenceChecks(gc, op, [X], ref_normalize) self.assertDeviceChecks(dc, op, [X], [0]) self.assertGradientChecks(gc, op, [X], 0, [0]) @given(n=st.integers(10000, 10003), **hu.gcs_cpu_only) def test_piecewise_linear_transform(self, n, gc, dc): W = np.random.uniform(-1, 1, (2, n)).astype(np.float32) b = np.random.uniform(-1, 1, (2, n)).astype(np.float32) # make sure bucket range are increating! bucket_range = np.random.uniform(0.1, 0.9, (2, n + 1)).astype(np.float32) bucket_base = np.array(list(range(n + 1))) bucket_range[0, :] = bucket_range[0, :] + bucket_base bucket_range[1, :] = bucket_range[1, :] + bucket_base # make x[i] inside bucket i, for the ease of testing X = np.random.uniform(0, 0.9, (n, 2)).astype(np.float32) for i in range(len(X)): X[i][0] = X[i][0] * bucket_range[0][i] + \ (1 - X[i][0]) * bucket_range[0][i + 1] X[i][1] = X[i][1] * bucket_range[1][i] + \ (1 - X[i][1]) * bucket_range[1][i + 1] op = core.CreateOperator( "PiecewiseLinearTransform", ["X"], ["Y"], bounds=bucket_range.flatten().tolist(), slopes=W.flatten().tolist(), intercepts=b.flatten().tolist(), pieces=n ) def piecewise(x, *args, **kw): return [W.transpose() * x + b.transpose()] self.assertReferenceChecks(gc, op, [X], piecewise) self.assertDeviceChecks(dc, op, [X], [0]) if __name__ == "__main__": unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/pipeline.py
315
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, queue_util from caffe2.python.dataio import Reader, Writer from caffe2.python.net_builder import NetBuilder from caffe2.python.schema import as_record, Field from caffe2.python.task import Task, TaskGroup class Output(object): """ Represents the result of a processor function. A processor can either return an Output, or it can return a record, in which case an Output will be created for it afterwards. """ def __init__(self, nets=None, record=None, should_stop=None): builder_children = NetBuilder.current().get() assert nets is None or len(builder_children) == 0, ( 'Cannot both use `ops` syntax and return a list of nets.') if nets is None: nets = builder_children if isinstance(nets, core.Net): nets = [nets] self.nets = [] if nets is None else list(nets) self.record = None if record is None else as_record(record) self.should_stop = should_stop DEFAULT_QUEUE_CAPACITY = 100 def _init_output(output, capacity, global_init_net, global_exit_net): if isinstance(output, Writer): assert capacity is None, 'capacity would not be used.' out_queue = None writer = output elif hasattr(output, 'writer'): assert capacity is None, 'capacity would not be used.' out_queue = output writer = output.writer() elif output is None: out_queue = queue_util.Queue( capacity=( capacity if capacity is not None else DEFAULT_QUEUE_CAPACITY)) writer = out_queue.writer() else: raise ValueError('output must be a reader, queue or stream.') writer.setup_ex(global_init_net, global_exit_net) return out_queue, writer def make_processor(processor): if processor is None: return lambda rec: rec elif isinstance(processor, core.Net): return NetProcessor(processor) else: return processor def normalize_processor_output(output): """ Allow for processors to return results in several formats. TODO(azzolini): simplify once all processors use NetBuilder API. """ if isinstance(output, Output): """ Processor returned an Output. """ return output elif isinstance(output, Field): """ Processor returned a record. """ return Output(record=output) elif isinstance(output, tuple): is_record_and_blob = ( len(output) == 2 and isinstance(output[0], Field) and isinstance(output[1], core.BlobReference)) if is_record_and_blob: """ Processor returned (record, stop_blob) """ return Output(None, *output) else: """ Processor returned (nets, record, stop_blob) """ return Output(*output) else: """ Processor returned nets, no output """ return Output(output) def pipe( input, output=None, num_threads=1, processor=None, name=None, capacity=None, group=None): """ Given a Reader, Queue or DataStream in `input`, and optionally, a Writer, Queue or DataStream in `output`, creates a Task that, when run, will pipe the input into the output, using multiple parallel threads. Additionally, if a processor is given, it will be called between reading and writing steps, allowing it to transform the record. Args: input: either a Reader, Queue or DataStream that will be read until a stop is signaled either by the reader or the writer. output: either a Writer, a Queue or a DataStream that will be writen to as long as neither reader or writer signal a stop condition. If output is not provided or is None, a Queue is created with given `capacity` and writen to. num_threads: number of concurrent threads used for processing and piping. If set to 0, no Task is created, and a reader is returned instead -- the reader returned will read from the reader passed in and process it. processor: (optional) function that takes an input record and optionally returns a record; this will be called between read and write steps. If the processor does not return a record, a writer will not be instantiated. Processor can also be a core.Net with input and output records properly set. In that case, a NetProcessor is instantiated, cloning the net for each of the threads. name: (optional) name of the task to be created. capacity: when output is not passed, a queue of given `capacity` is created and written to. group: (optional) explicitly add the created Task to this TaskGroup, instead of using the currently active one. Returns: Output Queue, DataStream, Reader, or None, depending on the parameters passed. """ result, step = _pipe_step( input, output, num_threads, processor, name, capacity, group) if step is not None: Task(step=step, group=group) return result def pipe_and_output( input, output=None, num_threads=1, processor=None, name=None, capacity=None, group=None, final_outputs=None): """ Similar to `pipe`, with the additional ability for the pipe Task to return output values to the `Session` once done. Returns: Tuple (out_queue, *task_outputs) out_queue: same as return value of `pipe`. task_outputs: TaskOutput object, fetchable from the client after session.run() returns. """ result, step = _pipe_step( input, output, num_threads, processor, name, capacity, group, final_outputs) assert step is not None task = Task(step=step, group=group, outputs=final_outputs) output = None if final_outputs is not None: output = task.outputs() if type(final_outputs) not in (list, tuple): output = output[0] return result, output def _pipe_step( input, output=None, num_threads=1, processor=None, name=None, capacity=None, group=None, final_outputs=None): """ """ group = TaskGroup.current(group) if name is None: name = 'processor:%d' % group.num_registered_tasks() if isinstance(input, Reader): reader = input elif hasattr(input, 'reader'): reader = input.reader() else: raise ValueError('in must be a reader, queue or streaam.') if processor is not None: reader = ProcessingReader(reader, processor) if num_threads == 0: assert output is None return reader, None global_exit_net = core.Net(name + '_producer_global_exit') global_init_net = core.Net(name + '_producer_global_init') out_queue = None writer = None reader.setup_ex(global_init_net, global_exit_net) steps = [] for thread_id in range(num_threads): init_net = core.Net(name + "_init_net_%d" % thread_id) exit_net = core.Net(name + "_exit_net_%d" % thread_id) read_nets, status, rec = reader.read_record_ex(init_net, exit_net) if rec is not None: if writer is None: out_queue, writer = _init_output( output, capacity, global_init_net, global_exit_net) write_nets, _ = writer.write_record_ex( rec, init_net, exit_net, status) else: write_nets = [] step = core.execution_step( name + "_thread_%d" % thread_id, [ core.execution_step(name + "_init_step", init_net), core.execution_step( name + "_worker_step", list(read_nets) + list(write_nets), should_stop_blob=status ), core.execution_step(name + "_exit_step", exit_net) ] ) steps.append(step) step = core.execution_step( "sender_step", [ core.execution_step('init_step', global_init_net), core.execution_step( "sender_steps", steps, concurrent_substeps=True), core.execution_step('finish_step', global_exit_net), ]) return out_queue, step class ProcessingReader(Reader): """ Reader that reads from a upstream reader, calls the processor, and returns the processed record. """ def __init__(self, reader, processor): Reader.__init__(self) self.reader = reader self.processor = make_processor(processor) def setup_ex(self, init_net, finish_net): self.reader.setup_ex(init_net, finish_net) def read_ex(self, init_net, exit_net): read_nets, status, rec = self.reader.read_record_ex(init_net, exit_net) with NetBuilder(): # Current NetBuilder is optionally used inside the processor, # then its children are retrived inside of # normalize_processor_output. # Once readers and writers also use NetBuilder, # this logic will be more natural. result = normalize_processor_output(self.processor(rec)) read_nets += result.nets if result.should_stop is not None: stop_net = core.Net('stop_net') stop_net.Copy([result.should_stop], [status]) read_nets.append(stop_net) if hasattr(self.processor, 'setup'): init_net.add_attribute(TaskGroup.LOCAL_SETUP, self.processor) self._set_schema(result.record) fields = result.record.field_blobs() if result.record else None return read_nets, status, fields class NetProcessor(object): """ Processor that clones a core.Net each time it's called, executing the cloned net as the processor. It requires the Net to have input and (optionally) output records set, with net.set_input_record() and net.set_output_record(). """ def __init__(self, net, stop_signal=None, thread_init_nets=None): assert isinstance(net, core.Net) assert stop_signal is None or isinstance( stop_signal, core.BlobReference) self.thread_init_nets = thread_init_nets or [] self.net = net self._stop_signal = stop_signal self._blob_maps = [] self._frozen = False self._cloned_init_nets = [] def setup(self, init_net): self._frozen = True cloned_init_nets = self._cloned_init_nets self._cloned_init_nets = [] return cloned_init_nets def __call__(self, rec): assert not self._frozen prefix = '/worker:%d/' % len(self._blob_maps) blob_remap = {} for net in self.thread_init_nets: new_net, _ = core.clone_and_bind_net( net, str(net) + prefix, prefix, blob_remap) self._cloned_init_nets.append(new_net) new_net, remappings = core.clone_and_bind_net( self.net, str(self.net) + prefix, prefix, blob_remap, rec) if self._stop_signal is None: stop_signal = None elif str(self._stop_signal) in remappings: stop_signal = core.BlobReference( remappings[str(self._stop_signal)], net=new_net) else: stop_signal = self._stop_signal self._blob_maps.append(remappings) return Output([new_net], new_net.output_record(), stop_signal) def blob_maps(self): self._frozen = True return self._blob_maps
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/segment_ops_test.py
310
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from functools import partial from hypothesis import given import caffe2.python.hypothesis_test_util as hu import numpy as np class TesterBase: def segment_reduce_op(self, data, segment_ids, reducer, indices=None): segments = self.split(data, segment_ids, indices) output = np.zeros((len(segments), ) + data.shape[1:]) for i, segment in enumerate(segments): if len(segment) > 0: output[i] = reducer(segment) else: output[i] = 0.0 return output def segment_reduce_grad_op( self, data, segment_ids, reducer_grad, grad_out, output, indices=None ): segments = self.split(data, segment_ids, indices) segment_grads = [ reducer_grad(grad_out[i], [output[i]], [segment]) for i, segment in enumerate(segments) ] return self.unsplit(data.shape[1:], segment_grads, segment_ids) def test(self, prefix, input_strategy, refs): tester = self @given(X=input_strategy, **hu.gcs_cpu_only) def test_segment_ops(self, X, gc, dc): for op_name, ref, grad_ref in refs: inputs = ['input%d' % i for i in range(0, len(X))] op = core.CreateOperator(prefix + op_name, inputs, ['output']) def seg_reduce(data, *args): indices, segments = ( args if len(args) == 2 else (None, args[0]) ) out = tester.segment_reduce_op( data=data, segment_ids=segments, indices=indices, reducer=ref ) return (out, ) def seg_reduce_grad(grad_out, outputs, inputs): data = inputs[0] args = inputs[1:] indices, segments = ( args if len(args) == 2 else (None, args[0]) ) # grad r.t. data grad_val = tester.segment_reduce_grad_op( data, segments, grad_ref, grad_out, outputs[0], indices ) # if sparse, include indices along with data gradient data_grad_slice = ( (grad_val, indices) if indices is not None else grad_val ) # other inputs don't have gradient return (data_grad_slice, ) + (None, ) * (len(inputs) - 1) self.assertReferenceChecks( device_option=gc, op=op, inputs=X, reference=seg_reduce, output_to_grad='output', grad_reference=seg_reduce_grad, ) return test_segment_ops class SegmentsTester(TesterBase): def split(self, data, segment_ids, indices=None): """ Given: data[M1 x M2 x ... x Md] the input data indices[N] the index of each entry of segment_ids into data, where 0 <= index[i] < M1, with default indices=[0,1,...N] segment_ids[N] the segment_id for each entry of indices, returns K outputs, each one containing data entries corresponding to one of the segments present in `segment_ids`. """ if segment_ids.size == 0: return [] K = max(segment_ids) + 1 outputs = [ np.zeros( (np.count_nonzero(segment_ids == seg_id), ) + data.shape[1:], dtype=data.dtype ) for seg_id in range(0, K) ] counts = np.zeros(K) for i, seg_id in enumerate(segment_ids): data_idx = i if indices is None else indices[i] outputs[seg_id][counts[seg_id]] = data[data_idx] counts[seg_id] += 1 return outputs def unsplit(self, extra_shape, inputs, segment_ids): """ Inverse operation to `split`, with indices=None """ output = np.zeros((len(segment_ids), ) + extra_shape) if len(segment_ids) == 0: return output K = max(segment_ids) + 1 counts = np.zeros(K) for i, seg_id in enumerate(segment_ids): output[i] = inputs[seg_id][counts[seg_id]] counts[seg_id] += 1 return output class LengthsTester(TesterBase): def split(self, data, lengths, indices=None): K = len(lengths) outputs = [ np.zeros((lengths[seg_id], ) + data.shape[1:], dtype=data.dtype) for seg_id in range(0, K) ] start = 0 for i in range(0, K): for j in range(0, lengths[i]): data_index = start + j if indices is not None: data_index = indices[data_index] outputs[i][j] = data[data_index] start += lengths[i] return outputs def unsplit(self, extra_shape, inputs, lengths): N = sum(lengths) output = np.zeros((N, ) + extra_shape) K = len(lengths) assert len(inputs) == K current = 0 for i in range(0, K): for j in range(0, lengths[i]): output[current] = inputs[i][j] current += 1 return output def sum_grad(grad_out, outputs, inputs): return np.repeat( np.expand_dims(grad_out, axis=0), inputs[0].shape[0], axis=0 ) def logsumexp(x): return np.log(np.sum(np.exp(x), axis=0)) def logsumexp_grad(grad_out, outputs, inputs): sum_exps = np.sum(np.exp(inputs[0]), axis=0) return np.repeat( np.expand_dims(grad_out / sum_exps, 0), inputs[0].shape[0], axis=0 ) * np.exp(inputs[0]) def logmeanexp(x): return np.log(np.mean(np.exp(x), axis=0)) def mean(x): return np.mean(x, axis=0) def mean_grad(grad_out, outputs, inputs): return np.repeat( np.expand_dims(grad_out / inputs[0].shape[0], 0), inputs[0].shape[0], axis=0 ) def max_fwd(x): return np.amax(x, axis=0) def max_grad(grad_out, outputs, inputs): flat_inputs = inputs[0].flatten() flat_outputs = np.array(outputs[0]).flatten() flat_grad_in = np.zeros(flat_inputs.shape) flat_grad_out = np.array(grad_out).flatten() blocks = inputs[0].shape[0] block_size = flat_inputs.shape[0] // blocks for i in range(block_size): out_grad = flat_grad_out[i] out = flat_outputs[i] for j in range(blocks): idx = j * block_size + i if out == flat_inputs[idx]: flat_grad_in[idx] = out_grad break return np.resize(flat_grad_in, inputs[0].shape) REFERENCES_ALL = [ ('Sum', partial(np.sum, axis=0), sum_grad), ('Mean', partial(np.mean, axis=0), mean_grad), ] REFERENCES_SORTED = [ ('RangeSum', partial(np.sum, axis=0), sum_grad), ('RangeLogSumExp', logsumexp, logsumexp_grad), # gradient is the same as sum ('RangeLogMeanExp', logmeanexp, logsumexp_grad), ('RangeMean', mean, mean_grad), ('RangeMax', max_fwd, max_grad), ] class TestSegmentOps(hu.HypothesisTestCase): def test_sorted_segment_ops(self): SegmentsTester().test( 'SortedSegment', hu.segmented_tensor( dtype=np.float32, is_sorted=True, allow_empty=True ), REFERENCES_ALL + REFERENCES_SORTED )(self) def test_unsorted_segment_ops(self): SegmentsTester().test( 'UnsortedSegment', hu.segmented_tensor( dtype=np.float32, is_sorted=False, allow_empty=True ), REFERENCES_ALL )(self) def test_sparse_sorted_segment_ops(self): SegmentsTester().test( 'SparseSortedSegment', hu.sparse_segmented_tensor( dtype=np.float32, is_sorted=True, allow_empty=True ), REFERENCES_ALL )(self) def test_sparse_unsorted_segment_ops(self): SegmentsTester().test( 'SparseUnsortedSegment', hu.sparse_segmented_tensor( dtype=np.float32, is_sorted=False, allow_empty=True ), REFERENCES_ALL )(self) def test_lengths_ops(self): LengthsTester().test( 'Lengths', hu.lengths_tensor( dtype=np.float32, min_value=1, max_value=10, allow_empty=True ), REFERENCES_ALL )(self) def test_sparse_lengths_ops(self): LengthsTester().test( 'SparseLengths', hu.sparse_lengths_tensor( dtype=np.float32, min_value=1, max_value=10, allow_empty=True ), REFERENCES_ALL )(self) if __name__ == "__main__": import unittest unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/conv_test.py
348
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import assume, given import hypothesis.strategies as st import collections from caffe2.python import core, workspace import caffe2.python.hypothesis_test_util as hu class TestConvolution(hu.HypothesisTestCase): # CUDNN does NOT support different padding values and we skip it @given(stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(3, 5), size=st.integers(1, 8), input_channels=st.integers(1, 3), output_channels=st.integers(1, 3), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), engine=st.sampled_from(["", "EIGEN"]), shared_buffer=st.booleans(), use_bias=st.booleans(), **hu.gcs) def test_convolution_separate_stride_pad_gradients(self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, size, input_channels, output_channels, batch_size, order, engine, shared_buffer, use_bias, gc, dc): op = core.CreateOperator( "Conv", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride_h=stride_h, stride_w=stride_w, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, kernel=kernel, order=order, engine=engine, shared_buffer=int(shared_buffer), ) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( output_channels, kernel, kernel, input_channels).astype(np.float32)\ - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) inputs = [X, w, b] if use_bias else [X, w] # Error handling path. if size + pad_r + pad_l < kernel or size + pad_t + pad_b < kernel: with self.assertRaises(RuntimeError): self.assertDeviceChecks(dc, op, inputs, [0]) return self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [0]) # CUDNN does NOT support different padding values and we skip it @given(stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(1, 5), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), engine=st.sampled_from(["", "EIGEN"]), use_bias=st.booleans(), **hu.gcs) def test_convolution_separate_stride_pad_layout(self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, size, input_channels, output_channels, batch_size, engine, use_bias, gc, dc): X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( output_channels, kernel, kernel, input_channels).astype(np.float32)\ - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 outputs = {} for order in ["NCHW", "NHWC"]: op = core.CreateOperator( "Conv", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride_h=stride_h, stride_w=stride_w, kernel=kernel, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, order=order, engine=engine, device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs[order] = self.ws.blobs["Y"].fetch() np.testing.assert_allclose( outputs["NCHW"], outputs["NHWC"].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), dilation=st.integers(1, 3), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), engine=st.sampled_from(["", "CUDNN", "MKLDNN"]), use_bias=st.booleans(), **hu.gcs) def test_convolution_gradients(self, stride, pad, kernel, dilation, size, input_channels, output_channels, batch_size, order, engine, use_bias, gc, dc): dkernel = dilation * (kernel - 1) + 1 assume("" == engine or 1 == dilation) assume(engine != "MKLDNN" or use_bias is True) op = core.CreateOperator( "Conv", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order=order, engine=engine, ) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( output_channels, kernel, kernel, input_channels).astype(np.float32)\ - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) inputs = [X, w, b] if use_bias else [X, w] # Error handling path. if size + pad + pad < dkernel or size + pad + pad < dkernel: with self.assertRaises(RuntimeError): self.assertDeviceChecks(dc, op, inputs, [0]) return self.assertDeviceChecks(dc, op, inputs, [0]) for i in range(len(inputs)): self.assertGradientChecks(gc, op, inputs, i, [0]) @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), dilation=st.integers(1, 3), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), use_bias=st.booleans(), **hu.gcs) def test_convolution_layout(self, stride, pad, kernel, dilation, size, input_channels, output_channels, batch_size, use_bias, gc, dc): assume(size >= dilation * (kernel - 1) + 1) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( output_channels, kernel, kernel, input_channels).astype(np.float32)\ - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 Output = collections.namedtuple("Output", ["Y", "engine", "order"]) outputs = [] for order in ["NCHW", "NHWC"]: for engine in (["", "CUDNN"] if dilation == 1 else [""]): op = core.CreateOperator( "Conv", ["X", "w", "b"] if use_bias else ["X", "w"], ["Y"], stride=stride, kernel=kernel, dilation=dilation, pad=pad, order=order, engine=engine, device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.assertDeviceChecks( dc, op, [X_f, w_f, b] if use_bias else [X_f, w_f], [0]) self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs.append(Output( Y=self.ws.blobs["Y"].fetch(), engine=engine, order=order)) def canonical(o): if o.order == "NHWC": return o.Y.transpose((0, 3, 1, 2)) else: return o.Y for o in outputs: np.testing.assert_allclose( canonical(outputs[0]), canonical(o), atol=1e-4, rtol=1e-4) @given(num_workers=st.integers(1, 4), net_type=st.sampled_from( ["simple", "dag"] + (["async_dag"] if workspace.has_gpu_support else [])), do=st.sampled_from(hu.device_options), engine=st.sampled_from(["CUDNN", ""])) def test_convolution_sync(self, net_type, num_workers, do, engine): from caffe2.python.cnn import CNNModelHelper m = CNNModelHelper() n = 1 d = 2 depth = 3 iters = 5 h = 5 w = 5 workspace.ResetWorkspace() np.random.seed(1701) # Build a binary tree of conv layers, summing at each node. for i in reversed(range(depth)): for j in range(2 ** i): bottom_1 = "{}_{}".format(i + 1, 2 * j) bottom_2 = "{}_{}".format(i + 1, 2 * j + 1) mid_1 = "{}_{}_m".format(i + 1, 2 * j) mid_2 = "{}_{}_m".format(i + 1, 2 * j + 1) top = "{}_{}".format(i, j) w1, b1, w2, b2 = np.random.randn(4).tolist() m.Conv( bottom_1, mid_1, dim_in=d, dim_out=d, kernel=3, weight_init=m.ConstantInit(w1), bias_init=m.ConstantInit(b1), cudnn_state=np.random.randint(0, 3), stride=1, pad=1, deterministic=1, engine=engine) m.Conv( bottom_2, mid_2, dim_in=d, dim_out=d, kernel=3, stride=1, pad=1, weight_init=m.ConstantInit(w2), bias_init=m.ConstantInit(b2), deterministic=1, cudnn_state=np.random.randint(0, 3), engine=engine) m.net.Sum([mid_1, mid_2], top) m.net.Flatten(["0_0"], ["0_0_flat"]) m.net.SquaredL2Distance(["0_0_flat", "label"], "xent") m.net.AveragedLoss("xent", "loss") input_to_grad = m.AddGradientOperators(["loss"]) m.Proto().device_option.CopyFrom(do) m.param_init_net.Proto().device_option.CopyFrom(do) m.Proto().type = net_type m.Proto().num_workers = num_workers self.ws.run(m.param_init_net) def run(): import numpy as np np.random.seed(1701) input_blobs = ["{}_{}".format(depth, j) for j in range(2 ** depth)] for input_blob in input_blobs: self.ws.create_blob(input_blob).feed( np.random.randn(n, d, h, w).astype(np.float32), device_option=do) self.ws.create_blob("label").feed( np.random.randn(n, d * h * w).astype(np.float32), device_option=do) self.ws.run(m.net) gradients = [ self.ws.blobs[str(input_to_grad[input_blob])].fetch() for input_blob in input_blobs] return gradients outputs = [run() for _ in range(iters)] for output in outputs[1:]: np.testing.assert_array_equal(outputs[0], output) np.testing.assert_allclose( np.sum(np.square(output)), 1763719461732352.0, rtol=1e-5) if __name__ == "__main__": import unittest unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/cnn.py
809
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, scope from caffe2.python.model_helper import ModelHelperBase from caffe2.proto import caffe2_pb2 class CNNModelHelper(ModelHelperBase): """A helper model so we can write CNN models more easily, without having to manually define parameter initializations and operators separately. """ def __init__(self, order="NCHW", name=None, use_cudnn=True, cudnn_exhaustive_search=False, ws_nbytes_limit=None, init_params=True, skip_sparse_optim=False, param_model=None): super(CNNModelHelper, self).__init__( skip_sparse_optim=skip_sparse_optim, name="CNN" if name is None else name, init_params=init_params, param_model=param_model, ) self.weights = [] self.biases = [] self.order = order self.use_cudnn = use_cudnn self.cudnn_exhaustive_search = cudnn_exhaustive_search self.ws_nbytes_limit = ws_nbytes_limit if self.order != "NHWC" and self.order != "NCHW": raise ValueError( "Cannot understand the CNN storage order %s." % self.order ) def GetWeights(self, namescope=None): if namescope is None: namescope = scope.CurrentNameScope() if namescope == '': return self.weights[:] else: return [w for w in self.weights if w.GetNameScope() == namescope] def GetBiases(self, namescope=None): if namescope is None: namescope = scope.CurrentNameScope() if namescope == '': return self.biases[:] else: return [b for b in self.biases if b.GetNameScope() == namescope] def ImageInput( self, blob_in, blob_out, use_gpu_transform=False, **kwargs ): """Image Input.""" if self.order == "NCHW": if (use_gpu_transform): kwargs['use_gpu_transform'] = 1 if use_gpu_transform else 0 # GPU transform will handle NHWC -> NCHW data, label = self.net.ImageInput( blob_in, [blob_out[0], blob_out[1]], **kwargs) # data = self.net.Transform(data, blob_out[0], **kwargs) pass else: data, label = self.net.ImageInput( blob_in, [blob_out[0] + '_nhwc', blob_out[1]], **kwargs) data = self.net.NHWC2NCHW(data, blob_out[0]) else: data, label = self.net.ImageInput( blob_in, blob_out, **kwargs) return data, label def Conv( self, blob_in, blob_out, dim_in, dim_out, kernel, weight_init=None, bias_init=None, group=1, **kwargs ): """Convolution. We intentionally do not provide odd kernel/stride/pad settings in order to discourage the use of odd cases. """ use_bias = False if ("no_bias" in kwargs and kwargs["no_bias"]) else True weight_init = weight_init if weight_init else ('XavierFill', {}) bias_init = bias_init if bias_init else ('ConstantFill', {}) blob_out = blob_out or self.net.NextName() weight_shape = ( [dim_out, int(dim_in / group), kernel, kernel] if self.order == "NCHW" else [dim_out, kernel, kernel, int(dim_in / group)] ) if self.init_params: weight = self.param_init_net.__getattr__(weight_init[0])( [], blob_out + '_w', shape=weight_shape, **weight_init[1] ) if use_bias: bias = self.param_init_net.__getattr__(bias_init[0])( [], blob_out + '_b', shape=[dim_out, ], **bias_init[1] ) else: weight = core.ScopedBlobReference( blob_out + '_w', self.param_init_net) if use_bias: bias = core.ScopedBlobReference( blob_out + '_b', self.param_init_net) if use_bias: self.params.extend([weight, bias]) else: self.params.extend([weight]) self.weights.append(weight) if use_bias: self.biases.append(bias) if self.use_cudnn: kwargs['engine'] = 'CUDNN' kwargs['exhaustive_search'] = self.cudnn_exhaustive_search if self.ws_nbytes_limit: kwargs['ws_nbytes_limit'] = self.ws_nbytes_limit inputs = [] if use_bias: inputs = [blob_in, weight, bias] else: inputs = [blob_in, weight] # For the operator, we no longer need to provide the no_bias field # because it can automatically figure this out from the number of # inputs. if 'no_bias' in kwargs: del kwargs['no_bias'] if group != 1: kwargs['group'] = group return self.net.Conv( inputs, blob_out, kernel=kernel, order=self.order, **kwargs ) def ConvTranspose( self, blob_in, blob_out, dim_in, dim_out, kernel, weight_init=None, bias_init=None, **kwargs ): """ConvTranspose. """ weight_init = weight_init if weight_init else ('XavierFill', {}) bias_init = bias_init if bias_init else ('ConstantFill', {}) blob_out = blob_out or self.net.NextName() weight_shape = ( [dim_in, dim_out, kernel, kernel] if self.order == "NCHW" else [dim_in, kernel, kernel, dim_out] ) if self.init_params: weight = self.param_init_net.__getattr__(weight_init[0])( [], blob_out + '_w', shape=weight_shape, **weight_init[1] ) bias = self.param_init_net.__getattr__(bias_init[0])( [], blob_out + '_b', shape=[dim_out, ], **bias_init[1] ) else: weight = core.ScopedBlobReference( blob_out + '_w', self.param_init_net) bias = core.ScopedBlobReference( blob_out + '_b', self.param_init_net) self.params.extend([weight, bias]) self.weights.append(weight) self.biases.append(bias) if self.use_cudnn: kwargs['engine'] = 'CUDNN' kwargs['exhaustive_search'] = self.cudnn_exhaustive_search if self.ws_nbytes_limit: kwargs['ws_nbytes_limit'] = self.ws_nbytes_limit return self.net.ConvTranspose( [blob_in, weight, bias], blob_out, kernel=kernel, order=self.order, **kwargs ) def GroupConv( self, blob_in, blob_out, dim_in, dim_out, kernel, weight_init=None, bias_init=None, group=1, **kwargs ): """Group Convolution. This is essentially the same as Conv with a group argument passed in. We specialize this for backward interface compatibility. """ return self.Conv(blob_in, blob_out, dim_in, dim_out, kernel, weight_init=weight_init, bias_init=bias_init, group=group, **kwargs) def GroupConv_Deprecated( self, blob_in, blob_out, dim_in, dim_out, kernel, weight_init=None, bias_init=None, group=1, **kwargs ): """GroupConvolution's deprecated interface. This is used to simulate a group convolution via split and concat. You should always use the new group convolution in your new code. """ weight_init = weight_init if weight_init else ('XavierFill', {}) bias_init = bias_init if bias_init else ('ConstantFill', {}) use_bias = False if ("no_bias" in kwargs and kwargs["no_bias"]) else True if self.use_cudnn: kwargs['engine'] = 'CUDNN' kwargs['exhaustive_search'] = self.cudnn_exhaustive_search if self.ws_nbytes_limit: kwargs['ws_nbytes_limit'] = self.ws_nbytes_limit if dim_in % group: raise ValueError("dim_in should be divisible by group.") if dim_out % group: raise ValueError("dim_out should be divisible by group.") splitted_blobs = self.net.DepthSplit( blob_in, ['_' + blob_out + '_gconv_split_' + str(i) for i in range(group)], dimensions=[int(dim_in / group) for i in range(group)], order=self.order ) weight_shape = ( [dim_out / group, dim_in / group, kernel, kernel] if self.order == "NCHW" else [dim_out / group, kernel, kernel, dim_in / group] ) # Make sure that the shapes are of int format. Especially for py3 where # int division gives float output. weight_shape = [int(v) for v in weight_shape] conv_blobs = [] for i in range(group): if self.init_params: weight = self.param_init_net.__getattr__(weight_init[0])( [], blob_out + '_gconv_%d_w' % i, shape=weight_shape, **weight_init[1] ) if use_bias: bias = self.param_init_net.__getattr__(bias_init[0])( [], blob_out + '_gconv_%d_b' % i, shape=[int(dim_out / group)], **bias_init[1] ) else: weight = core.ScopedBlobReference( blob_out + '_gconv_%d_w' % i, self.param_init_net) if use_bias: bias = core.ScopedBlobReference( blob_out + '_gconv_%d_b' % i, self.param_init_net) if use_bias: self.params.extend([weight, bias]) else: self.params.extend([weight]) self.weights.append(weight) if use_bias: self.biases.append(bias) if use_bias: inputs = [weight, bias] else: inputs = [weight] if 'no_bias' in kwargs: del kwargs['no_bias'] conv_blobs.append( splitted_blobs[i].Conv( inputs, blob_out + '_gconv_%d' % i, kernel=kernel, order=self.order, **kwargs ) ) concat, concat_dims = self.net.Concat( conv_blobs, [blob_out, "_" + blob_out + "_concat_dims"], order=self.order ) return concat def _FC_or_packed_FC( self, op_call, blob_in, blob_out, dim_in, dim_out, weight_init=None, bias_init=None, **kwargs ): """FC""" weight_init = weight_init if weight_init else ('XavierFill', {}) bias_init = bias_init if bias_init else ('ConstantFill', {}) blob_out = blob_out or self.net.NextName() if self.init_params: weight = self.param_init_net.__getattr__(weight_init[0])( [], blob_out + '_w', shape=[dim_out, dim_in], **weight_init[1] ) bias = self.param_init_net.__getattr__(bias_init[0])( [], blob_out + '_b', shape=[dim_out, ], **bias_init[1] ) else: weight = core.ScopedBlobReference( blob_out + '_w', self.param_init_net) bias = core.ScopedBlobReference( blob_out + '_b', self.param_init_net) if 'freeze_bias' in kwargs: self.params.extend([weight]) else: self.params.extend([weight, bias]) self.weights.append(weight) self.biases.append(bias) return op_call([blob_in, weight, bias], blob_out, **kwargs) def FC(self, *args, **kwargs): return self._FC_or_packed_FC(self.net.FC, *args, **kwargs) def PackedFC(self, *args, **kwargs): return self._FC_or_packed_FC(self.net.PackedFC, *args, **kwargs) def FC_Decomp( self, blob_in, blob_out, dim_in, dim_out, rank_approx=5, weight_init=None, bias_init=None, **kwargs ): """FC_Decomp version Here we assume that the rank of original input is bigger than 5. """ weight_init = weight_init if weight_init else ('XavierFill', {}) bias_init = bias_init if bias_init else ('ConstantFill', {}) blob_out = blob_out or self.net.NextName() u = self.param_init_net.__getattr__(weight_init[0])( [], blob_out + '_u', shape=[dim_out, rank_approx], **weight_init[1] ) v = self.param_init_net.__getattr__(weight_init[0])( [], blob_out + '_v', shape=[dim_in, rank_approx], **weight_init[1] ) bias = self.param_init_net.__getattr__(bias_init[0])( [], blob_out + '_b', shape=[dim_out, ], **bias_init[1] ) self.params.extend([u, v, bias]) return self.net.FC_Decomp([blob_in, u, v, bias], blob_out, **kwargs) def FC_Prune( self, blob_in, blob_out, dim_in, dim_out, weight_init=None, bias_init=None, mask_init=None, threshold=0.00001, need_compress_rate=False, comp_lb=0.05, **kwargs ): """FC_Prune version Runnable so far. Great!:) """ weight_init = weight_init if weight_init else ('XavierFill', {}) bias_init = bias_init if bias_init else ('ConstantFill', {}) mask_init = mask_init if mask_init else ('ConstantFill', {}) blob_out = blob_out or self.net.NextName() compress_rate = blob_out + '_compress_rate' if self.init_params: compress_lb = self.param_init_net.ConstantFill( [], blob_out + '_lb', shape=[1], value=comp_lb ) weight = self.param_init_net.__getattr__(weight_init[0])( [], blob_out + '_w', shape=[dim_out, dim_in], **weight_init[1] ) mask = self.param_init_net.ConstantFill( [], blob_out + '_m', shape=[dim_out, dim_in], value=1.0 ) ag_dw = self.param_init_net.__getattr__(mask_init[0])( [], blob_out + '_ag_dw', shape=[dim_out, dim_in], **mask_init[1] ) bias = self.param_init_net.__getattr__(bias_init[0])( [], blob_out + '_b', shape=[dim_out, ], **bias_init[1] ) mask_seq = self.param_init_net.__getattr__(mask_init[0])( [], blob_out + '_mask_seq', shape=[dim_out, dim_in], **mask_init[1] ) thres = self.param_init_net.ConstantFill( [], blob_out + '_thres', shape=[1], value=threshold ) else: compress_lb = core.ScopedBlobReference( blob_out + '_lb', self.param_init_net) weight = core.ScopedBlobReference( blob_out + '_w', self.param_init_net) bias = core.ScopedBlobReference( blob_out + '_b', self.param_init_net) mask = core.ScopedBlobReference( blob_out + '_m', self.param_init_net) ag_dw = core.ScopedBlobReference( blob_out + '_ag_dw', self.param_init_net) mask_seq = core.ScopedBlobReference( blob_out + '_mask_seq', self.param_init_net) thres = core.ScopedBlobReference( blob_out + '_thres', self.param_init_net) self.params.extend([weight, bias]) if need_compress_rate: return self.net.FC_Prune([blob_in, weight, mask, bias, ag_dw, mask_seq, thres, compress_lb], [blob_out, compress_rate], **kwargs) else: return self.net.FC_Prune([blob_in, weight, mask, bias, ag_dw, mask_seq, thres, compress_lb], blob_out, **kwargs) def FC_Sparse( self, blob_in, blob_out, w_csr, iw, jw, bias, **kwargs ): """FC_Sparse: Only takes in alocated weights""" if not (w_csr and iw and jw and bias): print("Warning...") self.params.extend([w_csr, iw, jw, bias]) return self.net.FC_Sparse([blob_in, w_csr, iw, jw, bias], blob_out, **kwargs) def LRN(self, blob_in, blob_out, **kwargs): """LRN""" return self.net.LRN( blob_in, [blob_out, "_" + blob_out + "_scale"], order=self.order, **kwargs )[0] def Dropout(self, blob_in, blob_out, **kwargs): """Dropout""" return self.net.Dropout( blob_in, [blob_out, "_" + blob_out + "_mask"], **kwargs )[0] def MaxPool(self, blob_in, blob_out, **kwargs): """Max pooling""" if self.use_cudnn: kwargs['engine'] = 'CUDNN' return self.net.MaxPool(blob_in, blob_out, order=self.order, **kwargs) def AveragePool(self, blob_in, blob_out, **kwargs): """Average pooling""" if self.use_cudnn: kwargs['engine'] = 'CUDNN' return self.net.AveragePool( blob_in, blob_out, order=self.order, **kwargs ) def Concat(self, blobs_in, blob_out, **kwargs): """Depth Concat.""" return self.net.Concat( blobs_in, [blob_out, "_" + blob_out + "_concat_dims"], order=self.order, **kwargs )[0] def DepthConcat(self, blobs_in, blob_out, **kwargs): """The old depth concat function - we should move to use concat.""" print("DepthConcat is deprecated. use Concat instead.") return self.Concat(blobs_in, blob_out, **kwargs) def PRelu(self, blob_in, blob_out, num_channels=1, slope_init=None, **kwargs): """PRelu""" slope_init = ( slope_init if slope_init else ('ConstantFill', {'value': 0.25})) if self.init_params: slope = self.param_init_net.__getattr__(slope_init[0])( [], blob_out + '_slope', shape=[num_channels], **slope_init[1] ) else: slope = core.ScopedBlobReference( blob_out + '_slope', self.param_init_net) self.params.extend([slope]) return self.net.PRelu([blob_in, slope], [blob_out]) def Relu(self, blob_in, blob_out, **kwargs): """Relu.""" if self.use_cudnn: kwargs['engine'] = 'CUDNN' return self.net.Relu(blob_in, blob_out, order=self.order, **kwargs) def Transpose(self, blob_in, blob_out, **kwargs): """Transpose.""" return self.net.Transpose(blob_in, blob_out, **kwargs) def Sum(self, blob_in, blob_out, **kwargs): """Sum""" return self.net.Sum(blob_in, blob_out, **kwargs) def InstanceNorm(self, blob_in, blob_out, dim_in, **kwargs): blob_out = blob_out or self.net.NextName() # Input: input, scale, bias # Output: output, saved_mean, saved_inv_std # scale: initialize with ones # bias: initialize with zeros def init_blob(value, suffix): return self.param_init_net.ConstantFill( [], blob_out + "_" + suffix, shape=[dim_in], value=value) scale, bias = init_blob(1.0, "s"), init_blob(0.0, "b") self.params.extend([scale, bias]) self.weights.append(scale) self.biases.append(bias) blob_outs = [blob_out, blob_out + "_sm", blob_out + "_siv"] if 'is_test' in kwargs and kwargs['is_test']: blob_outputs = self.net.InstanceNorm( [blob_in, scale, bias], [blob_out], order=self.order, **kwargs) return blob_outputs else: blob_outputs = self.net.InstanceNorm( [blob_in, scale, bias], blob_outs, order=self.order, **kwargs) # Return the output return blob_outputs[0] def SpatialBN(self, blob_in, blob_out, dim_in, **kwargs): blob_out = blob_out or self.net.NextName() # Input: input, scale, bias, est_mean, est_inv_var # Output: output, running_mean, running_inv_var, saved_mean, # saved_inv_var # scale: initialize with ones # bias: initialize with zeros # est mean: zero # est var: ones def init_blob(value, suffix): return self.param_init_net.ConstantFill( [], blob_out + "_" + suffix, shape=[dim_in], value=value) scale, bias = init_blob(1.0, "s"), init_blob(0.0, "b") running_mean = init_blob(0.0, "rm") running_inv_var = init_blob(1.0, "riv") self.params.extend([scale, bias]) self.computed_params.extend([running_mean, running_inv_var]) self.weights.append(scale) self.biases.append(bias) blob_outs = [blob_out, running_mean, running_inv_var, blob_out + "_sm", blob_out + "_siv"] if 'is_test' in kwargs and kwargs['is_test']: blob_outputs = self.net.SpatialBN( [blob_in, scale, bias, blob_outs[1], blob_outs[2]], [blob_out], order=self.order, **kwargs) return blob_outputs else: blob_outputs = self.net.SpatialBN( [blob_in, scale, bias, blob_outs[1], blob_outs[2]], blob_outs, order=self.order, **kwargs) # Return the output return blob_outputs[0] def Iter(self, blob_out, **kwargs): if 'device_option' in kwargs: del kwargs['device_option'] self.param_init_net.ConstantFill( [], blob_out, shape=[1], value=0, dtype=core.DataType.INT64, device_option=core.DeviceOption(caffe2_pb2.CPU, 0), **kwargs) return self.net.Iter(blob_out, blob_out, **kwargs) def Accuracy(self, blob_in, blob_out, **kwargs): dev = kwargs['device_option'] if 'device_option' in kwargs else scope.CurrentDeviceScope() blobs_in_dev = [] # if device_option is CPU (or None, so assumed to be CPU), nothing needs to be done if dev == None or dev.device_type == caffe2_pb2.CPU: blobs_in_dev = blob_in else: # Otherwise insert copy operators pred_host = self.net.CopyGPUToCPU(blob_in[0], blob_in[0]+"_host") label_host = self.net.CopyGPUToCPU(blob_in[1], blob_in[1]+"_host") blobs_in_dev = [pred_host, label_host] # Now use the Host version of the accuracy op self.net.Accuracy(blobs_in_dev, blob_out, device_option=core.DeviceOption(caffe2_pb2.CPU, 0), **kwargs) @property def XavierInit(self): return ('XavierFill', {}) def ConstantInit(self, value): return ('ConstantFill', dict(value=value)) @property def MSRAInit(self): return ('MSRAFill', {}) @property def ZeroInit(self): return ('ConstantFill', {}) def AddWeightDecay(self, weight_decay): """Adds a decay to weights in the model. This is a form of L2 regularization. Args: weight_decay: strength of the regularization """ if weight_decay <= 0.0: return wd = self.param_init_net.ConstantFill([], 'wd', shape=[1], value=weight_decay) ONE = self.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0) for param in self.GetWeights(): # Equivalent to: grad += wd * param grad = self.param_to_grad[param] self.net.WeightedSum( [grad, ONE, param, wd], grad, ) @property def CPU(self): device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CPU return device_option @property def GPU(self, gpu_id=0): device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CUDA device_option.cuda_gpu_id = gpu_id return device_option def LSTM(self, input_blob, seq_lengths, initial_states, dim_in, dim_out, scope=None): def s(name): # We have to manually scope due to our internal/external blob # relationships. scope_name = scope or str(input_blob) return "{}/{}".format(str(scope_name), str(name)) (hidden_input_blob, cell_input_blob) = initial_states input_blob = self.FC(input_blob, s("i2h"), dim_in=dim_in, dim_out=4 * dim_out, axis=2) step_net = CNNModelHelper(name="LSTM") step_net.Proto().external_input.extend([ str(seq_lengths), "input_t", "timestep", "hidden_t_prev", "cell_t_prev", s("gates_t_w"), s("gates_t_b"), ]) step_net.Proto().type = "simple" step_net.Proto().external_output.extend( ["hidden_t", "cell_t", s("gates_t")]) step_net.FC("hidden_t_prev", s("gates_t"), dim_in=dim_out, dim_out=4 * dim_out, axis=2) step_net.net.Sum([s("gates_t"), "input_t"], [s("gates_t")]) step_net.net.LSTMUnit( ["cell_t_prev", s("gates_t"), str(seq_lengths), "timestep"], ["hidden_t", "cell_t"]) links = [ ("hidden_t_prev", s("hidden"), 0), ("hidden_t", s("hidden"), 1), ("cell_t_prev", s("cell"), 0), ("cell_t", s("cell"), 1), ("input_t", str(input_blob), 0), ] link_internal, link_external, link_offset = zip(*links) # # Initialize params for step net in the parent net # for op in step_net.param_init_net.Proto().op: # Set up the backward links backward_ops, backward_mapping = core.GradientRegistry.GetBackwardPass( step_net.Proto().op, {"hidden_t": "hidden_t_grad", "cell_t": "cell_t_grad"}) backward_mapping = {str(k): str(v) for k, v in backward_mapping.items()} backward_step_net = core.Net("LSTMBackward") del backward_step_net.Proto().op[:] backward_step_net.Proto().op.extend(backward_ops) backward_links = [ ("hidden_t_prev_grad", s("hidden_grad"), 0), ("hidden_t_grad", s("hidden_grad"), 1), ("cell_t_prev_grad", s("cell_grad"), 0), ("cell_t_grad", s("cell_grad"), 1), (s("gates_t_grad"), str(input_blob) + "_grad", 0), ] backward_link_internal, backward_link_external, \ backward_link_offset = zip(*backward_links) backward_step_net.Proto().external_input.extend( ["hidden_t_grad", "cell_t_grad"]) backward_step_net.Proto().external_input.extend( step_net.Proto().external_input) backward_step_net.Proto().external_input.extend( step_net.Proto().external_output) inputs = map(str, [input_blob, seq_lengths, s("gates_t_w"), s("gates_t_b"), hidden_input_blob, cell_input_blob]) recurrent_inputs = [str(hidden_input_blob), str(cell_input_blob)] output, _, _, hidden_state, cell_state, _ = self.net.RecurrentNetwork( inputs, [s("output"), s("hidden"), s("cell"), s("hidden_output"), s("cell_output"), s("step_workspaces")], param=map(inputs.index, step_net.params), alias_src=[s("hidden"), s("hidden"), s("cell")], alias_dst=[s("output"), s("hidden_output"), s("cell_output")], alias_offset=[1, -1, -1], recurrent_states=[s("hidden"), s("cell")], recurrent_inputs=recurrent_inputs, recurrent_input_ids=map(inputs.index, recurrent_inputs), link_internal=link_internal, link_external=link_external, link_offset=link_offset, backward_link_internal=backward_link_internal, backward_link_external=backward_link_external, backward_link_offset=backward_link_offset, step_net=str(step_net.Proto()), backward_step_net=str(backward_step_net.Proto()), timestep="timestep") self.param_init_net.Proto().op.extend( step_net.param_init_net.Proto().op) self.params += step_net.params for p in step_net.params: if str(p) in backward_mapping: self.param_to_grad[p] = backward_mapping[str(p)] self.weights += step_net.weights self.biases += step_net.biases return output, hidden_state, cell_state
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/dataset.py
315
""" Implementation of an in-memory dataset with structured schema. Use this to store and iterate through datasets with complex schema that fit in memory. Iterating through entries of this dataset is very fast since the dataset is stored as a set of native Caffe2 tensors, thus no type conversion or deserialization is necessary. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from caffe2.python.dataio import Reader, Writer from caffe2.python.schema import ( Struct, from_blob_list, Field, from_column_list, InitEmptyRecord) import numpy as np class _DatasetReader(Reader): def __init__(self, dataset, name, batch_size=1): """Don't call this directly. Instead, use dataset.reader()""" Reader.__init__(self, dataset.content()) self.dataset = dataset self.name = name or (dataset.name + '_cursor') self.batch_size = batch_size self.cursor = None def setup_ex(self, init_net, exit_net): if self.cursor is None: self.cursor = init_net.CreateTreeCursor( [], [self.name], fields=self.dataset.fields) def read(self, read_net): assert self.cursor, 'setup not called.' content = self.dataset.content() with core.NameScope(read_net.NextName(self.name)): fields = read_net.ReadNextBatch( [self.cursor] + content.field_blobs(), content.field_names(), batch_size=self.batch_size) if type(fields) is core.BlobReference: fields = [fields] return (read_net.IsEmpty([fields[0]]), fields) def reset(self, net): net.ResetCursor([self.cursor], []) class _DatasetRandomReader(Reader): def __init__(self, dataset, name, indices, batch_size=1): """Don't call this directly. Instead, use dataset.random_reader()""" Reader.__init__(self, dataset.content()) self.dataset = dataset self.cursor = None self.name = name or (dataset.name + '_cursor') self.indices = indices self.batch_size = batch_size def setup_ex(self, init_net, exit_net): if self.cursor is None: self.cursor = init_net.CreateTreeCursor( [], [self.name], fields=self.dataset.fields) def reset(self, net): net.ResetCursor([self.cursor], []) def computeoffset(self, net): self.reset(net) offsets = net.ComputeOffset( [self.cursor] + self.dataset.content().field_blobs(), 'offsets') self.offsets = offsets def sort_and_shuffle(self, net, sort_by_field=None, shuffle_size=1, batch_size=1): # no sorting by default content = self.dataset.content() sort_by_field_idx = -1 if sort_by_field: assert sort_by_field in content.field_names(), ( 'Must be valid field.') sort_by_field_idx = content.field_names().index(sort_by_field) self.reset(net) indices = net.SortAndShuffle( [self.cursor] + content.field_blobs(), 'indices', sort_by_field_idx=sort_by_field_idx, shuffle_size=shuffle_size, batch_size=batch_size) self.indices = indices def read(self, read_net): with core.NameScope(read_net.NextName(self.name)): fields = read_net.ReadRandomBatch( [self.cursor, self.indices, self.offsets] + ( self.dataset.content().field_blobs()), self.dataset.content().field_names(), batch_size=self.batch_size) return (read_net.IsEmpty([fields[0]]), fields) class _DatasetWriter(Writer): def __init__(self, content): """Don't call this directly. Use dataset.writer() instead.""" self._content = content self.mutex = None def setup_ex(self, init_net, exit_net): if self.mutex is None: self.mutex = init_net.CreateMutex([]) def write(self, writer_net, fields): """ Add operations to `net` that append the blobs in `fields` to the end of the dataset. An additional operator will also be added that checks the consistency of the data in `fields` against the dataset schema. Args: writer_net: The net that will contain the Append operators. fields: A list of BlobReference to be appeneded to this dataset. """ assert self.mutex is not None, 'setup not called.' field_blobs = self._content.field_blobs() assert len(fields) == len(field_blobs), ( 'Expected %s fields, got %s.' % (len(field_blobs), len(fields))) writer_net.CheckDatasetConsistency( fields, [], fields=self._content.field_names()) writer_net.AtomicAppend( [self.mutex] + field_blobs + list(fields), field_blobs) def commit(self, finish_net): """Commit is a no-op for an in-memory dataset.""" pass def Const(net, value, dtype=None, name=None): """ Create a 'constant' by first creating an external input in the given net, and then feeding the corresponding blob with its provided value in the current workspace. The name is automatically generated in order to avoid clashes with existing blob names. """ assert isinstance(net, core.Net), 'net must be a core.Net instance.' value = np.array(value, dtype=dtype) blob = net.AddExternalInput(net.NextName(prefix=name)) workspace.FeedBlob(str(blob), value) return blob def execution_step_with_progress(name, init_net, substeps, rows_read): # progress reporter report_net = core.Net('report_net') report_net.Print([rows_read], []) return core.execution_step( name, substeps, report_net=report_net, concurrent_substeps=True, report_interval=5) class Dataset(object): """Represents an in-memory dataset with fixed schema. Use this to store and iterate through datasets with complex schema that fit in memory. Iterating through entries of this dataset is very fast since the dataset is stored as a set of native Caffe2 tensors, thus no type conversion or deserialization is necessary. """ def __init__(self, fields, name=None): """Create an un-initialized dataset with schema provided by `fields`. Before this dataset can be used, it must be initialized, either by `init_empty` or `init_from_dataframe`. Args: fields: either a schema.Struct or a list of field names in a format compatible with the one described in schema.py. name: optional name to prepend to blobs that will store the data. """ assert isinstance(fields, list) or isinstance(fields, Struct), ( 'fields must be either a Struct or a list of raw field names.') if isinstance(fields, list): fields = from_column_list(fields) self.schema = fields self.fields = fields.field_names() self.field_types = fields.field_types() self.name = name or 'dataset' self.field_blobs = fields.field_blobs() if fields.has_blobs() else None def init_empty(self, init_net): """Initialize the blobs for this dataset with empty values. Empty arrays will be immediately fed into the current workspace, and `init_net` will take those blobs as external inputs. """ self.field_blobs = InitEmptyRecord( init_net, self.schema.clone_schema()).field_blobs() def init_from_dataframe(self, net, dataframe): """Initialize the blobs for this dataset from a Pandas dataframe. Each column of the dataframe will be immediately fed into the current workspace, and the `net` will take this blobs as external inputs. """ assert len(self.fields) == len(dataframe.columns) self.field_blobs = [ Const(net, dataframe.as_matrix([col]).flatten(), name=field) for col, field in enumerate(self.fields)] def get_blobs(self): """ Return the list of BlobReference pointing to the blobs that contain the data for this dataset. """ assert self return self.field_blobs def content(self): """ Return a Record of BlobReferences pointing to the full content of this dataset. """ return from_blob_list(self.schema, self.field_blobs) def field_names(self): """Return the list of field names for this dataset.""" return self.fields def field_types(self): """ Return the list of field dtypes for this dataset. If a list of strings, not a schema.Struct, was passed to the constructor, this will return a list of dtype(np.void). """ return self.field_types def reader(self, init_net=None, cursor_name=None, batch_size=1): """Create a Reader object that is used to iterate through the dataset. This will append operations to `init_net` that create a TreeCursor, used to iterate through the data. NOTE: Currently, it is not safe to append to a dataset while reading. Args: init_net: net that will be run once to create the cursor. cursor_name: optional name for the blob containing a pointer to the cursor. batch_size: how many samples to read per iteration. Returns: A _DatasetReader that can be used to create operators that will iterate through the dataset. """ assert self.field_blobs, 'Dataset not initialized.' reader = _DatasetReader(self, cursor_name, batch_size) if init_net is not None: reader.setup_ex(init_net, None) return reader def random_reader(self, init_net=None, indices=None, cursor_name=None, batch_size=1): """Create a Reader object that is used to iterate through the dataset. NOTE: The reader order depends on the order in indices. Args: init_net: net that will be run once to create the cursor. indices: blob of reading order cursor_name: optional name for the blob containing a pointer to the cursor. batch_size: how many samples to read per iteration. Returns: A DatasetReader that can be used to create operators that will iterate through the dataset according to indices. """ assert self.field_blobs, 'Dataset not initialized.' reader = _DatasetRandomReader(self, cursor_name, indices, batch_size) if init_net is not None: reader.setup_ex(init_net, None) return reader def writer(self, init_net=None): """Create a Writer that can be used to append entries into the dataset. NOTE: Currently, it is not safe to append to a dataset while reading from it. NOTE: Currently implementation of writer is not thread safe. TODO: fixme Args: init_net: net that will be run once in order to create the writer. (currently not used) """ assert self.field_blobs, 'Dataset not initialized.' writer = _DatasetWriter(self.content()) if init_net is not None: writer.setup_ex(init_net, None) return writer
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/core.py
1,909
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from collections import namedtuple from collections import OrderedDict from caffe2.proto import caffe2_pb2 from collections import defaultdict from caffe2.python import scope, utils, workspace import numpy as np import caffe2.python._import_c_extension as C # Convenience redirections to functions inside scope. DeviceScope = scope.DeviceScope NameScope = scope.NameScope # Bring datatype enums to the main namespace class DataType: pass def _InitDataType(): for name, value in caffe2_pb2.TensorProto.DataType.items(): setattr(DataType, name, value) _InitDataType() # Python 2 and 3 compatibility: test if basestring exists try: basestring = basestring # NOQA except NameError: # This is python3 so we define basestring. basestring = str def _GetRegisteredOperators(): return set(s.decode() for s in workspace.RegisteredOperators()) _REGISTERED_OPERATORS = _GetRegisteredOperators() def RefreshRegisteredOperators(): global _REGISTERED_OPERATORS _REGISTERED_OPERATORS = _GetRegisteredOperators() _GLOBAL_INIT_ARGS = [] def GlobalInit(args): _GLOBAL_INIT_ARGS.extend(args[1:]) C.global_init(args) def GetGlobalInitArgs(): return _GLOBAL_INIT_ARGS[:] def IsOperator(op_type): return (op_type in _REGISTERED_OPERATORS) def IsOperatorWithEngine(op_type, engine): return (op_type + "_ENGINE_" + engine in _REGISTERED_OPERATORS) def DeviceOption(device_type, cuda_gpu_id=0, random_seed=None): option = caffe2_pb2.DeviceOption() option.device_type = device_type option.cuda_gpu_id = cuda_gpu_id if random_seed is not None: option.random_seed = random_seed return option GradientSlice = namedtuple('GradientSlice', ['indices', 'values']) class BlobReference(object): """A wrapper around a blob in a net. BlobReference gives us a way to refer to the network that the blob is generated from. Note that blobs are, essentially, just strings in the current workspace. """ def __init__(self, name, net=None): """Initializes a blob reference. Note that this does not prepends the namescope. If needed, use ScopedBlobReference() to prepend the existing namespace. """ self._name = name self._from_net = net # meta allows helper functions to put whatever metainformation needed # there. self.meta = {} def __hash__(self): return hash(self._name) def __eq__(self, other): if isinstance(other, basestring): return self._name == other elif isinstance(other, BlobReference): return self._name == other._name else: return False def __ne__(self, other): return not(self == other) def __str__(self): return self._name def __repr__(self): return 'BlobReference("{}")'.format(self._name) def __add__(self, other): if not isinstance(other, basestring): raise RuntimeError('Cannot add BlobReference to a non-string.') return BlobReference(self._name + other, self._from_net) def __radd__(self, other): if not isinstance(other, basestring): raise RuntimeError('Cannot add a non-string to BlobReference.') return BlobReference(other + self._name, self._from_net) def Net(self): return self._from_net def GetNameScope(self): return self._name[:self._name.rfind(scope._NAMESCOPE_SEPARATOR) + 1] def _CreateAndAddToNet(self, op_type, inputs=None, *args, **kwargs): """Internal function that routes the operator generation to the network's __getattr__ function. """ inputs = [] if inputs is None else inputs if isinstance(inputs, BlobReference) or isinstance(inputs, str): inputs = [inputs] # add self to the input list. inputs.insert(0, self) return self._from_net.__getattr__(op_type)(inputs, *args, **kwargs) def __getattr__(self, op_type): """A wrapper allowing one to initiate operators from a blob reference. Example: for a blob reference b that comes from network n, doing b.Relu(...) is equivalent to doing net.Relu([b], ...) """ if op_type.startswith('__'): raise AttributeError('Attribute {} not found.'.format(op_type)) if self._from_net is None: raise RuntimeError( 'You cannot use a blob reference that does not have a net ' 'source to create operators. Create the operator from an ' 'explicit net object.') if not IsOperator(op_type): raise RuntimeError( 'Method ' + op_type + ' is not a registered operator.' ) return lambda *args, **kwargs: self._CreateAndAddToNet( op_type, *args, **kwargs) def ScopedName(name): """prefix the name with the current scope.""" return scope.CurrentNameScope() + name def ScopedBlobReference(name, *args, **kwargs): """Returns a blob reference with scope prefixed.""" return BlobReference(ScopedName(name), *args, **kwargs) def _RectifyInputOutput(blobs, net=None): """A helper function to rectify the input or output of the CreateOperator interface. """ if isinstance(blobs, basestring): # If blobs is a single string, prepend scope.CurrentNameScope() # and put it as a list. # TODO(jiayq): enforce using BlobReference instead of raw strings. return [ScopedBlobReference(blobs, net=net)] elif type(blobs) is BlobReference: # If blob is a BlobReference, simply put it as a list. return [blobs] elif type(blobs) in (list, tuple): # If blob is a list, we go through it and type check. rectified = [] for blob in blobs: if isinstance(blob, basestring): rectified.append(ScopedBlobReference(blob, net=net)) elif type(blob) is BlobReference: rectified.append(blob) else: raise TypeError( "I/O blob #{} of unsupported type: {} of type {}" .format(len(rectified), str(blob), type(blob))) return rectified else: raise TypeError( "Unknown input/output type: %s of type %s." % (str(blobs), type(blobs)) ) def CreateOperator( operator_type, inputs, outputs, name='', control_input=None, device_option=None, arg=None, engine=None, **kwargs ): """A function wrapper that allows one to create operators based on the operator type. The type should be a string corresponding to an operator registered with Caffe2. """ operator = caffe2_pb2.OperatorDef() operator.type = operator_type operator.name = name # Add rectified inputs and outputs inputs = _RectifyInputOutput(inputs) outputs = _RectifyInputOutput(outputs) operator.input.extend([str(i) for i in inputs]) operator.output.extend([str(o) for o in outputs]) if control_input: control_input = _RectifyInputOutput(control_input) operator.control_input.extend([str(i) for i in control_input]) # Set device option: # (1) If device_option is explicitly set, use device_option. # (2) If not, but scope.CurrentDeviceScope() is set, # then we use scope.CurrentDeviceScope(). # (3) Otherwise, do not set device option. if device_option is not None: operator.device_option.CopyFrom(device_option) elif scope.CurrentDeviceScope() is not None: operator.device_option.CopyFrom(scope.CurrentDeviceScope()) if engine is not None: operator.engine = engine # random seed is defined in the device option, so we need to do special # care. if 'random_seed' in kwargs: operator.device_option.random_seed = kwargs['random_seed'] del kwargs['random_seed'] # Add given arguments that do not need parsing if arg is not None: operator.arg.extend(arg) # Add all other arguments for key, value in kwargs.items(): operator.arg.add().CopyFrom(utils.MakeArgument(key, value)) if workspace.IsImmediate(): workspace.RunOperatorImmediate(operator) return operator def _RegisterPythonImpl(f, grad_f=None, pass_workspace=False): token = C.register_python_op(f, pass_workspace) if grad_f: C.register_python_gradient_op(token, grad_f) return token def CreatePythonOperator( f, inputs, outputs, grad_f=None, pass_workspace=False, *args, **kwargs ): """ `f` should have a signature (inputs, outputs) If `pass_workspace` is True, the signature is changed to (inputs, outputs, workspace) where `workspace` is the workspace the op is going to run on. This is potentially dangerous (as the op can manipulate the workspace directly), use on your own risk. """ kwargs["token"] = _RegisterPythonImpl( f, grad_f, pass_workspace=pass_workspace ) return CreateOperator("Python", inputs, outputs, *args, **kwargs) def GetIndexFromGradientList(g_list, name): """A helper function to get the index from a gradient list, None if not matching.""" for i, g in enumerate(g_list): if g == name: return i elif type(g) is GradientSlice: if (g.indices == name or g.values == name): return i return None OpSSA = namedtuple('OpSSA', ['op', 'in_versions', 'out_versions']) GradGenMeta = namedtuple('GradGenMeta', ['grad_op', 'idx', 'gradient']) SparseGradGenMeta = namedtuple('SparseGradGenMeta', [ 'grad_op_indices', 'idx_indices', 'grad_op_values', 'idx_values', 'gradient', ]) class IR(object): """A simple IR class to keep track of all intermediate representations used in the gradient computation. """ def __init__(self, operators): # The IR class holds multiple metadata from the forward pass: # a) ssa: a list of [op, in_versions, out_versions] recording the # input and the output version of each operator, similar # to a normal SSA form. # b) input_count: a dictionary specifying for each blob and # each of its version, how many times it is used as input for another # op. # c) frontier: maintaining the current versions of the blobs # we are having in the workspace, after the execution of all the ops # added to the IR so far. This is useful because if a gradient is # trying to access an earlier version of a blob, we can sanity check # that it is no longer there, and thus throw an error. # d) gradient_frontier: maps the names of blobs to its version that the # gradient corresponds to. # e) gradient_generators: for each blob and each of its version, maps to # a list of operators that generates its gradient together with the # gradient name. self.ssa = [] self.input_usages = defaultdict(lambda: defaultdict(list)) self.frontier = defaultdict(int) self.gradient_frontier = {} self.gradient_generators = defaultdict(lambda: defaultdict(list)) for op in operators: self.Play(op) def Play(self, op): """"Adds an op to the current IR, and update the internal states to reflect the blobs and versions after the execution of the op. """ # For input, they are the current version in the dict. in_versions = {} for s in op.input: in_versions[s] = self.frontier[s] self.input_usages[s][self.frontier[s]].append(len(self.ssa)) # For output, they are the current version plus one. If this is a # newly created blob, its version starts with zero. out_versions = {} for s in op.output: if s in self.frontier: self.frontier[s] += 1 out_versions[s] = self.frontier[s] # Add to SSA for bookkeeping. self.ssa.append(OpSSA(op, in_versions, out_versions)) def CheckGradientOperatorInput( self, grad_op_input, g_output, fwd_op_idx, locally_generated_blobs): """Checks if the gradient operators can be correctly carried out.""" forward_op, in_versions, out_versions = self.ssa[fwd_op_idx] original_index = GetIndexFromGradientList(g_output, grad_op_input) # If it is a dense or sparse gradient name, it should match the # version of the corresponding output. if original_index is not None: original_name = forward_op.output[original_index] if (out_versions[original_name] != self.gradient_frontier[original_name]): raise RuntimeError( 'Gradient name "%s" is expected to correspond ' 'to version %d of "%s", but currently we have ' 'version %d.' % ( grad_op_input, out_versions[original_name], original_name, self.gradient_frontier[original_name])) # If it is an output name, the current version should match the # version when the operator was run. elif grad_op_input in out_versions: if self.frontier[grad_op_input] != out_versions[grad_op_input]: raise RuntimeError( 'Gradient operator needs output "%s" at version' ' %d, but currently we have version %d.' % ( grad_op_input, out_versions[grad_op_input], self.frontier[grad_op_input] ) ) # If it is an input name, the current version should match the # version when the operator was run. elif grad_op_input in in_versions: if (self.frontier[grad_op_input] != in_versions[grad_op_input]): raise RuntimeError( 'Gradient operator needs input "%s" at version ' '%d, but currently we have version %d.' % ( grad_op_input, in_versions[grad_op_input], self.frontier[grad_op_input] ) ) # If it is none of the above, it should be a blob that is # generated locally by one of the previous gradient operators. else: if grad_op_input not in locally_generated_blobs: raise RuntimeError( 'Blob name "%s" not in the scope of operator: ' '%s\nand is not generated by any of the local ' 'gradient operators.' % (grad_op_input, str(forward_op)) ) def AppendSparseGenerators(self, sparse_generators): # merge indices and values generators for sparse gradients for name, input_generators in sparse_generators.items(): for version, generators in input_generators.items(): if len(generators) == 1: # either indices or values are generated (but not both) generator = generators[0] else: # both indices and values are generated assert(len(generators) == 2) op1_i, idx1_i, op1_v, idx1_v, g1 = generators[0] op2_i, idx2_i, op2_v, idx2_v, g2 = generators[1] assert(g1 == g2) assert(op1_i is None or op2_i is None) assert(op1_v is None or op2_v is None) assert(idx1_i == 0 or idx2_i == 0) assert(idx1_v == 0 or idx2_v == 0) generator = SparseGradGenMeta( op1_i or op2_i, idx1_i + idx2_i, op1_v or op2_v, idx1_v + idx2_v, g1) self.gradient_generators[name][version].append(generator) def BuildGradientGenerators( # NOQA self, fwd_op_idx, gradient_ops, g_output, g_input): """Updates gradient_generators and gradient_frontier""" forward_op, in_versions, out_versions = self.ssa[fwd_op_idx] locally_generated_blobs = [] sparse_generators = defaultdict(lambda: defaultdict(list)) for grad_op in gradient_ops: # (1) check that inputs are valid for s in grad_op.input: self.CheckGradientOperatorInput( s, g_output, fwd_op_idx, locally_generated_blobs) # (2) add outputs to the locally generated blobs # If an output corresponds to the gradient of an input, we also # record it to gradient_generators locally_generated_blobs.extend([str(s) for s in grad_op.output]) for i, output in enumerate(grad_op.output): input_index = GetIndexFromGradientList(g_input, output) if input_index is not None: input_name = forward_op.input[input_index] input_version = in_versions[input_name] g = g_input[input_index] if type(g) is GradientSlice: # the output corresponds either to the indices or the # values of the sparse gradient. In either case we # create a (partial) SparseGradGenMeta. If necessary, # we'll merge indices and values generators # corresponding to the same gradient in step (3) if g.indices == output: m = SparseGradGenMeta(grad_op, i, None, 0, g) else: assert(g.values == output) m = SparseGradGenMeta(None, 0, grad_op, i, g) sparse_generators[input_name][input_version].append(m) else: self.gradient_generators[input_name][input_version] \ .append(GradGenMeta( grad_op, i, g)) # (3) merge indices and values generators for sparse gradients, and # add them to gradient_generators self.AppendSparseGenerators(sparse_generators) # (4) for ops (e.g., Add, Sum, Sub) which have gradient outputs directly # passed from inputs (not computed from gradient ops), we create an # GradGenMeta with None grad_op and idx so that the gradient_generators # knows where the gradients are coming from. This is needed for creating # Sum op to accumulate the gradients from multiple parents. for input_index, g in enumerate(g_input): input_name = forward_op.input[input_index] input_version = in_versions[input_name] if not g: continue if type(g) is GradientSlice: if str(g.indices) not in locally_generated_blobs and \ str(g.values) not in locally_generated_blobs: self.gradient_generators[input_name][input_version].append( SparseGradGenMeta(None, 0, None, 0, g)) else: if str(g) not in locally_generated_blobs: self.gradient_generators[input_name][input_version].append( GradGenMeta(None, 0, g)) # Finally, for the gradients specified in g_input, we update the # gradient frontier to reflect the input versions that the gradients # correspond to. for i, g in enumerate(g_input): if g is not None: input_name = forward_op.input[i] input_version = in_versions[input_name] self.gradient_frontier[input_name] = input_version def _GetSumOpOutputName(self, generator, input_name): def remove_suffix(s, suffix): if s.endswith(suffix): return s[:-len(suffix)] return s for g in generator: if type(g) is GradGenMeta: grad_op, idx, _ = g if grad_op: return grad_op.output[idx] else: assert(type(g) is SparseGradGenMeta) op_i, idx_i, op_v, idx_v, _ = g if op_i: return remove_suffix(op_i.output[idx_i], '_indices') if op_v: return remove_suffix(op_v.output[idx_v], '_values') return input_name + '_grad' def _SetSumOpsDeviceOption(self, sum_ops, generators): # we already checked that device options are consistent so we can just # use the first one we find for generator in generators: grad_op = generator.grad_op if type(generator) is GradGenMeta \ else generator.grad_op_values or generator.grad_op_indices if grad_op: if grad_op.HasField('device_option'): for op in sum_ops: op.device_option.CopyFrom(grad_op.device_option) break def _DisambiguateGradOpOutput(self, grad_op, idx, cnt): grad_op.output[idx] = ( '_' + grad_op.output[idx] + '_autosplit_{}'.format(cnt)) return grad_op.output[idx], cnt + 1 def _CheckSumOpsConflict(self, out_base_name, g): if str(out_base_name) == str(g): # TODO not sure what this message really means raise RuntimeError( 'The gradient output of empty gradient op can not ' 'be the same as the normal name of the current ' 'input gradient.') def _MakeDenseSumOps(self, generators, out_base_name): sum_op_input = [] cnt = 0 for generator in generators: grad_op, idx, g = generator assert(type(g) is not GradientSlice) if grad_op: out, cnt = self._DisambiguateGradOpOutput(grad_op, idx, cnt) sum_op_input.append(out) else: self._CheckSumOpsConflict(out_base_name, g) sum_op_input.append(str(g)) sum_ops = [CreateOperator( "Sum", map(BlobReference, sum_op_input), BlobReference(out_base_name))] return sum_ops, out_base_name def _MakeSparseSumOps(self, generators, out_base_name): indices_concat_input = [] values_concat_input = [] cnt_i = 0 cnt_v = 0 for generator in generators: assert(type(generator) is SparseGradGenMeta) op_i, idx_i, op_v, idx_v, g = generator if op_i: out, cnt_i = self._DisambiguateGradOpOutput(op_i, idx_i, cnt_i) indices_concat_input.append(out) else: self._CheckSumOpsConflict(out_base_name, g.indices) indices_concat_input.append(g.indices) if op_v: out, cnt_v = self._DisambiguateGradOpOutput(op_v, idx_v, cnt_v) values_concat_input.append(out) else: self._CheckSumOpsConflict(out_base_name, g.values) values_concat_input.append(g.values) indices_concat_output = out_base_name + '_indices_concat' indices_concat_split = out_base_name + '_indices_concat_split' values_concat_output = out_base_name + '_values_concat' values_concat_split = out_base_name + '_values_concat_split' # Sum the given sparse representations by simply concatenating the # indices (resp. values) tensors together. We don't do any deduplication # of indices at this point. This will be done as needed before the # optimizer is called sum_ops = [ CreateOperator( "Concat", map(BlobReference, indices_concat_input), map(BlobReference, [indices_concat_output, indices_concat_split]), axis=0 ), CreateOperator( "Concat", map(BlobReference, values_concat_input), map(BlobReference, [values_concat_output, values_concat_split]), axis=0 ), ] sum_op_output = GradientSlice( indices=indices_concat_output, values=values_concat_output, ) return sum_ops, sum_op_output def _MakeSumOps(self, input_name, input_version): generators = self.gradient_generators[input_name][input_version] out_base_name = self._GetSumOpOutputName(generators, input_name) types = list(set(type(x) for x in generators)) assert(len(types) == 1) if types[0] is GradGenMeta: sum_ops, g = self._MakeDenseSumOps(generators, out_base_name) else: assert(types[0] is SparseGradGenMeta) sum_ops, g = self._MakeSparseSumOps(generators, out_base_name) self._SetSumOpsDeviceOption(sum_ops, generators) return sum_ops, g def _VerifyGradientGenerators(self, generator): # (1) check if all gradients are of the same type. Aggregating a mix of # sparse and dense gradients is not supported yet if len({type(g) for g in generator}) > 1: raise RuntimeError( 'Automatic aggregation of a mix of sparse and dense gradients ' 'is not supported yet') # If for all the operators that used the operator, none or only one # produced the gradient, then no additional sum needs to be carried # out. if len(generator) < 2: return False all_gradient_names = [] all_device_options = [] for g in generator: if type(g) is GradGenMeta: if g.grad_op: all_gradient_names.append(g.gradient) all_device_options.append(g.grad_op.device_option) else: assert(type(g) is SparseGradGenMeta) if g.grad_op_indices: all_device_options.append(g.grad_op_indices.device_option) if g.grad_op_values: all_device_options.append(g.grad_op_values.device_option) all_gradient_names.append(g.gradient.values) # Check if all grad names are the same. if len(set(all_gradient_names)) > 1: raise RuntimeError('Unexpected behavior: not all grad output ' 'names are the same.') # Check if all grad op device options are the same. if len(all_device_options) >= 2 and not all( d == all_device_options[0] for d in all_device_options[1:]): raise RuntimeError('Unexpected behavior: not all grad ops' 'have the same device option.') return True def DoGradientAccumulation(self, fwd_op_idx): """For each input name in the forward op, check if we will need to add gradient accumulation. If so, do gradient accumulation and return the list of gradient operators. The criteria for doing gradient accumulation is: (1) the specific input version has been used by multiple operators. (2) the current fwd_op_idx is the first to use that input, i.e. in the backward pass, is the last to optionally generate the gradient for the op. (3) For the operators that used the input, their gradient operators have generated more than 1 gradient. When accumulating operators, our current solution is to rename all the created gradients with an internal intermediate name, and then add a Sum() operator that adds up all the gradients. This may use more memory due to intermediate storage, but is usually the fastest approach as one can do one single sum for multiple intermediate gradients. """ forward_op, in_versions, out_versions = self.ssa[fwd_op_idx] additional_sum_ops = [] grad_map = {} for i, input_name in enumerate(set(forward_op.input)): input_version = in_versions[input_name] input_usage = self.input_usages[input_name][input_version] if (len(input_usage) <= 1 or fwd_op_idx != input_usage[0]): # We do not need to do gradient accumulation yet. continue generator = self.gradient_generators[input_name][input_version] try: if not self._VerifyGradientGenerators(generator): continue except RuntimeError as err: raise RuntimeError( "Gradients for param ''{}'' failed to verify: {}".format( input_name, err ) ) # Finally, let's create the sum operator. sum_ops, g = self._MakeSumOps(input_name, input_version) additional_sum_ops.extend(sum_ops) grad_map[input_name] = g return additional_sum_ops, grad_map def _GetInitGradients(self, ys): input_to_grad = {} gradient_ops = [] for y, g in ys.items(): if g is None: autograd_op = CreateOperator( "ConstantFill", [y], [str(y) + "_autogen_grad"], value=1.0) gradient_ops.append(autograd_op) g = autograd_op.output[0] # Since the C++ gradient registry does not have notion of # NameScopes, we will convert all references to strings. input_to_grad[str(y)] = ( GradientSlice(str(g[0]), str(g[1])) if isinstance(g, GradientSlice) else str(g)) return input_to_grad, gradient_ops def _GenerateGradientsForForwardOp( self, forward_op_idx, input_to_grad): new_input_to_grad = {} gradient_ops = [] forward_op, in_versions, out_versions = self.ssa[forward_op_idx] g_output = list( input_to_grad.get(name, None) for name in forward_op.output) if not all(g is None for g in g_output): gradient_ops, g_input = GradientRegistry.GetGradientForOp( forward_op, g_output) # Check if the gradient operators are legal, and update # gradient_generators and gradient_frontier self.BuildGradientGenerators( forward_op_idx, gradient_ops, g_output, g_input) # Record the gradient map to all_input_to_grad. for name, grad in zip(forward_op.input, g_input): new_input_to_grad[name] = grad return new_input_to_grad, gradient_ops def GetBackwardPass(self, ys): """Gets the backward pass that computes the derivatives of given blobs. Inputs: ys: a list or a dictionary specifying what blobs we want to compute derivatives of. If the input is a list, we will automatically generate their gradients with all-one values; if the input is a dictionary, for any dictionary entries that are not None, we will take the corresponding blobs as their gradients; for all those that are None, we will auto-fill them with 1. """ if isinstance(ys, list): ys = dict((y, None) for y in ys) elif not isinstance(ys, dict): raise TypeError("ys should either be a list or a dict.") # Set the gradient frontier with the initialized external # gradients. for y, _ in ys.items(): self.gradient_frontier[y] = self.frontier[y] all_input_to_grad, all_gradient_ops = self._GetInitGradients(ys) # (2) Now, after having the virtual play above, we now play the ops # backwards, creating the gradients along the path. Note that although # we are playing it backwards, we cannot refer to variables that are # at a version older than current_versions because it is already been # overwritten. for forward_op_idx in reversed(range(len(self.ssa))): input_to_grad, gradient_ops = self._GenerateGradientsForForwardOp( forward_op_idx, all_input_to_grad) all_input_to_grad.update(input_to_grad) all_gradient_ops += gradient_ops # If there are multiple use blobs, do gradient accumulation. additional_sum_ops, grad_map = self.DoGradientAccumulation( forward_op_idx) # This line is so that if in an accumulation some of the operators # have not produced gradients, they still do not overwrite the # general all_input_to_grad map. all_input_to_grad.update(grad_map) all_gradient_ops += additional_sum_ops # (3) Post-processing. # After we have done computation for each op, we now have the gradient # operators ready. For the output map, we will convert everything to # BlobReferences for easier handling in python. all_input_to_grad_out = {} for key, val in all_input_to_grad.items(): if val is not None: all_input_to_grad_out[BlobReference(key)] = ( BlobReference(val) if isinstance(val, basestring) else GradientSlice(BlobReference(val[0]), BlobReference(val[1]))) return all_gradient_ops, all_input_to_grad_out class GradientRegistry(object): """GradientRegistry holds the mapping from operators to their gradients.""" gradient_registry_ = {} @classmethod def RegisterGradient(cls, op_type): """A decorator for registering gradient mappings.""" def Wrapper(func): cls.gradient_registry_[op_type] = func return func return Wrapper @classmethod def _GetGradientForOpCC(cls, op_def, g_output): # TODO(tulloch) - Propagate GradientWrapper up through the stack. def from_untyped(grad): if grad is None: w = C.GradientWrapper() assert w.is_empty() return w try: (indices, values) = grad w = C.GradientWrapper() w.indices = indices w.values = values assert w.is_sparse() return w except ValueError: w = C.GradientWrapper() w.dense = grad assert w.is_dense() return w g_output = [from_untyped(grad) for grad in g_output] grad_defs_str, g_input = C.get_gradient_defs( op_def.SerializeToString(), g_output) def to_untyped(grad_wrapper): if grad_wrapper.is_empty(): return None if grad_wrapper.is_sparse(): return GradientSlice(grad_wrapper.indices, grad_wrapper.values) assert grad_wrapper.is_dense() return grad_wrapper.dense g_input = [to_untyped(grad_wrapper) for grad_wrapper in g_input] grad_defs = [] for grad_def_str in grad_defs_str: grad_def = caffe2_pb2.OperatorDef() grad_def.ParseFromString(grad_def_str) grad_defs.append(grad_def) return grad_defs, g_input @classmethod def GetGradientForOp(cls, op, g_output): try: gradient_ops, g_input = cls._GetGradientForOpCC(op, g_output) except Exception as e: # Not supported in C++; will try python registration next. try: gradient_ops, g_input = cls.gradient_registry_[op.type]( op, g_output) except KeyError: raise Exception( "No gradient registered for {}. ".format(op.type) + "Exception from creating the gradient op: {}.".format(e)) if gradient_ops is None: return [], g_input if type(gradient_ops) is not list: gradient_ops = [gradient_ops] return gradient_ops, g_input @classmethod def GetBackwardPass(cls, operators, ys): """Gets the backward pass for the list of operators. Args: operators: a list of operators constituting the forward pass. ys: a list or a dictionary specifying what blobs we want to compute derivatives of. If the input is a list, we will automatically generate their gradients with all-one values; if the input is a dictionary, for any dictionary entries that are not None, we'll take the corresponding blobs as their gradients; for all those that are None, we will auto-fill them with 1. Returns: gradient_ops: a list of gradient operators to run. all_input_to_grads: a map from input to their corresponding gradients. """ ir = IR(operators) return ir.GetBackwardPass(ys) def get_ssa(net, blob_versions=None): """ Given a net, return a structure containing the version of each input and output blob used by each operator. Args: net: either a Net or a NetDef blob_versions: (optional) map with current version number for given blob names. If not provided or blob not found, start from version 0. Returns: Tuple (ssa, blob_versions) ssa: list of tuples (versioned_inputs, versioned_outputs) for each op in the net. A versioned input is a tuple (blob_name, version). blob_versions: updated map with latest version of each blob found in the net. """ proto = net.Proto() if isinstance(net, Net) else net assert isinstance(proto, caffe2_pb2.NetDef) if blob_versions is None: blob_versions = {} if isinstance(net, list): return [get_ssa(n, blob_versions) for n in net], blob_versions for i in proto.external_input: if i not in blob_versions: blob_versions[str(i)] = 0 ssa = [] for op in proto.op: if not proto.external_input: for i in op.input: if i not in blob_versions: blob_versions[i] = 0 inputs = [(str(i), blob_versions.get(str(i), 0)) for i in op.input] for o in op.output: blob_versions[str(o)] = blob_versions.get(str(o), 0) + 1 outputs = [(str(o), blob_versions[str(o)]) for o in op.output] ssa.append((inputs, outputs)) return ssa, blob_versions def get_undefined_blobs(ssa): """ Given a ssa in the format produced by get_ssa(), return a set of blobs that are used before they are defined, which corresponds to inputs at version 0. """ undef_blobs = set() for inputs, outputs in ssa: undef_blobs |= set(name for (name, ver) in inputs if ver == 0) return undef_blobs def get_output_producers(ssa): """ Given a ssa in the format produced by get_ssa(), returns a map from versioned blob into the operator index that produces that version of the blob. A versioned blob is a tuple (blob_name, version). """ producers = {} for i, (inputs, outputs) in enumerate(ssa): for o in outputs: producers[o] = i return producers def get_op_ids_in_path(ssa, blob_versions, inputs, outputs): """ Given a ssa and blob_versions as produced by get_ssa(), returns the list of op indices that are necessary in order to generate the blobs in `outputs`, given blobs in `inputs`. Consider that the `inputs` are given in their latest version. """ inputs_set = set((str(i), blob_versions[str(i)]) for i in inputs) producers = get_output_producers(ssa) queue = [(str(o), blob_versions[str(o)]) for o in outputs] used_op_ids = set() while len(queue) > 0: o = queue.pop() if (o not in inputs_set) and (o in producers): op_id = producers[o] if op_id not in used_op_ids: used_op_ids |= {op_id} inputs, _ = ssa[op_id] queue.extend(inputs) return sorted(used_op_ids) def clone_and_bind_net(net, name, prefix, blob_remap=None, inputs=None, keep_schema=True): """ Clone the given Net, binding its input schema to the given `inputs` record. Blob names defined by the net are prepended with the given `prefix`. Args: net: the net to clone name: the name of the new net prefix: the prefix to append to local blobs blob_remap: (optional) dict with additional blob name remapping. inputs: (optional) input record that will provide actual input values for the cloned net. Must be compatible with the net's input schema or be a strict superset of it keep_schema: by default (True), the original schema will be kept and remapped accordingly. otherwise, the schema will be set as inputs or left empty if inputs is not given. Returns: Tuple (cloned_net, blob_remap) clone_net: the cloned Net blob_remap: a map from original blob names into remapped blob names """ from caffe2.python import schema assert isinstance(net, Net) if blob_remap is None: blob_remap = {} if inputs is not None: assert isinstance(inputs, schema.Field) original = net.input_record() assert original is not None # TODO(azzolini): improve schema type checking diff = set(original.field_names()) - set(inputs.field_names()) assert len(diff) == 0, \ 'Schemas do not match, extra fields found in the net'.format(diff) original_mapping = dict(zip(original.field_names(), original.field_blobs())) for fn, fb in zip(inputs.field_names(), inputs.field_blobs()): if fn in original_mapping: blob_remap[str(original_mapping[fn])] = str(fb) proto = net.Proto() ssa, blob_versions = get_ssa(proto) undef_blobs = get_undefined_blobs(ssa) for blob in blob_versions.keys(): if blob in blob_remap: continue elif blob in undef_blobs: blob_remap[blob] = blob else: blob_remap[blob] = prefix + blob cloned_net = net.Clone(name, blob_remap, keep_schema=keep_schema) if not keep_schema and inputs: cloned_net.set_input_record(inputs) return cloned_net, blob_remap def _get_blob_ref(blob_name_or_ref): return ( blob_name_or_ref if isinstance(input, BlobReference) else BlobReference(blob_name_or_ref) ) class Net(object): _net_names_used = set() operator_registry_ = {} @staticmethod def _get_next_net_name(basename): name = basename next_idx = 1 while name in Net._net_names_used: name = basename + '_' + str(next_idx) next_idx += 1 Net._net_names_used |= set([name]) return name def __init__(self, name_or_proto): """ Create a Net. Args: name_or_proto: If a NetDef is provided, clone it. Otherwise, create an empty net with the given name. """ self._input_record = None self._output_record = None self._recreate_lookup_tables = False self._op_outputs = set() self._external_input_map = set() self._attr_dict = defaultdict(list) if type(name_or_proto) is caffe2_pb2.NetDef: proto = name_or_proto # We rae initializing a network by a NetDef. In this case, we will # initialize our network with the given netdef. self._net = caffe2_pb2.NetDef() self._net.CopyFrom(proto) existing_outputs = [list(op.output) for op in self._net.op] self._external_input_map.update(list(self._net.external_input)) # Set the next name index properly. existing_names = set( sum( [list(op.input) for op in self._net.op], [] ) + sum( existing_outputs, [] ) ) for outs in existing_outputs: self._op_outputs.update(outs) prefix_len = len(self._net.name + '_blob_') autogen_indices = [] for s in existing_names: if s.startswith(self._net.name + '_blob_'): try: autogen_indices.append(int(s[prefix_len])) except ValueError: pass if len(autogen_indices): self._next_name_index = max(autogen_indices) + 1 else: self._next_name_index = 0 else: self._net = caffe2_pb2.NetDef() self._net.name = name_or_proto self._next_name_index = 0 # make sure that this net name hasn't been used before self._net.name = Net._get_next_net_name(self._net.name) def AppendNet(self, net): assert isinstance(net, Net) self._ExtendOps(net.Proto().op) self.Proto().external_input.extend( [i for i in net.Proto().external_input if i not in self.Proto().external_input]) self.Proto().external_output.extend( [o for o in net.Proto().external_output if o not in self.Proto().external_output]) return self def LogInfo(self, *msg_or_blobs): for msg_or_blob in msg_or_blobs: if not isinstance(msg_or_blob, BlobReference): blob = self.GivenTensorStringFill( [], self.NextName('log'), shape=[], values=[msg_or_blob]) else: blob = msg_or_blob self.Print(blob, []) def add_attribute(self, name, obj): """ Add `obj` to the list of attributes in this net under the given `name`. Attributes are user-defined objects and have no pre-defined semantics. """ self._attr_dict[name].append(obj) def get_attributes(self, name): """ Returns the list of attributes in this net for a given `name`. Attributes are user-defined objects added with `add_attribute'. """ return self._attr_dict.get(name, []) def Name(self): return self._net.name def __str__(self): return self.Name() def Const(self, array, blob_out=None, dtype=None): if isinstance(array, bool): return self.ConstantFill( [], blob_out or 1, dtype=DataType.BOOL, value=array) if dtype is None: array = np.array(array) else: array = np.array(array, dtype=dtype) def do_set(operator): return operator( [], blob_out or 1, shape=array.shape, values=array.flatten().tolist()) if array.dtype == np.int32: return do_set(self.GivenTensorIntFill) elif array.dtype == np.int64: return do_set(self.GivenTensorInt64Fill) elif array.dtype == np.str: return do_set(self.GivenTensorStringFill) else: return do_set(self.GivenTensorFill) def BlobIsDefined(self, blob): """ Returns true if the given BlobReference is produced as output of an operator in this net, or if it is provided as an external input. """ if self._recreate_lookup_tables: self._RecreateLookupTables() name = str(blob) return (name in self._op_outputs) or (name in self._external_input_map) def UsesBlob(self, blob): """ Returns true iff the given BlobReference is used by any operator or this net, or if it is one of the external inputs of the net. """ blob_name = str(blob) for op in self._net.op: for input in op.input: if input == blob_name: return True return blob_name in self._external_input_map def GetBlobRef(self, blob_name): """ Given the name of a blob produced by this net, return a BlobReference to it. If the blob is not produced by any op in this net, raises KeyError. """ blob_name = str(blob_name) if not self.BlobIsDefined(blob_name): raise KeyError('Net does not define blob %s' % blob_name) return BlobReference(blob_name, self) def Clone( self, name, blob_remap=None, op_id_mask=None, remap_funcs=None, keep_schema=True ): """ Clone this net. Args: name: name of the cloned net blob_remap: optional map with list of blob names to replace op_id_mask: optional list of operator indices to include in the cloned net. If not provided, all ops are included. """ if remap_funcs is None: remap_funcs = {} proto = self._net new_proto = caffe2_pb2.NetDef() new_proto.CopyFrom(proto) new_proto.name = name if blob_remap is None and op_id_mask is None: # TODO(azzolini): should we also clone input_record here return Net(new_proto) if blob_remap is None: blob_remap = {} if op_id_mask is None: op_id_mask = range(0, len(proto.op)) def remap_list(proto_list): new_list = [blob_remap.get(b, b) for b in proto_list] del proto_list[:] proto_list.extend(new_list) def remap_op(op): new_op = caffe2_pb2.OperatorDef() new_op.CopyFrom(op) remap_list(new_op.input) remap_list(new_op.output) if new_op.type in remap_funcs: remap_funcs[new_op.type](new_op, (name + '/') if name else '') return new_op del new_proto.op[:] new_proto.op.extend(remap_op(proto.op[op_id]) for op_id in op_id_mask) remap_list(new_proto.external_input) remap_list(new_proto.external_output) new_net = Net(new_proto) if keep_schema: from caffe2.python import schema if self._input_record: new_net._input_record = schema.from_blob_list( self._input_record, [ BlobReference(str(blob_remap[str(blob)]), net=new_net) for blob in self._input_record.field_blobs() ], ) if self._output_record: new_net._output_record = schema.from_blob_list( self._output_record, [ BlobReference(str(blob_remap[str(blob)]), net=new_net) for blob in self._output_record.field_blobs() ], ) new_net._attr_dict.update(self._attr_dict) return new_net def ClonePartial(self, name, inputs, outputs, remap_funcs=None): """ Clone this net, including only ops that are necessary in order to compute `outputs` given `inputs`. Return references to the cloned outputs. Internal blobs (blobs that are produced and consumed inside the net but not used as outputs) will be remapped to avoid name conflict. Args: name: the name of the cloned net inputs: map where the keys correspond to BlobReferences in the original net, and the values correspond to external inputs in the partially cloned net. If `inputs` is a list, don't remap input names. outputs: outputs to be produced by the cloned net. Returns: Tuple (new_net, new_outputs) new_net: a new Net object. new_outputs: list of BlobReferences corresponding to the outputs produced by new_net. """ input_is_pair_list = isinstance(inputs, list) and all( isinstance(i, tuple) and len(i) == 2 for i in inputs) inputs = ( inputs if isinstance(inputs, (dict, OrderedDict)) else OrderedDict(inputs) if input_is_pair_list else OrderedDict(zip(inputs, inputs))) for output in outputs: assert self.BlobIsDefined(output) input_names = {str(k): str(v) for k, v in inputs.items()} output_names = [str(o) for o in outputs] proto = self._net ssa, blob_versions = get_ssa(proto) used_op_ids = get_op_ids_in_path(ssa, blob_versions, inputs, outputs) disallowed_op_ids = get_op_ids_in_path(ssa, blob_versions, [], inputs) assert len(set(used_op_ids) & set(disallowed_op_ids)) == 0, ( 'Cannot partially clone net: some of the ops required would ' + 'generate the given input.') sub_ssa = [op for i, op in enumerate(ssa) if i in used_op_ids] undef_blobs = get_undefined_blobs(sub_ssa) - set(input_names.keys()) prefix = (name + '/') if name else '' def remap(blob_name): if blob_name in input_names: return input_names[blob_name] elif blob_name in undef_blobs: return blob_name else: return prefix + blob_name blob_mapping = {b: remap(b) for b in blob_versions.keys()} new_net = self.Clone(name, blob_mapping, used_op_ids, remap_funcs) new_in = [ blob_mapping[i] for i in input_names.keys()] + list(undef_blobs) new_out = [blob_mapping[o] for o in output_names] del new_net.Proto().external_input[:] new_net.Proto().external_input.extend(new_in) new_net._external_input_map = set(list(new_in)) del new_net.Proto().external_output[:] new_net.Proto().external_output.extend(new_out) return new_net, [new_net.GetBlobRef(o) for o in new_out] def Proto(self): self._InvalidateLookupTables() return self._net def NextName(self, prefix=None, output_id=None): """Returns the next name to be used, if you do not want to explicitly name your blob.""" if prefix: output_name_base = self._net.name + '/' + prefix output_name = output_name_base if output_id is not None: output_name += ':' + str(output_id) index = 2 while self.BlobIsDefined(str(ScopedBlobReference(output_name))): output_name = output_name_base + '_' + str(index) if output_id is not None: output_name += ':' + str(output_id) index += 1 else: output_name = self._net.name + '_blob_' + str(self._next_name_index) self._next_name_index += 1 return str(output_name) def _ExtendOps(self, new_ops): self._net.op.extend(new_ops) for op in new_ops: self._op_outputs.update([str(o) for o in op.output]) def _CheckLookupTables(self): ''' Called from unit tests to validate the internal lookup tables match the protobuf contents. ''' test_op_outputs = set() for op in self._net.op: for o in op.output: test_op_outputs.add(o) test_external_inp = set() for inp in self._net.external_input: test_external_inp.add(inp) assert test_op_outputs.difference(self._op_outputs) == set() assert test_external_inp.difference(self._external_input_map) == set() def _InvalidateLookupTables(self): self._recreate_lookup_tables = True def _RecreateLookupTables(self): self._op_outputs = set() for op in self._net.op: for o in op.output: self._op_outputs.add(o) self._external_input_map = set() for inp in self._net.external_input: self._external_input_map.add(inp) self._recreate_lookup_tables = False def AddGradientOperators(self, ys, skip=0): """Add the gradient for operators in the net. Inputs: ys: a list or a dictionary specifying what blobs we want to compute derivatives of. If the input is a list, we will automatically generate their gradients with all-one values; if the input is a dictionary, for any dictionary entries that are not None, we will take the corresponding blobs as their gradients; for all those that are None, we will auto-fill them with 1. skip: skips the first n operators. This is provided mainly because a lot of nets may use the first few operators for data generation like stuff which really do not need to have gradients. Outputs: returns a map from the blob name in the input network to a blob containing gradient or a GradientSlice in case of sparse gradient Currently, this is hard-coded for float operators if there are branches (i.e. a blob is used as input to multiple operators). This is because the gradient accumulation (Sum) is float only right now. """ grad_ops, input_to_grad = GradientRegistry.GetBackwardPass( self._net.op[skip:], ys) # Check if in immediate mode: the grad_ops are actually being produced # by C++ and bypasses the CreateOperator() call, so in immediate mode # we will have to explicitly run them. if workspace.IsImmediate(): for op in grad_ops: workspace.RunOperatorImmediate(op) self._ExtendOps(grad_ops) return input_to_grad def AddExternalInput(self, *inputs): assert len(inputs) > 0 refs = [] for input in inputs: input_name = str(input) assert str(input) not in self._external_input_map, ( 'Net already contains an input named %s' % input_name) for input in inputs: input_name = str(input) self._net.external_input.extend([input_name]) self._external_input_map.update([input_name]) refs.append(_get_blob_ref(input_name)) return refs[0] if len(refs) == 1 else refs def AddExternalOutput(self, *outputs): for output in outputs: assert isinstance(output, BlobReference) assert self.BlobIsDefined(output) for output in outputs: self.Proto().external_output.extend([str(output)]) @property def external_inputs(self): return map(_get_blob_ref, self._net.external_input) @property def external_outputs(self): return map(_get_blob_ref, self._net.external_output) def set_input_record(self, input_record): from caffe2.python import schema assert self._input_record is None, ( 'Input schema cannot be reset') if not input_record.has_blobs(): self._input_record = schema.NewRecord(self, input_record) else: self._input_record = input_record for blob in input_record.field_blobs(): if blob not in self.external_inputs: self.AddExternalInput(blob) return self._input_record def set_output_record(self, record): assert self._output_record is None, ( 'Output record cannot be reset') for blob in record.field_blobs(): assert self.BlobIsDefined(blob) for blob in record.field_blobs(): self.AddExternalOutput(blob) self._output_record = record def input_record(self): return self._input_record def output_record(self): return self._output_record def AddExternalInputs(self, *inputs): return self.AddExternalInput(*inputs) def AddExternalOutputs(self, *outputs): self.AddExternalOutput(*outputs) def DeduplicateGradientSlices(self, g, aggregator='sum'): assert isinstance(g, GradientSlice) unique, remapping = self.Unique([g.indices], 2, engine='SparseHash') if aggregator.lower() == 'sum': new_g = self.UnsortedSegmentSum([g.values, remapping], 1) elif aggregator.lower() == 'mean': new_g = self.UnsortedSegmentMean([g.values, remapping], 1) else: raise ValueError('{} is not supported'.format(aggregator)) return GradientSlice(indices=unique, values=new_g) def RunAllOnGPU(self, gpu_id=0, use_cudnn=False): """A convenient function to run everything on the GPU.""" device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CUDA device_option.cuda_gpu_id = gpu_id self._net.device_option.CopyFrom(device_option) if use_cudnn: for op in self._net.op: op.engine = "CUDNN" def _CreateAndAddToSelf(self, op_type, inputs, outputs=None, **kwargs): """A helper function to create an operator and add it to self. """ inputs = _RectifyInputOutput(inputs) for input in inputs: if not self.BlobIsDefined(input): assert input.Net() != self self.AddExternalInput(input) if outputs is None: # If we do not specify an output, we will assume that this op # produces one output in this case. outputs = self.NextName(prefix=op_type) elif type(outputs) is int: # In this case, we will auto-fill the given number of outputs # with auto-generated names. outputs = [ self.NextName(prefix=op_type, output_id=i) for i in range(outputs)] outputs = _RectifyInputOutput(outputs, net=self) op = CreateOperator(op_type, inputs, outputs, **kwargs) self._ExtendOps([op]) if len(op.output) == 0: return elif len(op.output) == 1: return BlobReference(str(op.output[0]), self) else: return tuple(BlobReference(str(o), self) for o in op.output) def __getattr__(self, op_type): if op_type.startswith('__'): raise AttributeError('Attribute {} not found.'.format(op_type)) if not IsOperator(op_type): raise RuntimeError( 'Method ' + op_type + ' is not a registered operator.' ) return lambda *args, **kwargs: self._CreateAndAddToSelf( op_type, *args, **kwargs) def Python(self, f, grad_f=None, pass_workspace=False): """ `f` should have a signature (inputs, outputs) If `pass_workspace` is True, the signature is changed to (inputs, outputs, workspace) where `workspace` is the workspace the op is going to run on. This is potentially dangerous (as the op can manipulate the workspace directly), use on your own risk. """ assert(IsOperator('Python')) token = _RegisterPythonImpl(f, grad_f, pass_workspace=pass_workspace) return lambda *args, **kwargs: self._CreateAndAddToSelf( 'Python', token=token, *args, **kwargs) def get_net_name(netlike): if isinstance(netlike, Net): return netlike.Proto().name elif isinstance(netlike, caffe2_pb2.NetDef): return netlike.name else: return netlike def output_to_list(op_output): """ Ensures that the output of an operator is a list. Use when an operator has a variable number of outputs, but a list of outputs is desired even when number of outputs is 1. Args: op_output: Either a BlobReferenece or an iterable of BlobReferences. Returns: A list of BlobReferences. """ assert type(op_output) in (list, tuple, BlobReference) return ( [op_output] if isinstance(op_output, BlobReference) else list(op_output)) def _add_net_to_dict(net_dict, net): name = get_net_name(net) if net in net_dict: assert net_dict[name] is None or net == net_dict[name], ( 'Different nets with same name: ' + name) return False else: net_dict[name] = net if isinstance(net, Net) else None return True class ExecutionStep(object): _step_names_used = set() @staticmethod def _get_next_step_name(basename): name = basename next_idx = 1 while name in ExecutionStep._step_names_used: name = basename + '_' + str(next_idx) next_idx += 1 ExecutionStep._step_names_used |= set([name]) return name def __init__(self, name, nets=None, num_iter=None): self._step = caffe2_pb2.ExecutionStep() self._step.name = name or ExecutionStep._get_next_step_name('step') self._net_dict = OrderedDict() self._is_used = False self._substeps = [] if nets is not None: if type(nets) is Net: nets = [nets] for net in nets: if _add_net_to_dict(self._net_dict, net): self._step.network.extend([get_net_name(net)]) if num_iter is not None: self._step.num_iter = num_iter def get_net(self, name): return self._net_dict[name] def Name(self): return self._step.name def __str__(self): return self._step.name def _assert_can_mutate(self): assert not self._is_used, ( 'Cannot mutate a step that has already been added to a plan/step.') def _notify_is_used(self): self._is_used = True def Proto(self): return self._step def HasNets(self): return self._step.network is not None and ( len(self._step.network) > 0) def HasSubsteps(self): return self._step.substep is not None and ( len(self._step.substep) > 0) def Nets(self): return self._net_dict.values() def Substeps(self): return self._substeps def SetIter(self, num_iter): self._assert_can_mutate() self._step.num_iter = num_iter def SetOnlyOnce(self, only_once): self._assert_can_mutate() self._step.only_once = only_once def SetShouldStopBlob(self, should_stop_blob): assert isinstance(should_stop_blob, BlobReference), ( "expects BlobReference here, got {}".format(type(should_stop_blob))) self._assert_can_mutate() self._step.should_stop_blob = str(should_stop_blob) def SetReportNet(self, report_net, report_interval): self._assert_can_mutate() _add_net_to_dict(self._net_dict, report_net) self._step.report_net = get_net_name(report_net) self._step.report_interval = report_interval def AddSubstep(self, substep): self._assert_can_mutate() assert not self.HasNets(), 'Cannot have both network and substeps.' if isinstance(substep, ExecutionStep): substep._notify_is_used() if not substep.HasNets() and not substep.HasSubsteps(): return self for net in substep.Nets(): _add_net_to_dict(self._net_dict, net) self._substeps.append(substep) proto = substep.Proto() else: proto = substep self._step.substep.add().CopyFrom(proto) return self def SetConcurrentSubsteps(self, concurrent_substeps): self._assert_can_mutate() assert not self.HasNets(), 'Cannot have both network and substeps.' self._step.concurrent_substeps = concurrent_substeps def AddNet(self, net): self._assert_can_mutate() assert not self.HasSubsteps(), 'Cannot have both network and substeps.' assert isinstance(net, Net) _add_net_to_dict(self._net_dict, net) self._step.network.extend([get_net_name(net)]) return self def get_all_attributes(self, name): """ Return the list of all attributes under the given `name`, present in all of the nets used in this execution step and its children. """ objs = [] for net in self._net_dict.values(): objs += net.get_attributes(name) return objs def add_nets_in_order(step, net_list): proto = step.Proto() for substep in step.Substeps(): add_nets_in_order(substep, net_list) for net in proto.network: if net not in net_list: net_list.append(net) # FIXME(azzolini): This is actually wrong. Report nets should be # instantiated first since they may run before any substep is run. # However, curerntly, Reporter depends on this behavior. if proto.report_net and proto.report_net not in net_list: net_list.append(proto.report_net) class Plan(object): def __init__(self, name_or_step): self._plan = caffe2_pb2.PlanDef() self._net_dict = OrderedDict() if isinstance(name_or_step, ExecutionStep): self._plan.name = name_or_step.Name() self.AddStep(name_or_step) elif isinstance(name_or_step, basestring): self._plan.name = name_or_step else: raise ValueError('name_or_step must be a string or ExecutionStep') def __str__(self): return self._plan.name def Proto(self): return self._plan def AddNets(self, nets): for net in nets: if _add_net_to_dict(self._net_dict, net): assert isinstance(net, Net) self._plan.network.add().CopyFrom(net.Proto()) def Nets(self): return self._net_dict.values() def AddStep(self, step): assert isinstance(step, ExecutionStep) step._notify_is_used() if not step.HasNets() and not step.HasSubsteps(): return self._plan.execution_step.add().CopyFrom(step.Proto()) # nets need to be added to the plan in order of usage net_list = [] add_nets_in_order(step, net_list) self.AddNets([step.get_net(n) for n in net_list]) def get_all_attributes(self, name): """ Return the list of all attributes under the given `name`, present in all of the nets used in this plan. """ objs = [] for net in self._net_dict.values(): objs += net.get_attributes(name) return objs def to_execution_step(step_or_nets, default_name=None): from caffe2.python.net_builder import NetBuilder if isinstance(step_or_nets, ExecutionStep): return step_or_nets stop_blob = None if isinstance(step_or_nets, NetBuilder): stop_blob = step_or_nets._stop_blob step_or_nets = step_or_nets.get() return execution_step( default_name, step_or_nets, should_stop_blob=stop_blob) def execution_step(default_name, steps_or_nets, num_iter=None, report_net=None, report_interval=None, concurrent_substeps=None, should_stop_blob=None, only_once=None): """ Helper for creating an ExecutionStep. - steps_or_nets can be: - None - Net - ExecutionStep - list<Net> - list<ExecutionStep> - should_stop_blob is either None or a scalar boolean blob. - This blob is checked AFTER every substeps/subnets. - If specified and true, then this step will return immediately. - Be sure to handle race conditions if setting from concurrent threads. - if no should_stop_blob or num_iter is provided, defaults to num_iter=1 """ assert should_stop_blob is None or num_iter is None, ( 'Cannot set both should_stop_blob and num_iter.') if should_stop_blob is None and num_iter is None: num_iter = 1 step = ExecutionStep(default_name) if should_stop_blob is not None: step.SetShouldStopBlob(should_stop_blob) if num_iter is not None: step.SetIter(num_iter) if only_once is not None: step.SetOnlyOnce(only_once) if concurrent_substeps is not None: step.SetConcurrentSubsteps(concurrent_substeps) if report_net is not None: assert report_interval is not None step.SetReportNet(report_net, report_interval) if isinstance(steps_or_nets, ExecutionStep): step.AddSubstep(steps_or_nets) elif isinstance(steps_or_nets, Net): step.AddNet(steps_or_nets) elif isinstance(steps_or_nets, list): if all(isinstance(x, Net) for x in steps_or_nets): map(step.AddNet, steps_or_nets) else: map(step.AddSubstep, map(to_execution_step, steps_or_nets)) elif steps_or_nets: raise ValueError( 'steps_or_nets must be a step, a net, or a list of nets or steps.') return step def scoped_execution_step(name, *args, **kwargs): """Same as execution_step() except that the step name is scoped.""" default_name = ScopedName(name) if name else name return execution_step(default_name, *args, **kwargs)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/schema.py
857
""" Defines a minimal set of data types that allow to represent datasets with arbitrary nested structure, including objects of variable length, such as maps and lists. This defines a columnar storage format for such datasets on top of caffe2 tensors. In terms of capacity of representation, it can represent most of the data types supported by Parquet, ORC, DWRF file formats. See comments in operator_test/dataset_ops_test.py for a example and walkthrough on how to use schema to store and iterate through a structured in-memory dataset. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import logging import numpy as np from caffe2.python import core from caffe2.python import workspace from caffe2.python.core import ScopedBlobReference, BlobReference from collections import OrderedDict, namedtuple logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) def _join_field_name(prefix, suffix): if prefix and suffix: return '{}:{}'.format(prefix, suffix) elif prefix: return prefix elif suffix: return suffix else: return '' def _normalize_field(field_or_type_or_blob, keep_blobs=True): """Clones/normalizes a field before adding it to a container.""" if isinstance(field_or_type_or_blob, Field): return field_or_type_or_blob.clone(keep_blobs=keep_blobs) elif type(field_or_type_or_blob) in (type, np.dtype): return Scalar(dtype=field_or_type_or_blob) else: return Scalar(blob=field_or_type_or_blob) FeatureSpec = namedtuple( 'FeatureSpec', ['feature_type', 'feature_names', 'feature_ids', 'feature_is_request_only'] ) FeatureSpec.__new__.__defaults__ = (None, None, None, None) class Metadata( namedtuple( 'Metadata', ['categorical_limit', 'expected_value', 'feature_specs'] ) ): """Represents additional information associated with a scalar in schema. `categorical_limit` - for fields of integral type that are guaranteed to be non-negative it specifies the maximum possible value plus one. It's often used as a size of an embedding table. `expected_value` - anticipated average value of elements in the field. Usually makes sense for length fields of lists. `feature_specs` - information about the features that contained in this field. For example if field have more then 1 feature it can have list of feature names contained in this field.""" __slots__ = () Metadata.__new__.__defaults__ = (None, None, None) class Field(object): """Represents an abstract field type in a dataset. """ def __init__(self, children): """Derived classes must call this after their initialization.""" self._parent = (None, 0) offset = 0 self._field_offsets = [] for child in children: self._field_offsets.append(offset) offset += len(child.field_names()) self._field_offsets.append(offset) def clone_schema(self): return self.clone(keep_blobs=False) def field_names(self): """Return the children field names for this field.""" raise NotImplementedError('Field is an abstract class.') def field_types(self): """Return the numpy.dtype for each of the children fields.""" raise NotImplementedError('Field is an abstract class.') def field_metadata(self): """Return the Metadata for each of the children fields.""" raise NotImplementedError('Field is an abstract class.') def field_blobs(self): """Return the list of blobs with contents for this Field. Values can either be all numpy.ndarray or BlobReference. If any of the fields doens't have a blob, throws. """ raise NotImplementedError('Field is an abstract class.') def all_scalars(self): """Return the list of all Scalar instances in the Field. The order is the same as for field_names() or field_blobs()""" raise NotImplementedError('Field is an abstract class.') def has_blobs(self): """Return True if every scalar of this field has blobs.""" raise NotImplementedError('Field is an abstract class.') def clone(self, keep_blobs=True): """Clone this Field along with its children.""" raise NotImplementedError('Field is an abstract class.') def _set_parent(self, parent, relative_id): self._parent = (parent, relative_id) def slice(self): """ Returns a slice representing the range of field ids that belong to this field. This slice can be used to index a list of fields. E.g.: >>> s = Struct( >>> ('a', Scalar()), >>> ('b', Struct( >>> ('b1', Scalar()), >>> ('b2', Scalar()), >>> )), >>> ('c', Scalar()), >>> ) >>> field_data = ['da', 'db1', 'db2', 'dc'] >>> field_data[s.b.split()] ['db1', 'db2'] """ base_id = self._child_base_id() return slice(base_id, base_id + len(self.field_names())) def _child_base_id(self, child_index=None): """Get the base id of the given child""" p, i = self._parent pos = 0 if child_index is None else self._field_offsets[child_index] if p: pos += p._child_base_id(i) return pos def __eq__(self, other): """Equivalance of two schemas""" return ( (self.field_names() == other.field_names()) and (self.field_types() == other.field_types()) and (self.field_metadata() == other.field_metadata()) ) class List(Field): """Represents a variable-length list. Values of a list can also be complex fields such as Lists and Structs. In addition to the fields exposed by its `values` field, a List exposes an additional `lengths` field, which will contain the size of each list under the parent domain. """ def __init__(self, values, lengths_blob=None): if isinstance(lengths_blob, Field): assert isinstance(lengths_blob, Scalar) self.lengths = _normalize_field(lengths_blob) else: self.lengths = Scalar(np.int32, lengths_blob) self._items = _normalize_field(values) self.lengths._set_parent(self, 0) self._items._set_parent(self, 1) Field.__init__(self, [self.lengths, self._items]) def field_names(self): value_fields = self._items.field_names() return ( ['lengths'] + [_join_field_name('values', v) for v in value_fields] ) def field_types(self): return self.lengths.field_types() + self._items.field_types() def field_metadata(self): return self.lengths.field_metadata() + self._items.field_metadata() def field_blobs(self): return self.lengths.field_blobs() + self._items.field_blobs() def all_scalars(self): return self.lengths.all_scalars() + self._items.all_scalars() def has_blobs(self): return self.lengths.has_blobs() and self._items.has_blobs() def clone(self, keep_blobs=True): return List( _normalize_field(self._items, keep_blobs=keep_blobs), _normalize_field(self.lengths, keep_blobs=keep_blobs) ) def __getattr__(self, item): """If the value of this list is a struct, allow to instrospect directly into its fields.""" if item.startswith('__'): raise AttributeError(item) if isinstance(self._items, Struct): return getattr(self._items, item) elif item == 'value' or item == 'items': return self._items else: raise AttributeError('Field not found in list: %s.' % item) class Struct(Field): """Represents a named list of fields sharing the same domain. """ def __init__(self, *fields): for field in fields: assert len(field) == 2 assert field[0], 'Field names cannot be empty' assert field[0] != 'lengths', ( 'Struct cannot contain a field named `lengths`.' ) fields = [(name, _normalize_field(field)) for name, field in fields] for id, (name, field) in enumerate(fields): field._set_parent(self, id) self.fields = OrderedDict(fields) Field.__init__(self, self.fields.values()) def get_children(self): return self.fields.items() def field_names(self): names = [] for name, field in self.fields.items(): names += [_join_field_name(name, f) for f in field.field_names()] return names def field_types(self): types = [] for name, field in self.fields.items(): types += field.field_types() return types def field_metadata(self): metadata = [] for name, field in self.fields.items(): metadata += field.field_metadata() return metadata def field_blobs(self): blobs = [] for name, field in self.fields.items(): blobs += field.field_blobs() return blobs def all_scalars(self): scalars = [] for name, field in self.fields.items(): scalars += field.all_scalars() return scalars def has_blobs(self): return all(field.has_blobs() for field in self.fields.values()) def clone(self, keep_blobs=True): normalized_fields = [ (k, _normalize_field(v, keep_blobs=keep_blobs)) for k, v in self.fields.items() ] return Struct(*normalized_fields) def __len__(self): return len(self.fields) def __getitem__(self, item): if isinstance(item, list) or isinstance(item, tuple): return Struct( * [ ( self.fields.keys()[k] if isinstance(k, int) else k, self[k] ) for k in item ] ) elif isinstance(item, int): return self.fields.values()[item] else: return self.fields[item] def __getattr__(self, item): if item.startswith('__'): raise AttributeError(item) try: return self.__dict__['fields'][item] except KeyError: raise AttributeError(item) class Scalar(Field): """Represents a typed scalar or tensor of fixed shape. A Scalar is a leaf in a schema tree, translating to exactly one tensor in the dataset's underlying storage. Usually, the tensor storing the actual values of this field is a 1D tensor, representing a series of values in its domain. It is possible however to have higher rank values stored as a Scalar, as long as all entries have the same shape. E.g.: Scalar(np.float64) Scalar field of type float32. Caffe2 will expect readers and datasets to expose it as a 1D tensor of doubles (vector), where the size of the vector is determined by this fields' domain. Scalar((np.int32, 5)) Tensor field of type int32. Caffe2 will expect readers and datasets to implement it as a 2D tensor (matrix) of shape (L, 5), where L is determined by this fields' domain. Scalar((str, (10, 20))) Tensor field of type str. Caffe2 will expect readers and datasets to implement it as a 3D tensor of shape (L, 10, 20), where L is determined by this fields' domain. If the field type is unknown at construction time, call Scalar(), that will default to np.void as its dtype. It is an error to pass a structured dtype to Scalar, since it would contain more than one field. Instead, use from_dtype, which will construct a nested `Struct` field reflecting the given dtype's structure. A Scalar can also contain a blob, which represents the value of this Scalar. A blob can be either a numpy.ndarray, in which case it contain the actual contents of the Scalar, or a BlobReference, which represents a blob living in a caffe2 Workspace. If blob of different types are passed, a conversion to numpy.ndarray is attempted. """ def __init__(self, dtype=None, blob=None, metadata=None): self._metadata = None self.set(dtype, blob, metadata) Field.__init__(self, []) def field_names(self): return [''] def field_type(self): return self.dtype def field_types(self): return [self.dtype] def field_metadata(self): return [self._metadata] def has_blobs(self): return self._blob is not None def field_blobs(self): assert self._blob is not None, 'Value is not set for this field.' return [self._blob] def all_scalars(self): return [self] def clone(self, keep_blobs=True): return Scalar( dtype=self._original_dtype, blob=self._blob if keep_blobs else None, metadata=self._metadata ) def get(self): """Gets the current blob of this Scalar field.""" assert self._blob is not None, 'Value is not set for this field.' return self._blob def __call__(self): """Shortcut for self.get()""" return self.get() @property def metadata(self): return self._metadata def set_metadata(self, value): assert isinstance(value, Metadata), \ 'metadata must be Metadata, got {}'.format(type(value)) self._metadata = value self._validate_metadata() def _validate_metadata(self): if self._metadata is None: return if (self._metadata.categorical_limit is not None and self.dtype is not None): assert np.issubdtype(self.dtype, np.integer), \ "`categorical_limit` can be specified only in integral " + \ "fields but got {}".format(self.dtype) def set_value(self, blob): """Sets only the blob field still validating the existing dtype""" self.set(dtype=self._original_dtype, blob=blob) def set(self, dtype=None, blob=None, metadata=None): """Set the type and/or blob of this scalar. See __init__ for details. Args: dtype: can be any numpy type. If not provided and `blob` is provided, it will be inferred. If no argument is provided, this Scalar will be of type np.void. blob: if provided, can be either a BlobReference or a numpy.ndarray. If a value of different type is passed, a conversion to numpy.ndarray is attempted. Strings aren't accepted, since they can be ambiguous. If you want to pass a string, to either BlobReference(blob) or np.array(blob). metadata: optional instance of Metadata, if provided overrides the metadata information of the scalar """ if blob is not None and isinstance(blob, core.basestring): raise ValueError( 'Passing str blob to Scalar.set() is ambiguous. ' 'Do either set(blob=np.array(blob)) or ' 'set(blob=BlobReference(blob))' ) self._original_dtype = dtype if dtype is not None: dtype = np.dtype(dtype) # If blob is not None and it is not a BlobReference, we assume that # it is actual tensor data, so we will try to cast it to an numpy array. if blob is not None and not isinstance(blob, BlobReference): if dtype is not None and dtype != np.void: blob = np.array(blob, dtype=dtype.base) # if array is empty we may need to reshape a little if blob.size == 0: blob = blob.reshape((0, ) + dtype.shape) else: assert isinstance(blob, np.ndarray ), ('Invalid blob type: %s' % str(type(blob))) # reshape scalars into 1D arrays # TODO(azzolini): figure out better way of representing this if len(blob.shape) == 0: blob = blob.reshape((1, )) # infer inner shape from the blob given # TODO(dzhulgakov): tweak this to make it work with PackedStruct if (len(blob.shape) > 1 and dtype is not None and dtype.base != np.void): dtype = np.dtype((dtype.base, blob.shape[1:])) # if we were still unable to infer the dtype if dtype is None: dtype = np.dtype(np.void) assert not dtype.fields, ( 'Cannot create Scalar with a structured dtype. ' + 'Use from_dtype instead.' ) self.dtype = dtype self._blob = blob if metadata is not None: self.set_metadata(metadata) self._validate_metadata() def set_type(self, dtype): self._original_dtype = dtype self.dtype = np.dtype(dtype or np.void) self._validate_metadata() def id(self): """ Return the zero-indexed position of this scalar field in its schema. Used in order to index into the field_blob list returned by readers or accepted by writers. """ return self._child_base_id() def Map( keys, values, keys_name='keys', values_name='values', lengths_blob=None ): """A map is a List of Struct containing keys and values fields. Optionally, you can provide custom name for the key and value fields. """ return List( Struct((keys_name, keys), (values_name, values)), lengths_blob=lengths_blob ) def Tuple(*fields): """ Creates a Struct with default, sequential, field names of given types. """ return Struct(* [('field_%d' % i, field) for i, field in enumerate(fields)]) def RawTuple(num_fields): """ Creates a tuple of `num_field` untyped scalars. """ assert isinstance(num_fields, int) assert num_fields > 0 return Tuple(*([np.void] * num_fields)) def from_dtype(dtype, _outer_shape=()): """Constructs a Caffe2 schema from the given numpy's dtype. Numpy supports scalar, array-like and structured datatypes, as long as all the shapes are fixed. This function breaks down the given dtype into a Caffe2 schema containing `Struct` and `Scalar` types. Fields containing byte offsets are not currently supported. """ if not isinstance(dtype, np.dtype): # wrap into a ndtype shape = _outer_shape dtype = np.dtype((dtype, _outer_shape)) else: # concatenate shapes if necessary shape = _outer_shape + dtype.shape if shape != dtype.shape: dtype = np.dtype((dtype.base, shape)) if not dtype.fields: return Scalar(dtype) struct_fields = [] for name, (fdtype, offset) in dtype.fields: assert offset == 0, ('Fields with byte offsets are not supported.') struct_fields += (name, from_dtype(fdtype, _outer_shape=shape)) return Struct(*struct_fields) class _SchemaNode(object): """This is a private class used to represent a Schema Node""" def __init__(self, name, type_str=''): self.name = name self.children = [] self.type_str = type_str self.field = None self.col_blob = None def add_child(self, name, type_str=''): for child in self.children: if child.name == name and child.type_str == type_str: return child child = _SchemaNode(name, type_str) self.children.append(child) return child def get_field(self): list_names = ['lengths', 'values'] map_names = ['lengths', 'keys', 'values'] if len(self.children) == 0 or self.field is not None: assert self.field is not None return self.field child_names = [] for child in self.children: child_names.append(child.name) if (set(child_names) == set(list_names)): for child in self.children: if child.name == 'values': self.field = List( child.get_field(), lengths_blob=self.children[0].col_blob ) self.type_str = "List" return self.field elif (set(child_names) == set(map_names)): for child in self.children: if child.name == 'keys': key_field = child.get_field() elif child.name == 'values': values_field = child.get_field() self.field = Map( key_field, values_field, lengths_blob=self.children[0].col_blob ) self.type_str = "Map" return self.field else: struct_fields = [] for child in self.children: if child.field is not None: struct_fields.append((child.name, child.field)) else: struct_fields.append((child.name, child.get_field())) self.field = Struct(*struct_fields) self.type_str = "Struct" return self.field def print_recursively(self): for child in self.children: child.print_recursively() logger.info("Printing node: Name and type") logger.info(self.name) logger.info(self.type_str) def from_column_list( col_names, col_types=None, col_blobs=None, col_metadata=None ): """ Given a list of names, types, and optionally values, construct a Schema. """ if col_types is None: col_types = [None] * len(col_names) if col_metadata is None: col_metadata = [None] * len(col_names) if col_blobs is None: col_blobs = [None] * len(col_names) assert len(col_names) == len(col_types), ( 'col_names and col_types must have the same length.' ) assert len(col_names) == len(col_metadata), ( 'col_names and col_metadata must have the same length.' ) assert len(col_names) == len(col_blobs), ( 'col_names and col_blobs must have the same length.' ) root = _SchemaNode('root', 'Struct') for col_name, col_type, col_blob, col_metadata in zip( col_names, col_types, col_blobs, col_metadata ): columns = col_name.split(':') current = root for i in range(len(columns)): name = columns[i] type_str = '' field = None if i == len(columns) - 1: type_str = col_type field = Scalar( dtype=col_type, blob=col_blob, metadata=col_metadata ) next = current.add_child(name, type_str) if field is not None: next.field = field next.col_blob = col_blob current = next return root.get_field() def from_blob_list(schema, values): """ Create a schema that clones the given schema, but containing the given list of values. """ assert isinstance(schema, Field), 'Argument `schema` must be a Field.' if isinstance(values, BlobReference): values = [values] record = schema.clone_schema() scalars = record.all_scalars() assert len(scalars) == len(values), ( 'Values must have %d elements, got %d.' % (len(scalars), len(values)) ) for scalar, value in zip(scalars, values): scalar.set_value(value) return record def as_record(value): if isinstance(value, Field): return value elif isinstance(value, list) or isinstance(value, tuple): is_field_list = all( f is tuple and len(f) == 2 and isinstance(f[0], core.basestring) for f in value ) if is_field_list: return Struct(* [(k, as_record(v)) for k, v in value]) else: return Tuple(* [as_record(f) for f in value]) elif isinstance(value, dict): return Struct(* [(k, as_record(v)) for k, v in value.items()]) else: return _normalize_field(value) def FetchRecord(blob_record, ws=None): """ Given a record containing BlobReferences, return a new record with same schema, containing numpy arrays, fetched from the current active workspace. """ def fetch(v): if ws is None: return workspace.FetchBlob(str(v)) else: return ws.blobs[str(v)].fetch() assert isinstance(blob_record, Field) field_blobs = blob_record.field_blobs() assert all(isinstance(v, BlobReference) for v in field_blobs) field_arrays = [fetch(value) for value in field_blobs] return from_blob_list(blob_record, field_arrays) def FeedRecord(blob_record, arrays, ws=None): """ Given a Record containing blob_references and arrays, which is either a list of numpy arrays or a Record containing numpy arrays, feeds the record to the current workspace. """ def feed(b, v): if ws is None: workspace.FeedBlob(str(b), v) else: ws.create_blob(str(b)) ws.blobs[str(b)].feed(v) assert isinstance(blob_record, Field) field_blobs = blob_record.field_blobs() assert all(isinstance(v, BlobReference) for v in field_blobs) if isinstance(arrays, Field): # TODO: check schema arrays = arrays.field_blobs() assert len(arrays) == len(field_blobs), ( 'Values must contain exactly %d ndarrays.' % len(field_blobs) ) for blob, array in zip(field_blobs, arrays): feed(blob, array) def NewRecord(net, schema): """ Given a record of np.arrays, create a BlobReference for each one of them, returning a record containing BlobReferences. The BlobReferences will be added as ExternalInputs of the given net. """ if isinstance(schema, Scalar): result = schema.clone() result.set_value( blob=ScopedBlobReference(net.NextName('unnamed_scalar')) ) return result assert isinstance(schema, Field), 'Record must be a schema.Field instance.' blob_refs = [ net.AddExternalInput(net.NextName(prefix=name)) for name in schema.field_names() ] return from_blob_list(schema, blob_refs) def ConstRecord(net, array_record): """ Given a record of arrays, returns a record of blobs, initialized with net.Const. """ blob_record = NewRecord(net, array_record) for blob, array in zip( blob_record.field_blobs(), array_record.field_blobs() ): net.Const(array, blob) return blob_record def InitEmptyRecord(net, schema_or_record): if not schema_or_record.has_blobs(): record = NewRecord(net, schema_or_record) else: record = schema_or_record for blob in record.field_blobs(): net.ConstantFill([], blob, shape=[0]) return record _DATA_TYPE_FOR_DTYPE = [ (np.str, core.DataType.STRING), (np.float32, core.DataType.FLOAT), (np.float64, core.DataType.DOUBLE), (np.bool, core.DataType.BOOL), (np.int8, core.DataType.INT8), (np.int16, core.DataType.INT16), (np.int32, core.DataType.INT32), (np.int64, core.DataType.INT64), (np.uint8, core.DataType.UINT8), (np.uint16, core.DataType.UINT16), ] def is_schema_subset(schema, original_schema): # TODO add more checks return set(schema.field_names() ).issubset(set(original_schema.field_names())) def equal_schemas(schema, original_schema): assert isinstance(schema, Field) assert isinstance(original_schema, Field) # TODO allow for more compatibility return schema.field_names() == original_schema.field_names() and\ schema.field_types() == original_schema.field_types() def schema_check(schema, previous=None): record = as_record(schema) if previous is not None: assert equal_schemas(schema, previous) return record def data_type_for_dtype(dtype): for np_type, dt in _DATA_TYPE_FOR_DTYPE: if dtype.base == np_type: return dt raise TypeError('Unknown dtype: ' + str(dtype.base)) def attach_metadata_to_scalars(field, metadata): for f in field.all_scalars(): f.set_metadata(metadata)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/examples/resnet50_trainer.py
307
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import logging import numpy as np from caffe2.python import workspace, experiment_util, data_parallel_model from caffe2.python import timeout_guard, cnn import caffe2.python.models.resnet as resnet ''' Parallelized multi-GPU trainer for Resnet 50. Can be used to train on imagenet data, for example. ''' logging.basicConfig() log = logging.getLogger("resnet50_trainer") log.setLevel(logging.DEBUG) def AddImageInput(model, reader, batch_size, img_size): ''' Image input operator that loads data from reader and applies certain transformations to the images. ''' data, label = model.ImageInput( reader, ["data", "label"], batch_size=batch_size, use_caffe_datum=True, mean=128., std=128., scale=256, crop=img_size, mirror=1 ) data = model.StopGradient(data, data) def AddMomentumParameterUpdate(train_model, LR): ''' Add the momentum-SGD update. ''' params = train_model.GetParams() assert(len(params) > 0) for param in params: param_grad = train_model.param_to_grad[param] param_momentum = train_model.param_init_net.ConstantFill( [param], param + '_momentum', value=0.0 ) # Update param_grad and param_momentum in place train_model.net.MomentumSGDUpdate( [param_grad, param_momentum, LR, param], [param_grad, param_momentum, param], momentum=0.9, nesterov=1, ) def RunEpoch( args, epoch, train_model, test_model, total_batch_size, expname, explog, ): ''' Run one epoch of the trainer. TODO: add checkpointing here. ''' # TODO: add loading from checkpoint epoch_iters = int(args.epoch_size / total_batch_size) for i in range(epoch_iters): log.info("Start iteration {}/{} of epoch {}".format( i, epoch_iters, epoch, )) # This timeout is required (temporarily) since CUDA-NCCL # operators might deadlock when synchronizing between GPUs. timeout = 600.0 if i == 0 else 60.0 with timeout_guard.CompleteInTimeOrDie(timeout): workspace.RunNet(train_model.net.Proto().name) num_images = (i + epoch * epoch_iters) * total_batch_size record_freq = total_batch_size * 20 # Report progress, compute train and test accuracies. if num_images % record_freq == 0 and i > 0: prefix = "gpu_{}".format(train_model._devices[0]) accuracy = workspace.FetchBlob(prefix + '/accuracy') loss = workspace.FetchBlob(prefix + '/loss') learning_rate = workspace.FetchBlob(prefix + '/LR') test_accuracy = 0 ntests = 0 if (test_model is not None): # Run 5 iters of testing for t in range(0, 5): workspace.RunNet(test_model.net.Proto().name) for g in test_model._devices: test_accuracy += np.asscalar(workspace.FetchBlob( "gpu_{}".format(g) + '/accuracy' )) ntests += 1 test_accuracy /= ntests else: test_accuracy = (-1) explog.log( input_count=num_images, batch_count=(i + epoch * epoch_iters), additional_values={ 'accuracy': accuracy, 'loss': loss, 'learning_rate': learning_rate, 'epoch': epoch, 'test_accuracy': test_accuracy, } ) assert loss < 40, "Exploded gradients :(" # TODO: add checkpointing return epoch + 1 def Train(args): total_batch_size = args.batch_size num_gpus = args.num_gpus batch_per_device = total_batch_size // num_gpus assert \ total_batch_size % num_gpus == 0, \ "Number of GPUs must divide batch size" gpus = range(num_gpus) log.info("Running on gpus: {}".format(gpus)) # Create CNNModeLhelper object train_model = cnn.CNNModelHelper( order="NCHW", name="resnet50", use_cudnn=True, cudnn_exhaustive_search=True ) # Model building functions def create_resnet50_model_ops(model): [softmax, loss] = resnet.create_resnet50( model, "data", num_input_channels=args.num_channels, num_labels=args.num_labels, label="label", ) model.Accuracy([softmax, "label"], "accuracy") return [loss] # SGD def add_parameter_update_ops(model, lr_scale): model.AddWeightDecay(args.weight_decay) ITER = model.Iter("ITER") stepsz = int(30 * args.epoch_size / total_batch_size) LR = model.net.LearningRate( [ITER], "LR", base_lr=args.base_learning_rate * lr_scale, policy="step", stepsize=stepsz, gamma=0.1, ) AddMomentumParameterUpdate(model, LR) # Input. Note that the reader must be shared with all GPUS. reader = train_model.CreateDB( "reader", db=args.train_data, db_type=args.db_type, ) def add_image_input(model): AddImageInput( model, reader, batch_size=batch_per_device, img_size=args.image_size, ) # Create parallelized model data_parallel_model.Parallelize_GPU( train_model, input_builder_fun=add_image_input, forward_pass_builder_fun=create_resnet50_model_ops, param_update_builder_fun=add_parameter_update_ops, devices=gpus, optimize_gradient_memory=True, ) # Add test model, if specified test_model = None if (args.test_data is not None): log.info("----- Create test net ----") test_model = cnn.CNNModelHelper( order="NCHW", name="resnet50_test", use_cudnn=True, cudnn_exhaustive_search=True ) test_reader = test_model.CreateDB( "test_reader", db=args.test_data, db_type=args.db_type, ) def test_input_fn(model): AddImageInput( model, test_reader, batch_size=batch_per_device, img_size=args.image_size, ) data_parallel_model.Parallelize_GPU( test_model, input_builder_fun=test_input_fn, forward_pass_builder_fun=create_resnet50_model_ops, param_update_builder_fun=None, devices=gpus, ) workspace.RunNetOnce(test_model.param_init_net) workspace.CreateNet(test_model.net) workspace.RunNetOnce(train_model.param_init_net) workspace.CreateNet(train_model.net) expname = "resnet50_gpu%d_b%d_L%d_lr%.2f_v2" % ( args.num_gpus, total_batch_size, args.num_labels, args.base_learning_rate, ) explog = experiment_util.ModelTrainerLog(expname, args) # Run the training one epoch a time epoch = 0 while epoch < args.num_epochs: epoch = RunEpoch( args, epoch, train_model, test_model, total_batch_size, expname, explog ) # TODO: save final model. def main(): # TODO: use argv parser = argparse.ArgumentParser( description="Caffe2: Resnet-50 training" ) parser.add_argument("--train_data", type=str, default=None, help="Path to training data or 'everstore_sampler'", required=True) parser.add_argument("--test_data", type=str, default=None, help="Path to test data") parser.add_argument("--db_type", type=str, default="lmdb", help="Database type (such as lmdb or leveldb)") parser.add_argument("--num_gpus", type=int, default=1, help="Number of GPUs.") parser.add_argument("--num_channels", type=int, default=3, help="Number of color channels") parser.add_argument("--image_size", type=int, default=227, help="Input image size (to crop to)") parser.add_argument("--num_labels", type=int, default=1000, help="Number of labels") parser.add_argument("--batch_size", type=int, default=32, help="Batch size, total over all GPUs.") parser.add_argument("--epoch_size", type=int, default=1500000, help="Number of images/epoch") parser.add_argument("--num_epochs", type=int, default=1000, help="Num epochs.") parser.add_argument("--base_learning_rate", type=float, default=0.1, help="Initial learning rate.") parser.add_argument("--weight_decay", type=float, default=1e-4, help="Weight decay (L2 regularization)") args = parser.parse_args() Train(args) if __name__ == '__main__': workspace.GlobalInit(['caffe2', '--caffe2_log_level=2']) main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/net_builder.py
364
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, context from caffe2.python.task import Task @context.define_context() class NetBuilder(object): """ Scope-driven mechanism for building nets, loops and conditional blocks. Example: from caffe2.python.net_builder import NetBuilder, ops with NetBuilder() as nb: c = ops.Const(5) d = ops.Const(0) with ops.loop(): ops.stop_if(ops.LE([c, ops.Const(0)])) ops.Add([c, ops.Const(-1)], [c]) with ops.If(ops.GE([c, ops.Const(3)])): ops.Add([d, ops.Const(10)]) ops.Print(c, []) ops.Print(d, []) step = core.to_execution_step(nb) """ def __init__(self, name=None, _stop_blob_required=False): self._name = name or '' self._prefix = name + '/' if name else '' self._frozen = False self._current_net = None self._children = [] self._stop_blob = None self._stop_blob_required = _stop_blob_required def stop_blob(self): """ Returns the BlobReference to the stop_blob of this NetBuilder. If one is not yet available, creates one. This function assumes that the stop_blob() will be used immediatelly in the current net, so it doesn't initialize it if the current net is the first of the builder. """ if self._stop_blob is None: net = self.current_net() self._stop_blob = core.BlobReference( net.NextName('stop_blob'), net=net) if self._current_net != self._children[0]: self._children.insert(0, core.Net( self._prefix + 'stop_blob_init')) self._children[0].Const(False, blob_out=self._stop_blob) return self._stop_blob def stop_if(self, blob): ops.Copy(blob, self.stop_blob()) self._current_net = None def _assert_mutable(self): assert not self._frozen, ( 'This NetBuilder (%s) has been built already.' % self._name) def add(self, child): self._assert_mutable() self._current_net = None self._children.append(child) # to-do : check it's not a dag net if isinstance(child, core.Net): self._current_net = child return child def current_net(self): self._assert_mutable() if self._current_net is None: self.add(core.Net(self._prefix + 'net')) return self._current_net def freeze(self): for child in self._children: if hasattr(child, 'freeze'): child.freeze() self._current_net = None self._frozen = True def get(self): self.freeze() return self._children def __exit__(self, etype, *args): self.freeze() if etype is not None: return assert (not self._stop_blob_required) or self._stop_blob is not None, ( 'This NetBuilder (%s) requires a stop condition ' % self._name + 'to be set with `stop` or `stop_if`') class Operations(object): """ Operations to be used in the context of a NetBuilder. """ def net(self, net=None): """ Retrieves the current net, or add a new net to the builder. """ if net is not None: NetBuilder.current().add(net) return net return NetBuilder.current().current_net() def __getattr__(self, op_type): """ Adds an operator call to the currently active Net. """ if op_type.startswith('__'): raise AttributeError() return getattr(self.net(), op_type) def task_group(self): """ Creates a local task group which will execute as the next step of the current NetBuilder. """ from caffe2.python import task group = NetBuilder.current() with task.Cluster(): with task.Node('local'): tg = task.TaskGroup() group.add(tg) return tg def stop(self): """ Stop execution of the current execution step. Example: ops.Print(a, 0) ops.stop() ops.Print(b, 0) In the example, 'b' will never be printed. """ return self.stop_if(ops.Const(True)) def stop_if(self, blob): """ Stop execution of the current execution step if the condition `blob` is met. Example: ops.Print(a, 0) ops.stop_if(ops.LE([x, ops.Const(0)])) ops.Print(b, 0) In the example, 'b' will only be printed if the value of scalar tensor 'x' lower or equal to 0. """ return NetBuilder.current().stop_if(blob) def loop(self, iters=None): """ Creates a NetBuilder that will execute in a loop as the next step of the current NetBuilder. If `iters` is provided, the loop will execute for `iters` iterations and then stop. `iters` can be a constant or a BlobReference. If `iters` is not provided, the loop will execute until `ops.stop` or `ops.stop_if` is called. Examples: a = ops.Const(5) with ops.loop(): ops.stop_if(ops.LE([a, ops.Const(0)])) ops.Print(a, 0) ops.Add([a, ops.Const(-1)], [a]) Above, 'a' will be printed 5 times, with values 5 to 1. with ops.loop(10) as loop: ops.LogInfo(loop.iter()) This will print the numbers from 0 to 9. x = ops.Add([ops.Const(10), ops.Const(10)]) with ops.loop(x) as loop: ops.LogInfo(loop.iter()) This will print the numbers from 0 to 19. """ return NetBuilder.current().add(_Loop(iters)) def stop_guard(self, has_stopped_blob=None): """ Creates a NetBuilder that will execute once as the next step of the current NetBuilder. After execution, a bool tensor will indicate whether the inner execution was halted with `stop` or `stop_if`. Example: a = ops.Const(True) with ops.stop_guard() as sg1: ops.stop_if(a) ops.Print(ops.Const('did not stop')) b = ops.Const(False) with ops.stop_guard() as sg2: ops.stop_if(b) ops.Print(ops.Const('did not stop')) ops.Print(sg1.has_stopped(), []) ops.Print(sg2.has_stopped(), []) In the example, 'did not stop' will be printed once, followed by True and False. """ return NetBuilder.current().add( _StopGuard(has_stopped_blob=has_stopped_blob)) def If(self, cond): """ Creates a NetBuilder that will execute once as the next step of the current NetBuilder if the blob `cond` is True. Example: with ops.If(ops.Const(True)): ops.Print(ops.Const('Will print')) with ops.If(ops.Const(False)): ops.Print(ops.Const('Wont print')) The example will print 'Will print' once. """ return NetBuilder.current().add(_RunIf(cond)) def task_init(self): """ Defines operations that will be executed once at task startup. Useful when implementing processors, that don't have access to the Task top-level structure. Example: def my_processor(rec): with ops.task_init(): one = ops.Const(1) two = ops.Const(1) return Tuple( ops.Add(rec[0](), zero), ops.Add(rec[1](), two)) """ setup = _SetupBuilder(_SetupBuilder.INIT) self.net().add_attribute(Task.TASK_SETUP, setup) return NetBuilder.current().add(setup) def task_exit(self): """ Define operations to be executed at task shutdown. Useful when implementing processors, that don't have access to the Task top-level structure. Example: def read_queue(queue): with ops.task_exit(): queue.close(ops.net()) return queue.read(ops.net()) """ setup = _SetupBuilder(_SetupBuilder.EXIT) self.net().add_attribute(Task.TASK_SETUP, setup) return NetBuilder.current().add(setup) ops = Operations() class _SetupBuilder(NetBuilder): INIT = 'init' EXIT = 'exit' def __init__(self, type, name=None): NetBuilder.__init__(self, name) self.type = type def setup(self, net): if self.type == _SetupBuilder.INIT: return core.to_execution_step(self) def exit(self, net): if self.type == _SetupBuilder.EXIT: return core.to_execution_step(self) class _RunOnce(NetBuilder): def __init__(self, name=None): NetBuilder.__init__(self, name) def __exit__(self, etype, *args): if etype is None and self._stop_blob is not None: ops.stop() NetBuilder.__exit__(self, etype, *args) class _StopGuard(_RunOnce): def __init__(self, name=None, has_stopped_blob=None): _RunOnce.__init__(self, name) self._stopped = has_stopped_blob self._ran = False def __enter__(self): r = _RunOnce.__enter__(self) self._stopped = ops.Const(True, blob_out=self._stopped) return r def __exit__(self, etype, *args): if etype is None: self._ran = True ops.Const(False, blob_out=self._stopped) _RunOnce.__exit__(self, etype, *args) def has_stopped(self): """ Return a blob that will be set to scalar bool `True` after this net builder ran, iff it was halted early. """ assert self._ran, 'Context not used yet.' return self._stopped class _Loop(NetBuilder): def __init__(self, iters=None, name=None): NetBuilder.__init__(self, name, _stop_blob_required=True) if iters is not None: self._inc = ops.Const(1) self._iter = ops.Const(0) self._num_iters = ( iters if isinstance(iters, core.BlobReference) else ops.Const(iters)) else: self._num_iters = None def iter(self): assert self._num_iters is not None, ( 'This loop does not have a number of iterations.') assert self._iter is not None, ( 'iter() must be called from inside the loop context') return self._iter def __enter__(self): builder = NetBuilder.__enter__(self) if self._num_iters is not None: ops.stop_if(ops.GE([self._iter, self._num_iters])) return builder def __exit__(self, type, *args): if type is None and self._num_iters is not None: self.current_net().Add([self._iter, self._inc], [self._iter]) NetBuilder.__exit__(self, type, *args) class _RunIf(_RunOnce): def __init__(self, cond_blob=None, name=None, _already_ran=None): _RunOnce.__init__(self, name) assert cond_blob or _already_ran self._is_else = cond_blob is None if _already_ran is None: self._else_blob = ops.Not(cond_blob) self._already_ran = ops.Const(False) else: self._already_ran = _already_ran self._else_blob = _already_ran if cond_blob is None else ( ops.Or([_already_ran, ops.Not(cond_blob)])) def __enter__(self): r = _RunOnce.__enter__(self) ops.stop_if(self._else_blob) ops.Const(True, blob_out=self._already_ran) return r def Elif(self, cond): assert not self._is_else, 'Else not allowed for an Else.' return NetBuilder.current().add( _RunIf(cond, _already_ran=self._already_ran)) def Else(self): assert not self._is_else, 'Elif not allowed for an Else.' return NetBuilder.current().add( _RunIf(_already_ran=self._already_ran))
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/experiments/python/convnet_benchmarks.py
683
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals """ Benchmark for common convnets. (NOTE: Numbers below prior with missing parameter=update step, TODO to update) Speed on Titan X, with 10 warmup steps and 10 main steps and with different versions of cudnn, are as follows (time reported below is per-batch time, forward / forward+backward): CuDNN V3 CuDNN v4 AlexNet 32.5 / 108.0 27.4 / 90.1 OverFeat 113.0 / 342.3 91.7 / 276.5 Inception 134.5 / 485.8 125.7 / 450.6 VGG (batch 64) 200.8 / 650.0 164.1 / 551.7 Speed on Inception with varied batch sizes and CuDNN v4 is as follows: Batch Size Speed per batch Speed per image 16 22.8 / 72.7 1.43 / 4.54 32 38.0 / 127.5 1.19 / 3.98 64 67.2 / 233.6 1.05 / 3.65 128 125.7 / 450.6 0.98 / 3.52 Speed on Tesla M40, which 10 warmup steps and 10 main steps and with cudnn v4, is as follows: AlexNet 68.4 / 218.1 OverFeat 210.5 / 630.3 Inception 300.2 / 1122.2 VGG (batch 64) 405.8 / 1327.7 (Note that these numbers involve a "full" backprop, i.e. the gradient with respect to the input image is also computed.) To get the numbers, simply run: for MODEL in AlexNet OverFeat Inception; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 128 --model $MODEL --forward_only True done for MODEL in AlexNet OverFeat Inception; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 128 --model $MODEL done PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 64 --model VGGA --forward_only True PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 64 --model VGGA for BS in 16 32 64 128; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size $BS --model Inception --forward_only True PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size $BS --model Inception done Note that VGG needs to be run at batch 64 due to memory limit on the backward pass. """ import argparse import time from caffe2.python import cnn, workspace, core import caffe2.python.SparseTransformer as SparseTransformer def MLP(order): model = cnn.CNNModelHelper() d = 256 depth = 20 width = 3 for i in range(depth): for j in range(width): current = "fc_{}_{}".format(i, j) if i > 0 else "data" next_ = "fc_{}_{}".format(i + 1, j) model.FC( current, next_, dim_in=d, dim_out=d, weight_init=model.XavierInit, bias_init=model.XavierInit) model.Sum(["fc_{}_{}".format(depth, j) for j in range(width)], ["sum"]) model.FC("sum", "last", dim_in=d, dim_out=1000, weight_init=model.XavierInit, bias_init=model.XavierInit) xent = model.LabelCrossEntropy(["last", "label"], "xent") model.AveragedLoss(xent, "loss") return model, d def AlexNet(order): model = cnn.CNNModelHelper(order, name="alexnet", use_cudnn=True, cudnn_exhaustive_search=True) conv1 = model.Conv( "data", "conv1", 3, 64, 11, ('XavierFill', {}), ('ConstantFill', {}), stride=4, pad=2 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=3, stride=2) conv2 = model.Conv( pool1, "conv2", 64, 192, 5, ('XavierFill', {}), ('ConstantFill', {}), pad=2 ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=3, stride=2) conv3 = model.Conv( pool2, "conv3", 192, 384, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = model.Relu(conv3, "conv3") conv4 = model.Conv( relu3, "conv4", 384, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = model.Relu(conv4, "conv4") conv5 = model.Conv( relu4, "conv5", 256, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = model.Relu(conv5, "conv5") pool5 = model.MaxPool(relu5, "pool5", kernel=3, stride=2) fc6 = model.FC( pool5, "fc6", 256 * 6 * 6, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu6 = model.Relu(fc6, "fc6") fc7 = model.FC( relu6, "fc7", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu7 = model.Relu(fc7, "fc7") fc8 = model.FC( relu7, "fc8", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = model.Softmax(fc8, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") model.AveragedLoss(xent, "loss") return model, 224 def OverFeat(order): model = cnn.CNNModelHelper(order, name="overfeat", use_cudnn=True, cudnn_exhaustive_search=True) conv1 = model.Conv( "data", "conv1", 3, 96, 11, ('XavierFill', {}), ('ConstantFill', {}), stride=4 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=2, stride=2) conv2 = model.Conv( pool1, "conv2", 96, 256, 5, ('XavierFill', {}), ('ConstantFill', {}) ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=2, stride=2) conv3 = model.Conv( pool2, "conv3", 256, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = model.Relu(conv3, "conv3") conv4 = model.Conv( relu3, "conv4", 512, 1024, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = model.Relu(conv4, "conv4") conv5 = model.Conv( relu4, "conv5", 1024, 1024, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = model.Relu(conv5, "conv5") pool5 = model.MaxPool(relu5, "pool5", kernel=2, stride=2) fc6 = model.FC( pool5, "fc6", 1024 * 6 * 6, 3072, ('XavierFill', {}), ('ConstantFill', {}) ) relu6 = model.Relu(fc6, "fc6") fc7 = model.FC( relu6, "fc7", 3072, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu7 = model.Relu(fc7, "fc7") fc8 = model.FC( relu7, "fc8", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = model.Softmax(fc8, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") model.AveragedLoss(xent, "loss") return model, 231 def VGGA(order): model = cnn.CNNModelHelper(order, name='vgg-a', use_cudnn=True, cudnn_exhaustive_search=True) conv1 = model.Conv( "data", "conv1", 3, 64, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=2, stride=2) conv2 = model.Conv( pool1, "conv2", 64, 128, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=2, stride=2) conv3 = model.Conv( pool2, "conv3", 128, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = model.Relu(conv3, "conv3") conv4 = model.Conv( relu3, "conv4", 256, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = model.Relu(conv4, "conv4") pool4 = model.MaxPool(relu4, "pool4", kernel=2, stride=2) conv5 = model.Conv( pool4, "conv5", 256, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = model.Relu(conv5, "conv5") conv6 = model.Conv( relu5, "conv6", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu6 = model.Relu(conv6, "conv6") pool6 = model.MaxPool(relu6, "pool6", kernel=2, stride=2) conv7 = model.Conv( pool6, "conv7", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu7 = model.Relu(conv7, "conv7") conv8 = model.Conv( relu7, "conv8", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu8 = model.Relu(conv8, "conv8") pool8 = model.MaxPool(relu8, "pool8", kernel=2, stride=2) fcix = model.FC( pool8, "fcix", 512 * 7 * 7, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) reluix = model.Relu(fcix, "fcix") fcx = model.FC( reluix, "fcx", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relux = model.Relu(fcx, "fcx") fcxi = model.FC( relux, "fcxi", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = model.Softmax(fcxi, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") model.AveragedLoss(xent, "loss") return model, 231 def net_DAG_Builder(model): print("====================================================") print(" Start Building DAG ") print("====================================================") net_root = SparseTransformer.netbuilder(model) return net_root def _InceptionModule( model, input_blob, input_depth, output_name, conv1_depth, conv3_depths, conv5_depths, pool_depth ): # path 1: 1x1 conv conv1 = model.Conv( input_blob, output_name + ":conv1", input_depth, conv1_depth, 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv1 = model.Relu(conv1, conv1) # path 2: 1x1 conv + 3x3 conv conv3_reduce = model.Conv( input_blob, output_name + ":conv3_reduce", input_depth, conv3_depths[0], 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv3_reduce = model.Relu(conv3_reduce, conv3_reduce) conv3 = model.Conv( conv3_reduce, output_name + ":conv3", conv3_depths[0], conv3_depths[1], 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) conv3 = model.Relu(conv3, conv3) # path 3: 1x1 conv + 5x5 conv conv5_reduce = model.Conv( input_blob, output_name + ":conv5_reduce", input_depth, conv5_depths[0], 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv5_reduce = model.Relu(conv5_reduce, conv5_reduce) conv5 = model.Conv( conv5_reduce, output_name + ":conv5", conv5_depths[0], conv5_depths[1], 5, ('XavierFill', {}), ('ConstantFill', {}), pad=2 ) conv5 = model.Relu(conv5, conv5) # path 4: pool + 1x1 conv pool = model.MaxPool( input_blob, output_name + ":pool", kernel=3, stride=1, pad=1 ) pool_proj = model.Conv( pool, output_name + ":pool_proj", input_depth, pool_depth, 1, ('XavierFill', {}), ('ConstantFill', {}) ) pool_proj = model.Relu(pool_proj, pool_proj) output = model.Concat([conv1, conv3, conv5, pool_proj], output_name) return output def Inception(order): model = cnn.CNNModelHelper(order, name="inception", use_cudnn=True, cudnn_exhaustive_search=True) conv1 = model.Conv( "data", "conv1", 3, 64, 7, ('XavierFill', {}), ('ConstantFill', {}), stride=2, pad=3 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=3, stride=2, pad=1) conv2a = model.Conv( pool1, "conv2a", 64, 64, 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv2a = model.Relu(conv2a, conv2a) conv2 = model.Conv( conv2a, "conv2", 64, 192, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=3, stride=2, pad=1) # Inception modules inc3 = _InceptionModule( model, pool2, 192, "inc3", 64, [96, 128], [16, 32], 32 ) inc4 = _InceptionModule( model, inc3, 256, "inc4", 128, [128, 192], [32, 96], 64 ) pool5 = model.MaxPool(inc4, "pool5", kernel=3, stride=2, pad=1) inc5 = _InceptionModule( model, pool5, 480, "inc5", 192, [96, 208], [16, 48], 64 ) inc6 = _InceptionModule( model, inc5, 512, "inc6", 160, [112, 224], [24, 64], 64 ) inc7 = _InceptionModule( model, inc6, 512, "inc7", 128, [128, 256], [24, 64], 64 ) inc8 = _InceptionModule( model, inc7, 512, "inc8", 112, [144, 288], [32, 64], 64 ) inc9 = _InceptionModule( model, inc8, 528, "inc9", 256, [160, 320], [32, 128], 128 ) pool9 = model.MaxPool(inc9, "pool9", kernel=3, stride=2, pad=1) inc10 = _InceptionModule( model, pool9, 832, "inc10", 256, [160, 320], [32, 128], 128 ) inc11 = _InceptionModule( model, inc10, 832, "inc11", 384, [192, 384], [48, 128], 128 ) pool11 = model.AveragePool(inc11, "pool11", kernel=7, stride=1) fc = model.FC( pool11, "fc", 1024, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) # It seems that Soumith's benchmark does not have softmax on top # for Inception. We will add it anyway so we can have a proper # backward pass. pred = model.Softmax(fc, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") model.AveragedLoss(xent, "loss") return model, 224 def AddInput(model, batch_size, db, db_type): """Adds the data input part.""" data_uint8, label = model.TensorProtosDBInput( [], ["data_uint8", "label"], batch_size=batch_size, db=db, db_type=db_type ) data = model.Cast(data_uint8, "data_nhwc", to=core.DataType.FLOAT) data = model.NHWC2NCHW(data, "data") data = model.Scale(data, data, scale=float(1. / 256)) data = model.StopGradient(data, data) return data, label def AddParameterUpdate(model): """ Simple plain SGD update -- not tuned to actually train the models """ ITER = model.Iter("iter") LR = model.LearningRate( ITER, "LR", base_lr=-1e-8, policy="step", stepsize=10000, gamma=0.999) ONE = model.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0) for param in model.params: param_grad = model.param_to_grad[param] model.WeightedSum([param, ONE, param_grad, LR], param) def Benchmark(model_gen, arg): model, input_size = model_gen(arg.order) model.Proto().type = arg.net_type model.Proto().num_workers = arg.num_workers # In order to be able to run everything without feeding more stuff, let's # add the data and label blobs to the parameter initialization net as well. if arg.order == "NCHW": input_shape = [arg.batch_size, 3, input_size, input_size] else: input_shape = [arg.batch_size, input_size, input_size, 3] if arg.model == "MLP": input_shape = [arg.batch_size, input_size] model.param_init_net.GaussianFill( [], "data", shape=input_shape, mean=0.0, std=1.0 ) model.param_init_net.UniformIntFill( [], "label", shape=[arg.batch_size, ], min=0, max=999 ) if arg.forward_only: print('{}: running forward only.'.format(arg.model)) else: print('{}: running forward-backward.'.format(arg.model)) model.AddGradientOperators(["loss"]) AddParameterUpdate(model) if arg.order == 'NHWC': print( '==WARNING==\n' 'NHWC order with CuDNN may not be supported yet, so I might\n' 'exit suddenly.' ) if not arg.cpu: model.param_init_net.RunAllOnGPU() model.net.RunAllOnGPU() if arg.dump_model: # Writes out the pbtxt for benchmarks on e.g. Android with open( "{0}_init_batch_{1}.pbtxt".format(arg.model, arg.batch_size), "w" ) as fid: fid.write(str(model.param_init_net.Proto())) with open("{0}.pbtxt".format(arg.model, arg.batch_size), "w") as fid: fid.write(str(model.net.Proto())) workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net) for i in range(arg.warmup_iterations): workspace.RunNet(model.net.Proto().name) plan = core.Plan("plan") plan.AddStep(core.ExecutionStep("run", model.net, arg.iterations)) start = time.time() workspace.RunPlan(plan) print('Spent: {}'.format((time.time() - start) / arg.iterations)) if arg.layer_wise_benchmark: print('Layer-wise benchmark.') workspace.BenchmarkNet(model.net.Proto().name, 1, arg.iterations, True) def GetArgumentParser(): parser = argparse.ArgumentParser(description="Caffe2 benchmark.") parser.add_argument( "--batch_size", type=int, default=128, help="The batch size." ) parser.add_argument("--model", type=str, help="The model to benchmark.") parser.add_argument( "--order", type=str, default="NCHW", help="The order to evaluate." ) parser.add_argument( "--cudnn_ws", type=int, default=-1, help="The cudnn workspace size." ) parser.add_argument( "--iterations", type=int, default=10, help="Number of iterations to run the network." ) parser.add_argument( "--warmup_iterations", type=int, default=10, help="Number of warm-up iterations before benchmarking." ) parser.add_argument( "--forward_only", action='store_true', help="If set, only run the forward pass." ) parser.add_argument( "--layer_wise_benchmark", action='store_true', help="If True, run the layer-wise benchmark as well." ) parser.add_argument( "--cpu", action='store_true', help="If True, run testing on CPU instead of GPU." ) parser.add_argument( "--dump_model", action='store_true', help="If True, dump the model prototxts to disk." ) parser.add_argument("--net_type", type=str, default="dag") parser.add_argument("--num_workers", type=int, default=2) return parser if __name__ == '__main__': args = GetArgumentParser().parse_args() if ( not args.batch_size or not args.model or not args.order or not args.cudnn_ws ): GetArgumentParser().print_help() workspace.GlobalInit(['caffe2', '--caffe2_log_level=0']) model_map = { 'AlexNet': AlexNet, 'OverFeat': OverFeat, 'VGGA': VGGA, 'Inception': Inception, 'MLP': MLP, } Benchmark(model_map[args.model], args)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/dataio.py
334
""" Defines the base interface for reading and writing operations. Readers/Writers are objects that produce operations that read/write sequences of data. Each operation reads or writes a list of BlobReferences. Readers and Writers must be implemented such that read and write operations are atomic and thread safe. Examples of possible Readers and Writers: HiveReader, HiveWriter, QueueReader, QueueWriter, DatasetReader, DatasetWriter, DBReader, DBWriter, See `dataset.py` for an example of implementation. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from caffe2.python.schema import Field, Struct, from_blob_list import numpy as np class Reader(object): def __init__(self, schema=None): if schema is not None: assert isinstance(schema, Field) self._schema = schema def schema(self): """ Return the schema associated with the Hive Reader """ assert self._schema is not None, 'Schema not provided for this reader.' return self._schema def _set_schema(self, schema): self._schema = schema def setup_ex(self, init_net, finish_net): """Nets to be executed once at startup and finish. Experimental extension. Don't use yet""" pass def read_ex(self, local_init_net, local_finish_net): """Experimental extension to the interface. Don't use yet""" read_net = core.Net('reader_body') return ([read_net], ) + self.read(read_net) def read_record_ex(self, local_init_net, local_finish_net): """Experimental extension to the interface. Don't use yet""" nets, should_stop, fields = self.read_ex( local_init_net, local_finish_net) if self._schema: fields = from_blob_list(self._schema, fields) return nets, should_stop, fields """ Reader is a abstract class to be implemented in order to provide operations capable of iterating through a dataset or stream of data. A Reader must implement at least one operation, `read`, which adds operations to a net that read the next batch of data. Readers can optionally support the `reset` operation, which is useful when multiple passes over the data are required. """ def read(self, read_net): """ Add operations to read_net that will read the read batch of data and return a list of BlobReference representing the blobs that will contain the batches produced. Operations added to `read_net` must be thread safe and atomic, that is, it should be possible to clone `read_net` and run multiple instances of it in parallel. Args: read_net: the net that will be appended with read operations Returns: A tuple (should_stop, fields), with: should_stop: BlobReference pointing to a boolean scalar blob that indicates whether the read operation was succesfull or whether the end of data has been reached. fields: A tuple of BlobReference containing the latest batch of data that was read. """ raise NotImplementedError('Readers must implement `read`.') def reset(self, net): """Append operations to `net` that will reset the reader. This can be used to read the data multiple times. Not all readers support this operation. """ raise NotImplementedError('This reader cannot be resetted.') def read_record(self, read_net): should_stop, fields = self.read(read_net) if self._schema: fields = from_blob_list(self._schema, fields) return should_stop, fields def execution_step(self, reader_net_name=None): """Create an execution step with a net containing read operators. The execution step will contain a `stop_blob` that knows how to stop the execution loop when end of data was reached. E.g.: read_step, fields = reader.execution_step() consume_net = core.Net('consume') consume_net.Print(fields[0], []) p = core.Plan('reader') p.AddStep(read_step.AddNet(consume_net)) core.RunPlan(p) Args: reader_net_name: (optional) the name of the reader_net to be created. The execution step will be named accordingly. Returns: A tuple (read_step, fields), with: read_step: A newly created execution step containing a net with read operations. The step will have `stop_blob` set, in order to stop the loop on end of data. fields: A tuple of BlobReference containing the latest batch of data that was read. """ reader_net = core.Net(reader_net_name or 'reader') should_stop, fields = self.read_record(reader_net) read_step = core.execution_step( '{}_step'.format(reader_net_name), reader_net, should_stop_blob=should_stop) return (read_step, fields) class Writer(object): """ Writer is a abstract class to be implemented in order to provide operations capable of feeding a data stream or a dataset. A Writer must implement 2 operations: `write`, which adds operations to a net that write the write batch of data, and `commit`, which adds operations to a net in order to indicate that no more data will be written. """ _schema = None def schema(self): return self._schema def write(self, writer_net, fields): """Add operations to `writer_net` that write the next batch of data. Operations added to the net must be thread-safe and unique, that is: multiple writers must be able to write to the dataset in parallel. Args: fields: a tuple of BlobReference containing the batch of data to write. """ raise NotImplementedError('Writers must implement write.') def write_record(self, writer_net, fields): if isinstance(fields, Field): self._schema = fields fields = fields.field_blobs() self.write(writer_net, fields) def setup_ex(self, init_net, finish_net): """Experimental, don't use yet""" self.commit(finish_net) def write_ex(self, fields, local_init_net, local_finish_net, stop_blob): """Experimental extension to the interface. Don't use yet""" write_net = core.Net('write_net') self.write(write_net, fields) return [write_net] def write_record_ex( self, fields, local_init_net, local_finish_net, stop_blob=None): """Experimental extension to the interface. Don't use yet.""" if isinstance(fields, Field): self._schema = fields fields = fields.field_blobs() if stop_blob is None: stop_blob = local_init_net.NextName("dequeue_status") write_nets = self.write_ex( fields, local_init_net, local_finish_net, stop_blob) return (write_nets, stop_blob) def commit(self, finish_net): """Add operations to `finish_net` that signal end of data. This must be implemented by all Writers, but may be no-op for some of them. """ pass class ReaderBuilder(object): """ Allow usage of a reader in distributed fashion. """ def schema(self): raise NotImplementedError() def enqueue_splits(self, net, split_queue): raise NotImplementedError() def splits(self, net): raise NotImplementedError() def new_reader(self, split_queue): raise NotImplementedError() class Pipe(object): def __init__(self, schema=None, obj_key=None): self._num_writers = 0 self._num_readers = 0 self._schema = schema self._obj_key = obj_key def schema(self): return self._schema def setup(self, global_init_net): pass def reader(self): raise NotImplementedError() def writer(self): raise NotImplementedError() def num_readers(self): return self._num_readers def num_writers(self): return self._num_writers def _new_writer(self, writer_schema, writer_init_net): if writer_schema is not None and self._schema is None: self._schema = writer_schema self._num_writers += 1 if self._obj_key is not None: writer_init_net.add_attribute(self._obj_key, self) def _new_reader(self, reader_init_net): self._num_readers += 1 if self._obj_key is not None: reader_init_net.add_attribute(self._obj_key, self) class CounterReader(Reader): """ Reader that produces increasing integers. """ def __init__(self): Reader.__init__(self, schema=Struct(('iter', np.int64))) self.counter = None self.should_stop = None def setup_ex(self, global_init_net, global_finish_net): if self.counter is None: self.counter = global_init_net.CreateCounter([], init_count=0) self.should_stop = global_init_net.ConstantFill( [], shape=[], dtype=core.DataType.BOOL, value=False) def read_ex(self, local_init_net, local_finish_net): count_net = core.Net('limited_reader_counter') value = count_net.CountUp([self.counter], 1) return [count_net], self.should_stop, [value] class ReaderWithLimit(Reader): """ Reader that stops after `num_iter` calls. """ def __init__(self, reader, num_iter=1): Reader.__init__(self, schema=reader._schema) self.reader = reader self.counter = None self.num_iter = num_iter net = core.Net('reader_with_limit') self._data_finished = net.AddExternalInput( net.NextName('data_finished')) self.counter = net.AddExternalInput(net.NextName('counter')) def setup_ex(self, global_init_net, global_finish_net): global_init_net.CreateCounter( [], [self.counter], init_count=int(self.num_iter)) self.reader.setup_ex(global_init_net, global_finish_net) global_init_net.ConstantFill( [], [self._data_finished], shape=[], value=False, dtype=core.DataType.BOOL) def read_ex(self, local_init_net, local_finish_net): """ 1. check if we reached number of iterations """ count_net = core.Net('limited_reader_counter') should_stop = count_net.CountDown([self.counter], 1) """ 2. call original reader """ nets, local_data_finished, fields = self.reader.read_ex( local_init_net, local_finish_net) self._set_schema(self.reader._schema) """ 3. check if original reader is done. """ check_done_net = core.Net('limited_reader_post') check_done_net.Copy(local_data_finished, should_stop) check_done_net.Copy([local_data_finished], [self._data_finished]) # this relies on `should_stop` being called after each net. return [count_net] + nets + [check_done_net], should_stop, fields def data_finished(self): """ Return a blob that can be checked after the end of the reading task, which will contain a scalar float indicating whether the underlying reader has been exhausted (True) or whether we stopped because reached the limit of iterations (False). """ return self._data_finished def CountUntil(num_iter): return ReaderWithLimit(CounterReader(), num_iter)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/hsm_test.py
250
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import given import numpy as np import unittest from caffe2.proto import caffe2_pb2, hsm_pb2 from caffe2.python import workspace, core, gradient_checker import caffe2.python.hypothesis_test_util as hu import caffe2.python.hsm_util as hsmu # User inputs tree using protobuf file or, in this case, python utils # The hierarchy in this test looks as shown below. Note that the final subtrees # (with word_ids as leaves) have been collapsed for visualization # * # / \ # * 5,6,7,8 # / \ # 0,1,2 3,4 tree = hsm_pb2.TreeProto() words = [[0, 1, 2], [3, 4], [5, 6, 7, 8]] node1 = hsmu.create_node_with_words(words[0], "node1") node2 = hsmu.create_node_with_words(words[1], "node2") node3 = hsmu.create_node_with_words(words[2], "node3") node4 = hsmu.create_node_with_nodes([node1, node2], "node4") node = hsmu.create_node_with_nodes([node4, node3], "node5") tree.root_node.MergeFrom(node) # structure: # node5: [0, 2, ["node4", "node3"]] # offset, length, "node4, node3" # node4: [2, 2, ["node1", "node2"]] # node1: [4, 3, [0, 1 ,2]] # node2: [7, 2, [3, 4] # node3: [9, 4, [5, 6, 7, 8] struct = [[0, 2, ["node4", "node3"], "node5"], [2, 2, ["node1", "node2"], "node4"], [4, 3, [0, 1, 2], "node1"], [7, 2, [3, 4], "node2"], [9, 4, [5, 6, 7, 8], "node3"]] # Internal util to translate input tree to list of (word_id,path). serialized # hierarchy is passed into the operator_def as a string argument, hierarchy_proto = hsmu.create_hierarchy(tree) arg = caffe2_pb2.Argument() arg.name = "hierarchy" arg.s = hierarchy_proto.SerializeToString() beam = 5 args_search = [] arg_search = caffe2_pb2.Argument() arg_search.name = "tree" arg_search.s = tree.SerializeToString() args_search.append(arg_search) arg_search = caffe2_pb2.Argument() arg_search.name = "beam" arg_search.f = beam args_search.append(arg_search) class TestHsm(hu.HypothesisTestCase): def test_hsm_search(self): samples = 10 dim_in = 5 X = np.random.rand(samples, dim_in).astype(np.float32) - 0.5 w = np.random.rand(hierarchy_proto.size, dim_in) \ .astype(np.float32) - 0.5 b = np.random.rand(hierarchy_proto.size).astype(np.float32) - 0.5 labels = np.array([np.random.randint(0, 8) for i in range(samples)]) \ .astype(np.int32) workspace.GlobalInit(['caffe2']) workspace.FeedBlob("data", X) workspace.FeedBlob("weights", w) workspace.FeedBlob("bias", b) workspace.FeedBlob("labels", labels) op = core.CreateOperator( 'HSoftmaxSearch', ['data', 'weights', 'bias'], ['names', 'scores'], 'HSoftmaxSearch', arg=args_search) workspace.RunOperatorOnce(op) names = workspace.FetchBlob('names') scores = workspace.FetchBlob('scores') def simulation_hsm_search(): names = [] scores = [] for line in struct: s, e = line[0], line[0] + line[1] score = np.dot(X, w[s:e].transpose()) + b[s:e] score = np.exp(score - np.max(score, axis=1, keepdims=True)) score /= score.sum(axis=1, keepdims=True) score = -np.log(score) score = score.transpose() idx = -1 for j, n in enumerate(names): if n == line[3]: idx = j score += scores[j] if idx == -1: score[score > beam] = np.inf else: score[score - scores[idx] > beam] = np.inf for i, name in enumerate(line[2]): scores.append(score[i]) names.append(name) scores = np.vstack(scores) return names, scores.transpose() p_names, p_scores = simulation_hsm_search() idx = np.argsort(p_scores, axis=1) p_scores = np.sort(p_scores, axis=1) p_names = np.array(p_names)[idx] for i in range(names.shape[0]): for j in range(names.shape[1]): if names[i][j]: assert(names[i][j] == p_names[i][j]) self.assertAlmostEqual( scores[i][j], p_scores[i][j], delta=0.001) def test_hsm_run_once(self): workspace.GlobalInit(['caffe2']) workspace.FeedBlob("data", np.random.randn(1000, 100).astype(np.float32)) workspace.FeedBlob("weights", np.random.randn(1000, 100).astype(np.float32)) workspace.FeedBlob("bias", np.random.randn(1000).astype(np.float32)) workspace.FeedBlob("labels", np.random.rand(1000).astype(np.int32) * 9) op = core.CreateOperator( 'HSoftmax', ['data', 'weights', 'bias', 'labels'], ['output', 'intermediate_output'], 'HSoftmax', arg=[arg]) self.assertTrue(workspace.RunOperatorOnce(op)) # Test to check value of sum of squared losses in forward pass for given # input def test_hsm_forward(self): cpu_device_option = caffe2_pb2.DeviceOption() grad_checker = gradient_checker.GradientChecker( 0.01, 0.05, cpu_device_option, "default") samples = 9 dim_in = 5 X = np.zeros((samples, dim_in)).astype(np.float32) + 1 w = np.zeros((hierarchy_proto.size, dim_in)).astype(np.float32) + 1 b = np.array([i for i in range(hierarchy_proto.size)])\ .astype(np.float32) labels = np.array([i for i in range(samples)]).astype(np.int32) workspace.GlobalInit(['caffe2']) workspace.FeedBlob("data", X) workspace.FeedBlob("weights", w) workspace.FeedBlob("bias", b) workspace.FeedBlob("labels", labels) op = core.CreateOperator( 'HSoftmax', ['data', 'weights', 'bias', 'labels'], ['output', 'intermediate_output'], 'HSoftmax', arg=[arg]) grad_ops, g_input = core.GradientRegistry.GetGradientForOp( op, [s + '_grad' for s in op.output]) loss, _ = grad_checker.GetLossAndGrad( op, grad_ops, X, op.input[0], g_input[0], [0] ) self.assertAlmostEqual(loss, 44.269, delta=0.001) # Test to compare gradient calculated using the gradient operator and the # symmetric derivative calculated using Euler Method # TODO : convert to both cpu and gpu test when ready. @given(**hu.gcs_cpu_only) def test_hsm_gradient(self, gc, dc): samples = 10 dim_in = 5 X = np.random.rand(samples, dim_in).astype(np.float32) - 0.5 w = np.random.rand(hierarchy_proto.size, dim_in) \ .astype(np.float32) - 0.5 b = np.random.rand(hierarchy_proto.size).astype(np.float32) - 0.5 labels = np.array([np.random.randint(0, 8) for i in range(samples)]) \ .astype(np.int32) workspace.GlobalInit(['caffe2']) workspace.FeedBlob("data", X) workspace.FeedBlob("weights", w) workspace.FeedBlob("bias", b) workspace.FeedBlob("labels", labels) op = core.CreateOperator( 'HSoftmax', ['data', 'weights', 'bias', 'labels'], ['output', 'intermediate_output'], 'HSoftmax', arg=[arg]) self.assertDeviceChecks(dc, op, [X, w, b, labels], [0]) for i in range(3): self.assertGradientChecks(gc, op, [X, w, b, labels], i, [0]) def test_huffman_tree_hierarchy(self): workspace.GlobalInit(['caffe2']) labelSet = range(0, 6) counts = [1, 2, 3, 4, 5, 6] labels = sum([[l] * c for (l, c) in zip(labelSet, counts)], []) Y = np.array(labels).astype(np.int64) workspace.FeedBlob("labels", Y) arg = caffe2_pb2.Argument() arg.name = 'num_classes' arg.i = 6 op = core.CreateOperator( 'HuffmanTreeHierarchy', ['labels'], ['huffman_tree'], 'HuffmanTreeHierarchy', arg=[arg]) workspace.RunOperatorOnce(op) huffmanTreeOutput = workspace.FetchBlob('huffman_tree') treeOutput = hsm_pb2.TreeProto() treeOutput.ParseFromString(huffmanTreeOutput[0]) treePathOutput = hsmu.create_hierarchy(treeOutput) label_to_path = {} for path in treePathOutput.paths: label_to_path[path.word_id] = path def checkPath(label, indices, code): path = label_to_path[label] self.assertEqual(len(path.path_nodes), len(code)) self.assertEqual(len(path.path_nodes), len(code)) for path_node, index, target in \ zip(path.path_nodes, indices, code): self.assertEqual(path_node.index, index) self.assertEqual(path_node.target, target) checkPath(0, [0, 4, 6, 8], [1, 0, 0, 0]) checkPath(1, [0, 4, 6, 8], [1, 0, 0, 1]) checkPath(2, [0, 4, 6], [1, 0, 1]) checkPath(3, [0, 2], [0, 0]) checkPath(4, [0, 2], [0, 1]) checkPath(5, [0, 4], [1, 1]) if __name__ == '__main__': unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/model_helper.py
328
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, scope import numpy as np import logging class ParameterType(object): DENSE = 'dense' SPARSE = 'sparse' class ParameterInfo(object): def __init__( self, param_id, param, key=None, shape=None, length=None): assert isinstance(param, core.BlobReference) self.param_id = param_id self.name = str(param) self.blob = param self.key = key self.shape = shape self.size = None if shape is None else np.prod(shape) self.length = max(1, length if length is not None else 1) self.grad = None self._cloned_init_net = None def grad_type(self): # self.grad could be None for model parallelism with parameter server if self.grad is None: return return ( ParameterType.SPARSE if isinstance(self.grad, core.GradientSlice) else ParameterType.DENSE) def cloned_init_net(self): if not self._cloned_init_net: init_net, outputs = self.blob.Net().ClonePartial( 'param_%d_%s_init' % (self.param_id, self.name), inputs=[], outputs=[self.blob]) self._cloned_init_net = (init_net, outputs[0]) return self._cloned_init_net def __str__(self): return self.name class ModelHelperBase(object): """A helper model so we can write models more easily, without having to manually define parameter initializations and operators separately. In order to add support for specific operators, inherit from this class and add corresponding methods. Operator representing methods should take care of adding their parameters to params """ def __init__(self, name=None, init_params=True, allow_not_known_ops=True, skip_sparse_optim=False, param_model=None): self.name = name or "model" self.net = core.Net(self.name) if param_model is not None: self.param_init_net = param_model.param_init_net self.param_to_grad = param_model.param_to_grad self.params = param_model.params self.computed_params = param_model.computed_params else: self.param_init_net = core.Net(name + '_init') self.param_to_grad = {} self.params = [] self.computed_params = [] self._param_info = [] self._devices = [] self.gradient_ops_added = False self.init_params = init_params self.allow_not_known_ops = allow_not_known_ops self.skip_sparse_optim = skip_sparse_optim def _infer_param_shape(self, param): for op in self.param_init_net.Proto().op: if str(param) in op.output: for arg in op.arg: if arg.name == "shape": return list(arg.ints) return None def _update_param_info(self): assert len(self._param_info) <= len(self.params) for param in self.params[len(self._param_info):]: if not isinstance(param, core.BlobReference): param = core.BlobReference(str(param), net=self._param_init_net) self._param_info.append(ParameterInfo( param_id=len(self._param_info), param=param, shape=self._infer_param_shape(param))) for info in self._param_info: info.grad = self.param_to_grad.get(info.name) def add_param(self, param, key=None, shape=None, length=None): self._update_param_info() if key is not None and self.net.input_record() is not None: idx = self.net.input_record().field_blobs().index(key) key = self.net.input_record().field_names()[idx] shape = shape if shape is not None else self._infer_param_shape(param) self.params.append(param) if not isinstance(param, core.BlobReference): param = core.BlobReference(str(param), net=self._param_init_net) self._param_info.append(ParameterInfo( param_id=len(self._param_info), param=param, shape=shape, key=key, length=length, )) return self._param_info[-1] def param_info(self, grad_type=None, id=None): self._update_param_info() if id is not None: assert grad_type is None info = self._param_info[id] assert info.param_id == id return info elif grad_type is not None: return [ info for info in self._param_info if info.grad_type() == grad_type] else: return self._param_info def GetParams(self, namescope=None): ''' Returns the params in current namescope ''' if namescope is None: namescope = scope.CurrentNameScope() else: if not namescope.endswith(scope._NAMESCOPE_SEPARATOR): namescope += scope._NAMESCOPE_SEPARATOR if namescope == '': return self.params[:] else: return [p for p in self.params if p.GetNameScope() == namescope] def Proto(self): return self.net.Proto() def InitProto(self): return self.param_init_net.Proto() def RunAllOnGPU(self, *args, **kwargs): self.param_init_net.RunAllOnGPU(*args, **kwargs) self.net.RunAllOnGPU(*args, **kwargs) def CreateDB(self, blob_out, db, db_type, **kwargs): dbreader = self.param_init_net.CreateDB( [], blob_out, db=db, db_type=db_type, **kwargs) return dbreader def AddGradientOperators(self, *args, **kwargs): if self.gradient_ops_added: raise RuntimeError("You cannot run AddGradientOperators twice.") self.gradient_ops_added = True self.grad_map = self.net.AddGradientOperators(*args, **kwargs) self.param_to_grad = self.get_param_to_grad(self.params) return self.grad_map def get_param_to_grad(self, params): ''' Given a list of parameters returns a dict from a parameter to a corresponding gradient ''' param_to_grad = {} if not self.gradient_ops_added: raise RuntimeError("You need to run AddGradientOperators first.") # We need to use empty namescope when creating the gradients # to prevent duplicating the namescope prefix for gradient blobs. for p in params: if str(p) in self.grad_map: param_to_grad[p] = self.grad_map[str(p)] return param_to_grad def GetOptimizationPairs(self, params=None): ''' Returns a map for param => grad. If params is not specified, all parameters will be considered. ''' if not self.gradient_ops_added: raise RuntimeError("Need to call AddGradientOperators first") param_to_grad = self.param_to_grad if params: param_to_grad = self.get_param_to_grad(params) if not self.skip_sparse_optim: return param_to_grad else: return {param: grad for param, grad in param_to_grad.items() if not isinstance(grad, core.GradientSlice)} def GetComputedParams(self, namescope=None): ''' Returns the computed params in current namescope. 'Computed params' are such parameters that are not optimized via gradient descent but are directly computed from data, such as the running mean and variance of Spatial Batch Normalization. ''' if namescope is None: namescope = scope.CurrentNameScope() else: if not namescope.endswith(scope._NAMESCOPE_SEPARATOR): namescope += scope._NAMESCOPE_SEPARATOR if namescope == '': return self.computed_params[:] else: return [p for p in self.computed_params if p.GetNameScope() == namescope] def GetAllParams(self, namescope=None): return self.GetParams(namescope) + self.GetComputedParams(namescope) def TensorProtosDBInput( self, unused_blob_in, blob_out, batch_size, db, db_type, **kwargs ): """TensorProtosDBInput.""" dbreader_name = "dbreader_" + db dbreader = self.param_init_net.CreateDB( [], dbreader_name, db=db, db_type=db_type) return self.net.TensorProtosDBInput( dbreader, blob_out, batch_size=batch_size) def AddOperator(self, op_type, inputs, parameters, *args, **kwargs): """ Adds an operator to a model. Use parameters list to specify which operator inputs are model parameters to be optimized. Example of usage: model.SparseLengthsSum( [embedding, indices, lengths], parameters=[embedding], ) Here embedding is a parameter to be optimized while indices and lengths are not. """ extra_parameters = filter(lambda x: (x not in inputs), parameters) if len(extra_parameters) > 0: raise Exception("Some parameters are not inputs: {}".format( map(str, extra_parameters) )) self.params.extend(parameters) return self.net.__getattr__(op_type)(inputs, *args, **kwargs) def GetDevices(self): assert len(self._devices) > 0, \ "Use data_parallel_model to run model on multiple GPUs." return self._devices def __getattr__(self, op_type): """Catch-all for all other operators, mostly those without params.""" if op_type.startswith('__'): raise AttributeError(op_type) if not core.IsOperator(op_type): raise RuntimeError( 'Method ' + op_type + ' is not a registered operator.' ) # known_working_ops are operators that do not need special care. known_working_ops = [ "Accuracy", "Adam", "Add", "Adagrad", "SparseAdagrad", "AveragedLoss", "Cast", "Checkpoint", "ConstantFill", "CopyGPUToCPU", "CopyCPUToGPU", "DequeueBlobs", "EnsureCPUOutput", "Flatten", "FlattenToVec", "LabelCrossEntropy", "LearningRate", "MakeTwoClass", "MatMul", "NCCLAllreduce", "NHWC2NCHW", "PackSegments", "Print", "PRelu", "Scale", "ScatterWeightedSum", "Sigmoid", "SortedSegmentSum", "Snapshot", # Note: snapshot is deprecated, use Checkpoint "Softmax", "SoftmaxWithLoss", "SquaredL2Distance", "Squeeze", "StopGradient", "Summarize", "Tanh", "UnpackSegments", "WeightedSum", ] if op_type not in known_working_ops: if not self.allow_not_known_ops: raise RuntimeError( "Operator {} is not known to be safe".format(op_type)) logging.warning("You are creating an op that the ModelHelperBase " "does not recognize: {}.".format(op_type)) return self.net.__getattr__(op_type)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/contrib/nccl/nccl_ops_test.py
172
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import unittest import hypothesis.strategies as st from hypothesis import given, assume import numpy as np import time import os from caffe2.proto import caffe2_pb2 from caffe2.python import core, workspace, muji, dyndep import caffe2.python.hypothesis_test_util as hu np.random.seed(1) dyndep.InitOpsLibrary('@/caffe2/caffe2/contrib/nccl:nccl_ops') def gpu_device(i): device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CUDA device_option.cuda_gpu_id = i return device_option def benchmark(ws, net, warmups=5, iters=100): for _ in range(warmups): ws.run(net) plan = core.Plan("plan") plan.AddStep(core.ExecutionStep("test-step", net, iters)) before = time.time() ws.run(plan) after = time.time() print("Timing network, time taken per-iteration: {:.6f}ms".format(( after - before) / float(iters) * 1000.0)) return after - before @unittest.skipIf(not workspace.has_gpu_support, "NCCL only on GPU") class NCCLOpsTest(hu.HypothesisTestCase): @given(n=st.integers(min_value=2, max_value=workspace.NumCudaDevices()), m=st.integers(min_value=1, max_value=1000), in_place=st.booleans()) def test_nccl_allreduce(self, n, m, in_place): xs = [np.random.randn(m).astype(np.float32) for i in range(n)] inputs = [str("x_{}".format(i)) for i in range(n)] prefix = "" if in_place else "o" outputs = [str("{}x_{}".format(prefix, i)) for i in range(n)] op = core.CreateOperator("NCCLAllreduce", inputs, outputs) input_device_options = {n: gpu_device(i) for i, n in enumerate(inputs)} def allreduce(*args): assert len(args) == n output = np.sum(args, axis=0) return [output for _ in range(n)] outputs = self.assertReferenceChecks( hu.gpu_do, op, [xs[i] for i, _ in enumerate(inputs)], allreduce, input_device_options) for output in outputs: np.testing.assert_array_equal(outputs[0], output) self.assertEqual(outputs[0].tobytes(), output.tobytes()) @given(n=st.integers(min_value=2, max_value=workspace.NumCudaDevices()), m=st.integers(min_value=1, max_value=1000), root=st.integers(min_value=0, max_value=workspace.NumCudaDevices() - 1)) def test_nccl_broadcast(self, n, m, root): assume(root < n) xs = [np.random.randn(m).astype(np.float32) for i in range(n)] inputs = [str("x_{}".format(i)) for i in range(n)] op = core.CreateOperator("NCCLBroadcast", inputs, inputs, root=root) input_device_options = {n: gpu_device(i) for i, n in enumerate(inputs)} def broadcast(*args): assert len(args) == n return [args[root] for _ in range(n)] self.assertReferenceChecks( hu.gpu_do, op, [xs[i] for i, _ in enumerate(inputs)], broadcast, input_device_options) @given(n=st.integers(min_value=2, max_value=workspace.NumCudaDevices()), m=st.integers(min_value=1, max_value=1000), # NCCL Reduce seems to deadlock for non-zero roots. root=st.integers(min_value=0, max_value=0), in_place=st.booleans()) def test_nccl_reduce(self, n, m, root, in_place): assume(in_place is False or root == 0) xs = [np.random.randn(m).astype(np.float32) for i in range(n)] inputs = [str("x_{}".format(i)) for i in range(n)] op = core.CreateOperator( "NCCLReduce", inputs, inputs[root] if in_place else b"o", root=root) input_device_options = {n: gpu_device(i) for i, n in enumerate(inputs)} def reduce(*args): assert len(args) == n return [np.sum(args, axis=0)] self.assertReferenceChecks( hu.gpu_do, op, [xs[i] for i, _ in enumerate(inputs)], reduce, input_device_options) @given(n=st.integers(min_value=2, max_value=workspace.NumCudaDevices()), m=st.integers(min_value=1, max_value=1000)) def test_nccl_allgather(self, n, m): xs = [np.random.randn(m).astype(np.float32) for i in range(n)] inputs = [str("x_{}".format(i)) for i in range(n)] outputs = [str("o_{}".format(i)) for i in range(n)] op = core.CreateOperator("NCCLAllGather", inputs, outputs) input_device_options = {n: gpu_device(i) for i, n in enumerate(inputs)} def allgather(*args): assert len(args) == n return [np.stack(args, axis=0) for _ in range(n)] outputs = self.assertReferenceChecks( hu.gpu_do, op, [xs[i] for i, _ in enumerate(inputs)], allgather, input_device_options) for output in outputs: np.testing.assert_array_equal(outputs[0], output) self.assertEqual(outputs[0].tobytes(), output.tobytes()) @given(n=st.integers(min_value=2, max_value=workspace.NumCudaDevices()), m=st.integers(min_value=100000, max_value=100000), iters=st.integers(min_value=1, max_value=100), net_type=st.sampled_from(["dag", "async_dag", "simple"])) def test_nccl_sync(self, n, m, iters, net_type): inputs = [str("x_{}".format(i)) for i in range(n)] extra_inputs = [str("xe_{}".format(i)) for i in range(n)] net = core.Net("asdf") net.Proto().type = net_type net.Proto().num_workers = n for i in range(n): net.ConstantFill([], inputs[i], shape=[m], value=0.0, device_option=gpu_device(i)) net.ConstantFill([], extra_inputs[i], shape=[m], value=1.0, device_option=gpu_device(i)) for _ in range(iters): net.Sum([inputs[i], extra_inputs[i]], [inputs[i]], device_option=gpu_device(i)) net.NCCLReduce(inputs, [inputs[0]], device_option=gpu_device(0)) self.ws.run(net) np.testing.assert_array_equal( self.ws.blobs[inputs[0]].fetch(), np.full(shape=(m,), fill_value=iters * n, dtype=np.float32)) @unittest.skipIf(not os.environ.get("CAFFE2_BENCHMARK"), "Benchmark") def test_timings(self): for n in range(2, workspace.NumCudaDevices()): for in_place in [False, True]: xs = [np.random.randn(1e7).astype(np.float32) for i in range(n)] inputs = [str("x_{}".format(i)) for i in range(n)] prefix = "" if in_place else "o" outputs = [str("{}x_{}".format(prefix, i)) for i in range(n)] net = core.Net("test") net.NCCLAllreduce(inputs, outputs) net.RunAllOnGPU() for i in range(n): self.ws.create_blob(inputs[i]).feed(xs[i], gpu_device(i)) self.ws.run(net) net_time = benchmark(self.ws, net) vanilla = core.Net("vanilla") muji.Allreduce(vanilla, inputs) vanilla_time = benchmark(self.ws, vanilla) print("Speedup for NCCL: {:.2f}".format( vanilla_time / net_time))
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/convnet_benchmarks.py
658
""" Benchmark for common convnets. Speed on Titan X, with 10 warmup steps and 10 main steps and with different versions of cudnn, are as follows (time reported below is per-batch time, forward / forward+backward): CuDNN V3 CuDNN v4 AlexNet 32.5 / 108.0 27.4 / 90.1 OverFeat 113.0 / 342.3 91.7 / 276.5 Inception 134.5 / 485.8 125.7 / 450.6 VGG (batch 64) 200.8 / 650.0 164.1 / 551.7 Speed on Inception with varied batch sizes and CuDNN v4 is as follows: Batch Size Speed per batch Speed per image 16 22.8 / 72.7 1.43 / 4.54 32 38.0 / 127.5 1.19 / 3.98 64 67.2 / 233.6 1.05 / 3.65 128 125.7 / 450.6 0.98 / 3.52 Speed on Tesla M40, which 10 warmup steps and 10 main steps and with cudnn v4, is as follows: AlexNet 68.4 / 218.1 OverFeat 210.5 / 630.3 Inception 300.2 / 1122.2 VGG (batch 64) 405.8 / 1327.7 (Note that these numbers involve a "full" backprop, i.e. the gradient with respect to the input image is also computed.) To get the numbers, simply run: for MODEL in AlexNet OverFeat Inception; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 128 --model $MODEL --forward_only True done for MODEL in AlexNet OverFeat Inception; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 128 --model $MODEL done PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 64 --model VGGA --forward_only True PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size 64 --model VGGA for BS in 16 32 64 128; do PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size $BS --model Inception --forward_only True PYTHONPATH=../gen:$PYTHONPATH python convnet_benchmarks.py \ --batch_size $BS --model Inception done Note that VGG needs to be run at batch 64 due to memory limit on the backward pass. """ import argparse from caffe2.python import cnn, workspace def MLP(order): model = cnn.CNNModelHelper() d = 256 depth = 20 width = 3 for i in range(depth): for j in range(width): current = "fc_{}_{}".format(i, j) if i > 0 else "data" next_ = "fc_{}_{}".format(i + 1, j) model.FC( current, next_, dim_in=d, dim_out=d, weight_init=model.XavierInit, bias_init=model.XavierInit) model.Sum(["fc_{}_{}".format(depth, j) for j in range(width)], ["sum"]) model.FC("sum", "last", dim_in=d, dim_out=1000, weight_init=model.XavierInit, bias_init=model.XavierInit) xent = model.LabelCrossEntropy(["last", "label"], "xent") model.AveragedLoss(xent, "loss") return model, d def AlexNet(order): model = cnn.CNNModelHelper( order, name="alexnet", use_cudnn=True, cudnn_exhaustive_search=True) conv1 = model.Conv( "data", "conv1", 3, 64, 11, ('XavierFill', {}), ('ConstantFill', {}), stride=4, pad=2 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=3, stride=2) conv2 = model.Conv( pool1, "conv2", 64, 192, 5, ('XavierFill', {}), ('ConstantFill', {}), pad=2 ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=3, stride=2) conv3 = model.Conv( pool2, "conv3", 192, 384, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = model.Relu(conv3, "conv3") conv4 = model.Conv( relu3, "conv4", 384, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = model.Relu(conv4, "conv4") conv5 = model.Conv( relu4, "conv5", 256, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = model.Relu(conv5, "conv5") pool5 = model.MaxPool(relu5, "pool5", kernel=3, stride=2) fc6 = model.FC( pool5, "fc6", 256 * 6 * 6, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu6 = model.Relu(fc6, "fc6") fc7 = model.FC( relu6, "fc7", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu7 = model.Relu(fc7, "fc7") fc8 = model.FC( relu7, "fc8", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = model.Softmax(fc8, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") loss = model.AveragedLoss(xent, "loss") return model, 224 def OverFeat(order): model = cnn.CNNModelHelper( order, name="overfeat", use_cudnn=True, cudnn_exhaustive_search=True) conv1 = model.Conv( "data", "conv1", 3, 96, 11, ('XavierFill', {}), ('ConstantFill', {}), stride=4 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=2, stride=2) conv2 = model.Conv( pool1, "conv2", 96, 256, 5, ('XavierFill', {}), ('ConstantFill', {}) ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=2, stride=2) conv3 = model.Conv( pool2, "conv3", 256, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = model.Relu(conv3, "conv3") conv4 = model.Conv( relu3, "conv4", 512, 1024, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = model.Relu(conv4, "conv4") conv5 = model.Conv( relu4, "conv5", 1024, 1024, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = model.Relu(conv5, "conv5") pool5 = model.MaxPool(relu5, "pool5", kernel=2, stride=2) fc6 = model.FC( pool5, "fc6", 1024 * 6 * 6, 3072, ('XavierFill', {}), ('ConstantFill', {}) ) relu6 = model.Relu(fc6, "fc6") fc7 = model.FC( relu6, "fc7", 3072, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu7 = model.Relu(fc7, "fc7") fc8 = model.FC( relu7, "fc8", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = model.Softmax(fc8, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") loss = model.AveragedLoss(xent, "loss") return model, 231 def VGGA(order): model = cnn.CNNModelHelper( order, name='vgg-a', use_cudnn=True, cudnn_exhaustive_search=True) conv1 = model.Conv( "data", "conv1", 3, 64, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=2, stride=2) conv2 = model.Conv( pool1, "conv2", 64, 128, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=2, stride=2) conv3 = model.Conv( pool2, "conv3", 128, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = model.Relu(conv3, "conv3") conv4 = model.Conv( relu3, "conv4", 256, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = model.Relu(conv4, "conv4") pool4 = model.MaxPool(relu4, "pool4", kernel=2, stride=2) conv5 = model.Conv( pool4, "conv5", 256, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = model.Relu(conv5, "conv5") conv6 = model.Conv( relu5, "conv6", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu6 = model.Relu(conv6, "conv6") pool6 = model.MaxPool(relu6, "pool6", kernel=2, stride=2) conv7 = model.Conv( pool6, "conv7", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu7 = model.Relu(conv7, "conv7") conv8 = model.Conv( relu7, "conv8", 512, 512, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu8 = model.Relu(conv8, "conv8") pool8 = model.MaxPool(relu8, "pool8", kernel=2, stride=2) fcix = model.FC( pool8, "fcix", 512 * 7 * 7, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) reluix = model.Relu(fcix, "fcix") fcx = model.FC( reluix, "fcx", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relux = model.Relu(fcx, "fcx") fcxi = model.FC( relux, "fcxi", 4096, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) pred = model.Softmax(fcxi, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") loss = model.AveragedLoss(xent, "loss") return model, 231 def _InceptionModule( model, input_blob, input_depth, output_name, conv1_depth, conv3_depths, conv5_depths, pool_depth ): # path 1: 1x1 conv conv1 = model.Conv( input_blob, output_name + ":conv1", input_depth, conv1_depth, 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv1 = model.Relu(conv1, conv1) # path 2: 1x1 conv + 3x3 conv conv3_reduce = model.Conv( input_blob, output_name + ":conv3_reduce", input_depth, conv3_depths[0], 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv3_reduce = model.Relu(conv3_reduce, conv3_reduce) conv3 = model.Conv( conv3_reduce, output_name + ":conv3", conv3_depths[0], conv3_depths[1], 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) conv3 = model.Relu(conv3, conv3) # path 3: 1x1 conv + 5x5 conv conv5_reduce = model.Conv( input_blob, output_name + ":conv5_reduce", input_depth, conv5_depths[0], 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv5_reduce = model.Relu(conv5_reduce, conv5_reduce) conv5 = model.Conv( conv5_reduce, output_name + ":conv5", conv5_depths[0], conv5_depths[1], 5, ('XavierFill', {}), ('ConstantFill', {}), pad=2 ) conv5 = model.Relu(conv5, conv5) # path 4: pool + 1x1 conv pool = model.MaxPool( input_blob, output_name + ":pool", kernel=3, stride=1, pad=1 ) pool_proj = model.Conv( pool, output_name + ":pool_proj", input_depth, pool_depth, 1, ('XavierFill', {}), ('ConstantFill', {}) ) pool_proj = model.Relu(pool_proj, pool_proj) output = model.Concat([conv1, conv3, conv5, pool_proj], output_name) return output def Inception(order): model = cnn.CNNModelHelper( order, name="inception", use_cudnn=True, cudnn_exhaustive_search=True) conv1 = model.Conv( "data", "conv1", 3, 64, 7, ('XavierFill', {}), ('ConstantFill', {}), stride=2, pad=3 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=3, stride=2, pad=1) conv2a = model.Conv( pool1, "conv2a", 64, 64, 1, ('XavierFill', {}), ('ConstantFill', {}) ) conv2a = model.Relu(conv2a, conv2a) conv2 = model.Conv( conv2a, "conv2", 64, 192, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=3, stride=2, pad=1) # Inception modules inc3 = _InceptionModule( model, pool2, 192, "inc3", 64, [96, 128], [16, 32], 32 ) inc4 = _InceptionModule( model, inc3, 256, "inc4", 128, [128, 192], [32, 96], 64 ) pool5 = model.MaxPool(inc4, "pool5", kernel=3, stride=2, pad=1) inc5 = _InceptionModule( model, pool5, 480, "inc5", 192, [96, 208], [16, 48], 64 ) inc6 = _InceptionModule( model, inc5, 512, "inc6", 160, [112, 224], [24, 64], 64 ) inc7 = _InceptionModule( model, inc6, 512, "inc7", 128, [128, 256], [24, 64], 64 ) inc8 = _InceptionModule( model, inc7, 512, "inc8", 112, [144, 288], [32, 64], 64 ) inc9 = _InceptionModule( model, inc8, 528, "inc9", 256, [160, 320], [32, 128], 128 ) pool9 = model.MaxPool(inc9, "pool9", kernel=3, stride=2, pad=1) inc10 = _InceptionModule( model, pool9, 832, "inc10", 256, [160, 320], [32, 128], 128 ) inc11 = _InceptionModule( model, inc10, 832, "inc11", 384, [192, 384], [48, 128], 128 ) pool11 = model.AveragePool(inc11, "pool11", kernel=7, stride=1) fc = model.FC( pool11, "fc", 1024, 1000, ('XavierFill', {}), ('ConstantFill', {}) ) # It seems that Soumith's benchmark does not have softmax on top # for Inception. We will add it anyway so we can have a proper # backward pass. pred = model.Softmax(fc, "pred") xent = model.LabelCrossEntropy([pred, "label"], "xent") loss = model.AveragedLoss(xent, "loss") return model, 224 def AddParameterUpdate(model): """ Simple plain SGD update -- not tuned to actually train the models """ ITER = model.Iter("iter") LR = model.LearningRate( ITER, "LR", base_lr=-1e-8, policy="step", stepsize=10000, gamma=0.999) ONE = model.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0) for param in model.params: param_grad = model.param_to_grad[param] model.WeightedSum([param, ONE, param_grad, LR], param) def Benchmark(model_gen, arg): model, input_size = model_gen(arg.order) model.Proto().type = arg.net_type model.Proto().num_workers = arg.num_workers # In order to be able to run everything without feeding more stuff, let's # add the data and label blobs to the parameter initialization net as well. if arg.order == "NCHW": input_shape = [arg.batch_size, 3, input_size, input_size] else: input_shape = [arg.batch_size, input_size, input_size, 3] if arg.model == "MLP": input_shape = [arg.batch_size, input_size] model.param_init_net.GaussianFill( [], "data", shape=input_shape, mean=0.0, std=1.0 ) model.param_init_net.UniformIntFill( [], "label", shape=[arg.batch_size, ], min=0, max=999 ) if arg.forward_only: print('{}: running forward only.'.format(arg.model)) else: print('{}: running forward-backward.'.format(arg.model)) model.AddGradientOperators(["loss"]) AddParameterUpdate(model) if arg.order == 'NHWC': print( '==WARNING==\n' 'NHWC order with CuDNN may not be supported yet, so I might\n' 'exit suddenly.' ) if not arg.cpu: model.param_init_net.RunAllOnGPU() model.net.RunAllOnGPU() if arg.engine: for op in model.net.Proto().op: op.engine = arg.engine if arg.dump_model: # Writes out the pbtxt for benchmarks on e.g. Android with open( "{0}_init_batch_{1}.pbtxt".format(arg.model, arg.batch_size), "w" ) as fid: fid.write(str(model.param_init_net.Proto())) with open("{0}.pbtxt".format(arg.model, arg.batch_size), "w") as fid: fid.write(str(model.net.Proto())) workspace.RunNetOnce(model.param_init_net) workspace.CreateNet(model.net) workspace.BenchmarkNet( model.net.Proto().name, arg.warmup_iterations, arg.iterations, arg.layer_wise_benchmark) def GetArgumentParser(): parser = argparse.ArgumentParser(description="Caffe2 benchmark.") parser.add_argument( "--batch_size", type=int, default=128, help="The batch size." ) parser.add_argument("--model", type=str, help="The model to benchmark.") parser.add_argument( "--order", type=str, default="NCHW", help="The order to evaluate." ) parser.add_argument( "--cudnn_ws", type=int, default=-1, help="The cudnn workspace size." ) parser.add_argument( "--iterations", type=int, default=10, help="Number of iterations to run the network." ) parser.add_argument( "--warmup_iterations", type=int, default=10, help="Number of warm-up iterations before benchmarking." ) parser.add_argument( "--forward_only", action='store_true', help="If set, only run the forward pass." ) parser.add_argument( "--layer_wise_benchmark", action='store_true', help="If True, run the layer-wise benchmark as well." ) parser.add_argument( "--cpu", action='store_true', help="If True, run testing on CPU instead of GPU." ) parser.add_argument( "--engine", type=str, default="", help="If set, blindly prefer the given engine(s) for every op.") parser.add_argument( "--dump_model", action='store_true', help="If True, dump the model prototxts to disk." ) parser.add_argument("--net_type", type=str, default="dag") parser.add_argument("--num_workers", type=int, default=2) parser.add_argument("--use-nvtx", default=False, action='store_true') parser.add_argument("--htrace_span_log_path", type=str) return parser if __name__ == '__main__': args = GetArgumentParser().parse_args() if ( not args.batch_size or not args.model or not args.order or not args.cudnn_ws ): GetArgumentParser().print_help() workspace.GlobalInit( ['caffe2', '--caffe2_log_level=0'] + (['--caffe2_use_nvtx'] if args.use_nvtx else []) + (['--caffe2_htrace_span_log_path=' + args.htrace_span_log_path] if args.htrace_span_log_path else [])) model_map = { 'AlexNet': AlexNet, 'OverFeat': OverFeat, 'VGGA': VGGA, 'Inception': Inception, 'MLP': MLP, } Benchmark(model_map[args.model], args)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/recurrent.py
256
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from caffe2.python.cnn import CNNModelHelper def recurrent_net( net, cell_net, inputs, initial_cell_inputs, links, scratch_sizes, timestep=None, scope=None ): ''' net: the main net operator should be added to cell_net: cell_net which is executed in a recurrent fasion inputs: sequences to be fed into the recurrent net. Currently only one input is supported. It has to be in a format T x N x (D1...Dk) where T is lengths of the sequence. N is a batch size and (D1...Dk) are the rest of dimentions initial_cell_inputs: inputs of the cell_net for the 0 timestamp. Format for each input is: (cell_net_input_name, external_blob_with_data) links: a dictionary from cell_net input names in moment t+1 and output names of moment t. Currently we assume that each output becomes an input for the next timestep. scratch_sizes: sizes of the scratch blobs. Scratch blobs are those intermidiate blobs of the cell_net which are used in backward pass. We use sizes iformation to preallocate memory for them over time. For example in case of LSTM we have FC -> Sum ->LSTMUnit sequence of operations in each iteration of the cell net. Output of Sum is an intermidiate blob. Also it is going to be part of the backward pass. Thus it is a scratch blob size of which we must to pvovide. timestep: name of the timestep blob to be used. If not provided "timestep" is used. scope: Internal blobs are going to be scoped in a format <scope_name>/<blob_name> If not provided we generate a scope name automatically ''' assert len(inputs) == 1, "Only one input blob is supported so far" input_blobs = [str(i[0]) for i in inputs] initial_input_blobs = [str(x[1]) for x in initial_cell_inputs] op_name = net.NextName('recurrent') def s(name): # We have to manually scope due to our internal/external blob # relationships. scope_name = op_name if scope is None else scope return "{}/{}".format(str(scope_name), str(name)) # determine inputs that are considered to be references # it is those that are not referred to in inputs or initial_cell_inputs known_inputs = map(str, input_blobs + initial_input_blobs) known_inputs += [str(x[0]) for x in initial_cell_inputs] if timestep is not None: known_inputs.append(str(timestep)) references = [ b for b in cell_net.Proto().external_input if b not in known_inputs] inner_outputs = list(cell_net.Proto().external_output) # These gradients are expected to be available during the backward pass inner_outputs_map = {o: o + '_grad' for o in inner_outputs} # compute the backward pass of the cell net backward_ops, backward_mapping = core.GradientRegistry.GetBackwardPass( cell_net.Proto().op, inner_outputs_map) backward_mapping = {str(k): str(v) for k, v in backward_mapping.items()} backward_cell_net = core.Net("RecurrentBackwardStep") del backward_cell_net.Proto().op[:] backward_cell_net.Proto().op.extend(backward_ops) # compute blobs used but not defined in the backward pass ssa, _ = core.get_ssa(backward_cell_net.Proto()) undefined = core.get_undefined_blobs(ssa) # also add to the output list the intermediate outputs of fwd_step that # are used by backward. ssa, blob_versions = core.get_ssa(cell_net.Proto()) scratches = [ blob for (blob, ver) in blob_versions.items() if ver > 0 and blob in undefined and blob not in cell_net.Proto().external_output] backward_cell_net.Proto().external_input.extend(scratches) all_inputs = [i[1] for i in inputs] + [ x[1] for x in initial_cell_inputs] + references all_outputs = [] cell_net.Proto().type = 'simple' backward_cell_net.Proto().type = 'simple' # Internal arguments used by RecurrentNetwork operator # Links are in the format blob_name, recurrent_states, offset. # In the moment t we know that corresponding data block is at # t + offset position in the recurrent_states tensor forward_links = [] backward_links = [] # Aliases are used to expose outputs to external world # Format (internal_blob, external_blob, offset) # Negative offset stands for going from the end, # positive - from the beginning aliases = [] # States held inputs to the cell net recurrent_states = [] for cell_input, _ in initial_cell_inputs: cell_input = str(cell_input) # Recurrent_states is going to be (T + 1) x ... # It stores all inputs and outputs of the cell net over time. # Or their gradients in the case of the backward pass. state = s(cell_input + "_states") states_grad = state + "_grad" cell_output = links[str(cell_input)] forward_links.append((cell_input, state, 0)) forward_links.append((cell_output, state, 1)) backward_links.append((cell_input + "_grad", states_grad, 0)) backward_links.append((cell_output + "_grad", states_grad, 1)) backward_cell_net.Proto().external_input.append( str(cell_output) + "_grad") aliases.append((state, cell_output + "_last", -1)) aliases.append((state, cell_output + "_all", 1)) all_outputs.extend([cell_output + "_all", cell_output + "_last"]) recurrent_states.append(state) for input_id, (input_t, input_blob) in enumerate(inputs): forward_links.append((str(input_t), str(input_blob), 0)) backward_links.append(( backward_mapping[str(input_t)], str(input_blob) + "_grad", 0 )) backward_cell_net.Proto().external_input.extend( cell_net.Proto().external_input) backward_cell_net.Proto().external_input.extend( cell_net.Proto().external_output) def unpack_triple(x): if x: a, b, c = zip(*x) return a, b, c return [], [], [] # Splitting to separate lists so we can pass them to c++ # where we ensemle them back link_internal, link_external, link_offset = unpack_triple(forward_links) backward_link_internal, backward_link_external, backward_link_offset = \ unpack_triple(backward_links) alias_src, alias_dst, alias_offset = unpack_triple(aliases) params = [x for x in references if x in backward_mapping.keys()] recurrent_inputs = [str(x[1]) for x in initial_cell_inputs] results = net.RecurrentNetwork( all_inputs, all_outputs + [s("step_workspaces")], param=map(all_inputs.index, params), alias_src=alias_src, alias_dst=map(str, alias_dst), alias_offset=alias_offset, recurrent_states=recurrent_states, recurrent_inputs=recurrent_inputs, recurrent_input_ids=map(all_inputs.index, recurrent_inputs), link_internal=map(str, link_internal), link_external=map(str, link_external), link_offset=link_offset, backward_link_internal=map(str, backward_link_internal), backward_link_external=map(str, backward_link_external), backward_link_offset=backward_link_offset, step_net=str(cell_net.Proto()), backward_step_net=str(backward_cell_net.Proto()), timestep="timestep" if timestep is None else str(timestep), ) # The last output is a list of step workspaces, # which is only needed internally for gradient propogation return results[:-1] def LSTM(model, input_blob, seq_lengths, initial_states, dim_in, dim_out, scope): ''' Adds a standard LSTM recurrent network operator to a model. model: ModelHelperBase object new operators would be added to input_blob: the input sequence in a format T x N x D where T is sequence size, N - batch size and D - input dimention seq_lengths: blob containing sequence lengths which would be passed to LSTMUnit operator initial_states: a tupple of (hidden_input_blob, cell_input_blob) which are going to be inputs to the cell net on the first iteration dim_in: input dimention dim_out: output dimention ''' def s(name): # We have to manually scope due to our internal/external blob # relationships. return "{}/{}".format(str(scope), str(name)) """ initial bulk fully-connected """ input_blob = model.FC( input_blob, s('i2h'), dim_in=dim_in, dim_out=4 * dim_out, axis=2) """ the step net """ step_model = CNNModelHelper(name='lstm_cell', param_model=model) input_t, timestep, cell_t_prev, hidden_t_prev = ( step_model.net.AddExternalInputs( 'input_t', 'timestep', 'cell_t_prev', 'hidden_t_prev')) gates_t = step_model.FC( hidden_t_prev, s('gates_t'), dim_in=dim_out, dim_out=4 * dim_out, axis=2) step_model.net.Sum([gates_t, input_t], gates_t) hidden_t, cell_t = step_model.net.LSTMUnit( [cell_t_prev, gates_t, seq_lengths, timestep], ['hidden_t', 'cell_t'], ) step_model.net.AddExternalOutputs(cell_t, hidden_t) """ recurrent network """ (hidden_input_blob, cell_input_blob) = initial_states output, last_output, all_states, last_state = recurrent_net( net=model.net, cell_net=step_model.net, inputs=[(input_t, input_blob)], initial_cell_inputs=[ (hidden_t_prev, hidden_input_blob), (cell_t_prev, cell_input_blob), ], links={ hidden_t_prev: hidden_t, cell_t_prev: cell_t, }, timestep=timestep, scratch_sizes=[dim_out * 4], scope=scope, ) return output, last_output, all_states, last_state
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/experiments/python/train.py
331
""" Benchmark for ads based model. To run a benchmark with full forward-backward-update, do e.g. OMP_NUM_THREADS=8 _build/opt/caffe2/caffe2/fb/ads/train_cpu.lpar \ --batchSize 100 \ --hidden 128-64-32 \ --loaderConfig /mnt/vol/gfsdataswarm-global/namespaces/ads/fblearner/users/ \ dzhulgakov/caffe2/tests/test_direct_loader.config For more details, run with --help. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function # TODO(jiayq): breaks Caffe2, need to investigate # from __future__ import unicode_literals from caffe2.python import workspace, cnn, core from caffe2.python.fb.models.mlp import ( mlp, mlp_decomp, mlp_prune, sparse_mlp, debug_sparse_mlp, debug_sparse_mlp_decomposition, debug_sparse_mlp_prune, ) from caffe2.python.fb.models.loss import BatchLRLoss from caffe2.python.fb.metrics.metrics import LogScoreReweightedMeasurements from caffe2.python.fb.executor.executor import Trainer from caffe2.python.fb.optimizers.sgd import build_sgd from caffe2.python import net_drawer from caffe2.python import SparseTransformer from collections import namedtuple import os import sys import json import subprocess import logging import numpy as np from libfb import pyinit import hiveio.par_init import fblearner.nn.gen_conf as conf_utils dyndep.InitOpsLibrary('@/caffe2/caffe2/fb/data:reading_ops') hiveio.par_init.install_class_path() for h in logging.root.handlers: h.setFormatter(logging.Formatter( '%(levelname)s %(asctime)s : %(message)s')) logger = logging.getLogger(__name__) logger.setLevel(logging.DEBUG) InputData = namedtuple( 'InputData', ['data', 'label', 'weight', 'prod_pred', 'sparse_segments']) def FakeData(args, model): logger.info('Input dimensions is %d', args.input_dim) workspace.FeedBlob('data', np.random.normal( size=(args.batchSize, args.input_dim)).astype(np.float32)) workspace.FeedBlob('label', np.random.randint( 2, size=args.batchSize).astype(np.int32)) workspace.FeedBlob('weight', np.ones(args.batchSize).astype(np.float32)) sparseBin = 100 workspace.FeedBlob('eid', np.arange(args.batchSize).astype(np.int32)) workspace.FeedBlob('key', np.random.randint( 0, sparseBin, args.batchSize).astype(np.int64)) workspace.FeedBlob('val', np.ones(args.batchSize).astype(np.float32)) sparseSegments = [ { 'size': sparseBin, 'eid': 'eid', 'key': 'key', 'val': 'val', }, ] return InputData(data='data', label='label', weight='weight', prod_pred=None, sparse_segments=sparseSegments) def NNLoaderData(args, model): cfg = conf_utils.loadNNLoaderConfig(args.loaderConfig) loaderConfig = conf_utils.getLoaderConfigFromNNLoaderConfig(cfg) preperConfig = loaderConfig.preperConfig metaFile = preperConfig.metaFile assert metaFile, 'meta data not found' if type(loaderConfig).__name__ == 'LocalDirectLoader': loaderConfig.batchConfig.batchSize = args.batchSize logger.info('Batch size = %d', loaderConfig.batchConfig.batchSize) else: logger.info('Batch size unknown here. will be determined by the reader') logger.info('Parsing meta data %s', metaFile) cmd = 'cat "{}" | {}'.format(metaFile, args.meta2json) meta = json.loads(subprocess.check_output(cmd, shell=True)) args.input_dim = len(meta['denseFeatureNames']) logger.info('Input dimensions is %d', args.input_dim) fields = ['data', 'label', 'weight', 'prod_pred'] sparseSegments = [] if preperConfig.skipSparse or not preperConfig.sparseSegments.segments: logger.info('No sparse features found') else: segments = loaderConfig.preperConfig.sparseSegments.segments logger.info('Found %d sparse segments', len(segments)) sparseFieldNames = ('eid', 'key', 'val', 'size') for i, segment in enumerate(segments): sparseData = ['{}_{}'.format(fn, i) for fn in sparseFieldNames[:3]] fields.extend(sparseData) size = max(sf.mod + sf.offset for sf in segment.inputs) sparseSegments.append( dict(zip(sparseFieldNames, sparseData + [size]))) logger.info('Sparse segment %d: %s', i, sparseSegments[-1]) loader = model.param_init_net.NNLoaderCreate( [], json_config=conf_utils.structToString(cfg)) model.net.NNLoaderRead([loader], fields, add_sparse_bias=True) return InputData(*(fields[:4] + [sparseSegments])) def sparse_transform(model): print("====================================================") print(" Sparse Transformer ") print("====================================================") net_root, net_name2id, net_id2node = SparseTransformer.netbuilder(model) SparseTransformer.Prune2Sparse( net_root, net_id2node, net_name2id, model.net.Proto().op, model) op_list = SparseTransformer.net2list(net_root) del model.net.Proto().op[:] model.net.Proto().op.extend(op_list) def train(model_gen, data_gen, args): model = cnn.CNNModelHelper("NCHW", name="mlp") input_data = data_gen(args, model) logger.info(input_data) batch_loss = model_gen(args, model, input_data) try: print(model.net.Proto()) graph = net_drawer.GetPydotGraph(model.net.Proto().op, 'net', 'TB') netGraphFile = os.path.join( os.path.expanduser('~'), 'public_html/net.png') logger.info('Drawing network to %s', netGraphFile) graph.write(netGraphFile, format='png') except Exception as err: logger.error('Failed to draw net: %s', err) # Add gradients model.AddGradientOperators([batch_loss.loss]) if model.net.Proto().op[-1].output[-1] == 'data_grad': logger.info('Skipping grad for data') del model.net.Proto().op[-1].output[-1] build_sgd(model, base_learning_rate=args.rateOfLearning, policy="inv", gamma=args.learnRateDecay, power=args.learnRatePower) if args.seed: logger.info('Setting random seed to %d', args.seed) model.param_init_net._net.device_option.CopyFrom( core.DeviceOption(0, 0, random_seed=args.seed)) if args.gpu: model.param_init_net.RunAllOnGPU() model.net.RunAllOnGPU() if args.net_type: model.net.Proto().type = args.net_type model.net.Proto().num_workers = args.num_workers trainer = Trainer( model, epoch_size=args.epochSize // args.batchSize, num_threads=args.numThreads, num_epochs=args.maxEpoch, reporter=LogScoreReweightedMeasurements( batch_loss, input_data.weight, args.negDownsampleRate, args.batchSize, args.last_n_stats)) trainer.run(args.maxEpoch) print(model.net.Proto()) sparse_transform(model) print(model.net.Proto()) workspace.RunNetOnce(model.net) def mlp_model(args, model, input_data): hiddens = [int(s) for s in args.hidden.split('-')] + [2] sums = mlp(model, input_data.data, args.input_dim, hiddens) return BatchLRLoss(model, sums, input_data.label) def mlp_decomp_model(args, model, input_data): hiddens = [int(s) for s in args.hidden.split('-')] + [2] sums = mlp_decomp(model, input_data.data, args.input_dim, hiddens) return BatchLRLoss(model, sums, input_data.label) def mlp_prune_model(args, model, input_data): hiddens = [int(s) for s in args.hidden.split('-')] + [2] sums = mlp_prune(model, input_data.data, args.input_dim, hiddens, prune_thres=args.prune_thres, comp_lb=args.compress_lb) return BatchLRLoss(model, sums, input_data.label) def sparse_mlp_model(args, model, input_data): hiddens = [int(s) for s in args.hidden.split('-')] + [2] sums = sparse_mlp(model, input_data.data, args.input_dim, hiddens, input_data.sparse_segments) return BatchLRLoss(model, sums, input_data.label) def debug_sparse_mlp_model(args, model, input_data): hiddens = [int(s) for s in args.hidden.split('-')] + [2] sums = debug_sparse_mlp(model, input_data.data, args.input_dim, hiddens, input_data.sparse_segments) return BatchLRLoss(model, sums, input_data.label) def debug_sparse_mlp_decomposition_model(args, model, input_data): hiddens = [int(s) for s in args.hidden.split('-')] + [2] sums = debug_sparse_mlp_decomposition(model, input_data.data, args.input_dim, hiddens, input_data.sparse_segments) return BatchLRLoss(model, sums, input_data.label) def debug_sparse_mlp_prune_model(args, model, input_data): hiddens = [int(s) for s in args.hidden.split('-')] + [2] sums = debug_sparse_mlp_prune(model, input_data.data, args.input_dim, hiddens, input_data.sparse_segments) return BatchLRLoss(model, sums, input_data.label) MODEL_TYPE_FUNCTIONS = { 'mlp': mlp_model, 'mlp_decomp': mlp_decomp_model, 'mlp_prune': mlp_prune_model, 'sparse_mlp': sparse_mlp_model, 'debug_sparse_mlp': debug_sparse_mlp_model, 'debug_sparse_mlp_decomposition': debug_sparse_mlp_decomposition_model, 'debug_sparse_mlp_prune': debug_sparse_mlp_prune_model, # Add more model_type functions here. } if __name__ == '__main__': # it's hard to init flags correctly... so here it is sys.argv.append('--caffe2_keep_on_shrink') # FbcodeArgumentParser calls initFacebook which is necessary for NNLoader # initialization parser = pyinit.FbcodeArgumentParser(description='Ads NN trainer') # arguments starting with single '-' are compatible with Lua parser.add_argument("-batchSize", type=int, default=100, help="The batch size of benchmark data.") parser.add_argument("-loaderConfig", type=str, help="Json file with NNLoader's config. If empty some " "fake data is used") parser.add_argument("-meta", type=str, help="Meta file (deprecated)") parser.add_argument("-hidden", type=str, help="A dash-separated string specifying the " "model dimensions without the output layer.") parser.add_argument("-epochSize", type=int, default=1000000, help="Examples to process in one take") parser.add_argument("-maxEpoch", type=int, help="Limit number of epochs, if empty reads all data") parser.add_argument("-negDownsampleRate", type=float, default=0.1, help="Used to compute the bias term") parser.add_argument("-rateOfLearning", type=float, default=0.02, help="Learning rate, `lr/(1+t*d)^p`") parser.add_argument("-learnRateDecay", type=float, default=1e-06, help="d in `lr/(1+t*d)^p`") parser.add_argument("-learnRatePower", type=float, default=0.5, help="p in `lr/(1+t*d)^p`") parser.add_argument("-numThreads", type=int, help="If set runs hogwild") parser.add_argument("-model_type", type=str, default='mlp', choices=MODEL_TYPE_FUNCTIONS.keys(), help="The model to benchmark.") parser.add_argument("-seed", type=int, help="random seed.") # arguments for Lua compatibility which are not implemented yet parser.add_argument("-output", help="not implemented") # arguments starting with double '--' are additions of this script parser.add_argument("--input_dim", type=int, default=1500, help="The input dimension of benchmark data.") parser.add_argument("--gpu", action="store_true", help="If set, run testing on GPU.") parser.add_argument("--net_type", type=str, help="Set the type of the network to run with.") parser.add_argument("--num_workers", type=int, default=4, help="The number of workers, if the net type has " "multiple workers.") parser.add_argument("--last_n_stats", type=int, default=0, help="LastN reporting, big values can slow things down") parser.add_argument("--meta2json", default='_bin/fblearner/nn/ads/meta2json.llar', help='Path to meta2json.lar') parser.add_argument("--prune_thres", type=float, default=0.00001, help="The threshold to prune the weights") parser.add_argument("--compress_lb", type=float, default=0.05, help="The lower bound of layer compression") args = parser.parse_args() workspace.GlobalInit(['caffe2', '--caffe2_log_level=-1']) data_gen = NNLoaderData if args.loaderConfig else FakeData train(MODEL_TYPE_FUNCTIONS[args.model_type], data_gen, args)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/core_gradients_test.py
763
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import given import hypothesis.strategies as st import unittest from caffe2.proto import caffe2_pb2 from caffe2.python import core, test_util from caffe2.python.core import CreateOperator, GradientRegistry # First, we will set up a few gradient registry entries so that we can manually # construct some test cases. def NeedAll(op, g_output): """A sanity check to make sure that all the gradient are given.""" for name, g in zip(op.output, g_output): if g is None: raise RuntimeError( 'Need gradient for "%s" but it is not provided.' % name) return g_output def GIS(op): """A test util function to generate the gradient name for input.""" return [s + '_grad' for s in op.input] def CopyDeviceOption(op, src_op): if src_op.HasField('device_option'): op.device_option.CopyFrom(src_op.device_option) return op # First gradient: (in -> out) leading to (out_grad -> in_grad) @GradientRegistry.RegisterGradient('Direct') def AddDirectGradient(op, g_output): return ( CopyDeviceOption( CreateOperator('DirectGradient', NeedAll(op, g_output), GIS(op)), op), GIS(op) ) # Second gradient: (in -> out) leading to (out, out_grad -> in_grad) @GradientRegistry.RegisterGradient('UseOutput') def AddUseOutputGradient(op, g_output): return ( CopyDeviceOption( CreateOperator( 'UseOutputGradient', list(op.output) + NeedAll(op, g_output), GIS(op)), op), GIS(op) ) @GradientRegistry.RegisterGradient('UseInput') def AddUseInputGradient(op, g_output): return ( CopyDeviceOption( CreateOperator( 'UseInputGradient', list(op.input) + NeedAll(op, g_output), GIS(op)), op), GIS(op) ) @GradientRegistry.RegisterGradient('Nogradient') def AddNogradient(op, g_output): return ( [], [None for s in op.input] ) class TestGradientCalculation(test_util.TestCase): @given(device_option=st.sampled_from([ None, core.DeviceOption(caffe2_pb2.CUDA, 1)])) def testDirect(self, device_option): operators = [ CreateOperator('Direct', 'in', 'hidden'), CreateOperator('Direct', 'hidden', 'out'), ] if device_option: for op in operators: op.device_option.CopyFrom(device_option) desired_grad_operators = [ CreateOperator('DirectGradient', 'out_grad', 'hidden_grad'), CreateOperator('DirectGradient', 'hidden_grad', 'in_grad'), ] if device_option: for op in desired_grad_operators: op.device_option.CopyFrom(device_option) gradients, _ = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) self.assertEqual(gradients, desired_grad_operators) def testDirectImplicitGradientSource(self): operators = [ CreateOperator('Direct', 'in', 'hidden'), CreateOperator('Direct', 'hidden', 'out'), ] desired_grad_operators = [ CreateOperator( "ConstantFill", 'out', "out_autogen_grad", value=1.0), CreateOperator( 'DirectGradient', 'out_autogen_grad', 'hidden_grad'), CreateOperator('DirectGradient', 'hidden_grad', 'in_grad'), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, ['out']) self.assertEqual(gradients, desired_grad_operators) def testDoesNotGenerateUnnecessaryGradients(self): operators = [ CreateOperator('Direct', 'in', 'hidden'), CreateOperator('Direct', 'hidden', 'out'), ] desired_grad_operators = [ CreateOperator('DirectGradient', 'hidden_grad', 'in_grad'), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'hidden': 'hidden_grad'}) self.assertEqual(gradients, desired_grad_operators) def testDirectButNoOutputGradientGiven(self): operators = [ CreateOperator('Direct', 'in', 'hidden'), CreateOperator('Direct', 'hidden', 'out'), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {}) self.assertEqual(gradients, []) def testDirectInPlace(self): operators = [ CreateOperator('Direct', 'in', 'in'), CreateOperator('Direct', 'in', 'out'), ] desired_grad_operators = [ CreateOperator('DirectGradient', 'out_grad', 'in_grad'), CreateOperator('DirectGradient', 'in_grad', 'in_grad'), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) self.assertEqual(gradients, desired_grad_operators) def testUseOutput(self): operators = [ CreateOperator('UseOutput', 'in', 'hidden'), CreateOperator('UseOutput', 'hidden', 'out'), CreateOperator('Direct', 'out', 'sink'), ] desired_grad_operators = [ CreateOperator('DirectGradient', 'sink_grad', 'out_grad'), CreateOperator( 'UseOutputGradient', ['out', 'out_grad'], 'hidden_grad' ), CreateOperator( 'UseOutputGradient', ['hidden', 'hidden_grad'], 'in_grad' ), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'sink': 'sink_grad'}) self.assertEqual(gradients, desired_grad_operators) def testUseOutputInPlace(self): operators = [ CreateOperator('UseOutput', 'in', 'in'), CreateOperator('UseOutput', 'in', 'out'), CreateOperator('Direct', 'out', 'sink'), ] desired_grad_operators = [ CreateOperator('DirectGradient', 'sink_grad', 'out_grad'), CreateOperator( 'UseOutputGradient', ['out', 'out_grad'], 'in_grad' ), CreateOperator( 'UseOutputGradient', ['in', 'in_grad'], 'in_grad' ), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'sink': 'sink_grad'}) self.assertEqual(gradients, desired_grad_operators) def testUseOutputButOutputHasBeenChanged(self): operators = [ CreateOperator('UseOutput', 'in', 'hidden'), # Note here: we overwrite hidden, but hidden will be needed by the # gradient calculation of the first operator, so the gradient # registry should return an error. CreateOperator('Direct', 'hidden', 'hidden'), CreateOperator('UseOutput', 'hidden', 'out'), CreateOperator('Direct', 'out', 'sink'), ] with self.assertRaises(RuntimeError): gradients, _ = GradientRegistry.GetBackwardPass( operators, {'sink': 'sink_grad'}) def testUseInput(self): operators = [ CreateOperator('Direct', 'in', 'hidden'), CreateOperator('UseInput', 'hidden', 'out'), CreateOperator('Direct', 'out', 'sink'), ] desired_grad_operators = [ CreateOperator('DirectGradient', 'sink_grad', 'out_grad'), CreateOperator( 'UseInputGradient', ['hidden', 'out_grad'], 'hidden_grad' ), CreateOperator( 'DirectGradient', 'hidden_grad', 'in_grad' ), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'sink': 'sink_grad'}) self.assertEqual(gradients, desired_grad_operators) def testUseInputButInputHasBeenChanged(self): """Test gradient for the following case: in -> out, with UseInput in -> in Since we overwrite in in op#1, but in will be needed by the gradient calculation of op#0, the gradient registry should raise an error. """ operators = [ CreateOperator('UseInput', 'in', 'out'), CreateOperator('Direct', 'in', 'in'), ] with self.assertRaises(RuntimeError): gradients, _ = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) @given(device_option=st.sampled_from([ None, core.DeviceOption(caffe2_pb2.CUDA, 1)])) def testMultiUseInput(self, device_option): """Test gradient for the following case: in -> hidden1 in -> hidden2 hidden1, hidden2 -> out """ operators = [ CreateOperator('Direct', 'in', 'hidden1'), CreateOperator('Direct', 'in', 'hidden2'), CreateOperator('Direct', ['hidden1', 'hidden2'], 'out'), ] if device_option: for op in operators: op.device_option.CopyFrom(device_option) desired_grad_operators = [ CreateOperator( 'DirectGradient', 'out_grad', ['hidden1_grad', 'hidden2_grad'] ), CreateOperator( 'DirectGradient', 'hidden2_grad', '_in_grad_autosplit_0' ), CreateOperator( 'DirectGradient', 'hidden1_grad', '_in_grad_autosplit_1' ), CreateOperator( 'Sum', ['_in_grad_autosplit_0', '_in_grad_autosplit_1'], 'in_grad' ), ] if device_option: for op in desired_grad_operators: op.device_option.CopyFrom(device_option) gradients, _ = GradientRegistry.GetBackwardPass( operators, {"out": "out_grad"}) self.assertEqual(gradients, desired_grad_operators) def testMultiUseInputButWithNoGradient(self): """Test gradient for the following case: in -> hidden1 in -(no gradient)-> hidden2 hidden1, hidden2 -> out """ operators = [ CreateOperator('Direct', 'in', 'hidden1'), CreateOperator('Nogradient', 'in', 'hidden2'), CreateOperator('Direct', ['hidden1', 'hidden2'], 'out'), ] desired_grad_operators = [ CreateOperator( 'DirectGradient', 'out_grad', ['hidden1_grad', 'hidden2_grad'] ), CreateOperator( 'DirectGradient', 'hidden1_grad', 'in_grad' ), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) self.assertEqual(gradients, desired_grad_operators) def testMultiUseInputAndMultipleVersions(self): """Test gradient for the following case: in -> in in -> hidden1, hidden2 hidden1, hidden2 -> out """ operators = [ CreateOperator('Direct', 'in', 'in'), CreateOperator('Direct', 'in', 'hidden1'), CreateOperator('Direct', 'in', 'hidden2'), CreateOperator('Direct', ['hidden1', 'hidden2'], 'out'), ] desired_grad_operators = [ CreateOperator( 'DirectGradient', 'out_grad', ['hidden1_grad', 'hidden2_grad'] ), CreateOperator( 'DirectGradient', 'hidden2_grad', '_in_grad_autosplit_0' ), CreateOperator( 'DirectGradient', 'hidden1_grad', '_in_grad_autosplit_1' ), CreateOperator( 'Sum', ['_in_grad_autosplit_0', '_in_grad_autosplit_1'], 'in_grad' ), CreateOperator( 'DirectGradient', 'in_grad', 'in_grad' ), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) self.assertEqual(gradients, desired_grad_operators) def testMultiUseInputAndMultipleVersionsBig(self): """Test gradient for the following case: in -> in in -> hidden1, hidden2 hidden1, hidden2 -> in in -> hidden3, hidden4, hidden5 hidden3, hidden4, hidden5 -> out """ operators = [ CreateOperator('Direct', 'in', 'in'), CreateOperator('Direct', 'in', 'hidden1'), CreateOperator('Direct', 'in', 'hidden2'), CreateOperator('Direct', ['hidden1', 'hidden2'], 'in'), CreateOperator('Direct', 'in', 'hidden3'), CreateOperator('Direct', 'in', 'hidden4'), CreateOperator('Direct', 'in', 'hidden5'), CreateOperator('Direct', ['hidden3', 'hidden4', 'hidden5'], 'out'), ] desired_grad_operators = [ CreateOperator( 'DirectGradient', 'out_grad', ['hidden3_grad', 'hidden4_grad', 'hidden5_grad'] ), CreateOperator( 'DirectGradient', 'hidden5_grad', '_in_grad_autosplit_0' ), CreateOperator( 'DirectGradient', 'hidden4_grad', '_in_grad_autosplit_1' ), CreateOperator( 'DirectGradient', 'hidden3_grad', '_in_grad_autosplit_2' ), CreateOperator( 'Sum', ['_in_grad_autosplit_0', '_in_grad_autosplit_1', '_in_grad_autosplit_2'], 'in_grad' ), CreateOperator( 'DirectGradient', 'in_grad', ['hidden1_grad', 'hidden2_grad'] ), CreateOperator( 'DirectGradient', 'hidden2_grad', '_in_grad_autosplit_0' ), CreateOperator( 'DirectGradient', 'hidden1_grad', '_in_grad_autosplit_1' ), CreateOperator( 'Sum', ['_in_grad_autosplit_0', '_in_grad_autosplit_1'], 'in_grad' ), CreateOperator( 'DirectGradient', 'in_grad', 'in_grad' ), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) for s in gradients: print(str(s)) self.assertEqual(gradients, desired_grad_operators) def testGradientMappingUsingSumOp(self): """Since Sum is used in accumulating gradients, we will test if it is OK to also explicitly use it in the graph.""" operators = [ CreateOperator('FC', ['in', 'w', 'b'], 'fc'), CreateOperator('Sum', 'fc', 'agg'), CreateOperator('AveragedLoss', 'agg', 'loss'), ] # This should run correctly. gradient_ops, _ = GradientRegistry.GetBackwardPass( operators, {'loss': 'loss_grad'}) for s in gradient_ops: print(str(s)) def testGradientCalculationWithPrint(self): """Test a common use case where we have Print in the forward pass.""" operators = [ CreateOperator('FC', ['in', 'w', 'b'], 'fc'), CreateOperator('Print', 'fc', []), CreateOperator('AveragedLoss', 'fc', 'loss'), ] desired_grad_operators = [ CreateOperator('AveragedLossGradient', ['fc', 'loss_grad'], 'fc_grad'), CreateOperator('FCGradient', ['in', 'w', 'fc_grad'], ['w_grad', 'b_grad', 'in_grad']), ] # This should run correctly. gradient_ops, _ = GradientRegistry.GetBackwardPass( operators, {'loss': 'loss_grad'}) for s in gradient_ops: print(str(s)) self.assertEqual(gradient_ops, desired_grad_operators) def testStopGradient(self): operators = [ CreateOperator('Direct', 'in', 'hidden'), CreateOperator('StopGradient', 'hidden', 'hidden2'), CreateOperator('Direct', 'hidden2', 'out'), ] desired_grad_operators = [ CreateOperator('DirectGradient', 'out_grad', 'hidden2_grad'), ] gradients, _ = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) self.assertEqual(gradients, desired_grad_operators) def testStopGradientInplace(self): operators = [ CreateOperator('Direct', 'in', 'hidden'), CreateOperator('StopGradient', 'hidden', 'hidden'), CreateOperator('Direct', 'hidden', 'out'), ] desired_grad_operators = [ CreateOperator('DirectGradient', 'out_grad', 'hidden_grad'), ] gradients, grad_map = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) self.assertEqual(gradients, desired_grad_operators) self.assertEqual(grad_map, {'out': 'out_grad'}) def testStopGradientWithMultiUseOperators(self): operators = [ CreateOperator('Direct', 'in', 'hidden'), CreateOperator('Direct', 'hidden', 'hidden2'), CreateOperator('StopGradient', 'hidden', 'hidden3'), CreateOperator('Direct', ['hidden2', 'hidden3'], 'out'), ] desired_grad_operators = [ CreateOperator('DirectGradient', 'out_grad', ['hidden2_grad', 'hidden3_grad']), CreateOperator('DirectGradient', 'hidden2_grad', 'hidden_grad'), CreateOperator('DirectGradient', 'hidden_grad', 'in_grad'), ] gradients, grad_map = GradientRegistry.GetBackwardPass( operators, {'out': 'out_grad'}) self.assertEqual(gradients, desired_grad_operators) self.assertEqual( grad_map, {'out': 'out_grad', 'hidden2': 'hidden2_grad', 'hidden3': 'hidden3_grad', 'hidden': 'hidden_grad', 'in': 'in_grad'}) # Skip if sparse operators are not available @unittest.skipIf(not core.IsOperator('SparseFunHash'), 'Sparse operators not available') class TestSparseGradientsAccumulation(test_util.TestCase): def testSparseAccumulationWithValues(self): # The gradient for "Gather" only computes values. indices are directly # passed from the input # # x1-->Gather-->x4--> # | | # x2-----+ DotProduct-->x6 # | | # x3-->Gather-->x5--> net = core.Net("test_net") net.Gather(["x2", "x1"], "x4") net.Gather(["x2", "x3"], "x5") net.DotProduct(["x4", "x5"], "x6") net.AddGradientOperators(["x6"]) sum_op_i = net.Proto().op[-2] sum_op_v = net.Proto().op[-1] self.assertEqual(sum_op_i.input[0], "x3") self.assertEqual(sum_op_i.input[1], "x1") self.assertEqual(sum_op_i.output[0], "x2_grad_indices_concat") self.assertEqual(sum_op_v.input[0], "x5_grad") self.assertEqual(sum_op_v.input[1], "x4_grad") self.assertEqual(sum_op_v.output[0], "x2_grad_values_concat") def testSparseAccumulationWithIndicesAndValues(self): # The gradient for "SparseFunHash" computes both indices and values # # x1--------> # | # x2----> | # | | # x3---SparseFunHash-->x8 # / \ # x4---+ DotProduct-->x10 # \ / # x5---SparseFunHash-->x9 # | | # x6----> | # | # x7--------> net = core.Net("test_net") net.SparseFunHash(["x1", "x2", "x3", "x4"], "x8") net.SparseFunHash(["x5", "x6", "x7", "x4"], "x9") net.DotProduct(["x8", "x9"], "x10") net.AddGradientOperators(["x10"]) sum_op_i = net.Proto().op[-2] sum_op_v = net.Proto().op[-1] self.assertEqual(sum_op_i.input[0], "_x4_grad_indices_autosplit_0") self.assertEqual(sum_op_i.input[1], "_x4_grad_indices_autosplit_1") self.assertEqual(sum_op_i.output[0], "x4_grad_indices_concat") self.assertEqual(sum_op_v.input[0], "_x4_grad_values_autosplit_0") self.assertEqual(sum_op_v.input[1], "_x4_grad_values_autosplit_1") self.assertEqual(sum_op_v.output[0], "x4_grad_values_concat") class TestGradientsAccumulationWithNoGradientOps(test_util.TestCase): def testNormalAccumulation(self): # x1-->Relu--x2----------------->DotProduct-->x4 # | | # -->Softmax-->x3--> net = core.Net("test_net") net.Relu("x1", "x2") net.Softmax("x2", "x3") net.DotProduct(["x2", "x3"], "x4") net.AddGradientOperators(["x4"]) sum_op = net.Proto().op[-2] self.assertEqual(sum_op.input[0], "_x2_grad_autosplit_0") self.assertEqual(sum_op.input[1], "_x2_grad_autosplit_1") self.assertEqual(sum_op.output[0], "x2_grad") def testAccumulationWithNoGradientBranch(self): # -->PRINT # | # x1-->Relu--x2----------------->DotProduct-->x4 # | | # -->Softmax-->x3--> net = core.Net("test_net") net.Relu("x1", "x2") net.Print("x2", []) net.Softmax("x2", "x3") net.DotProduct(["x2", "x3"], "x4") net.AddGradientOperators(["x4"]) sum_op = net.Proto().op[-2] self.assertEqual(sum_op.input[0], "_x2_grad_autosplit_0") self.assertEqual(sum_op.input[1], "_x2_grad_autosplit_1") self.assertEqual(sum_op.output[0], "x2_grad") class TestGradientsAccumulationWithPassThroughGradients(test_util.TestCase): def testAddOpInMiddle(self): # x1-->Relu--x2----------------->Add-->x4 # | | # -->Softmax-->x3--> # # Expected gradient graph: # # x1_g<--ReluG<--x2_g<--Sum<------------<---------x4_g # | | # <--_x2_g_split_0<--SoftmaxG net = core.Net("test_net") net.Relu("x1", "x2") net.Softmax("x2", "x3") net.Add(["x2", "x3"], "x4") input_to_grad = net.AddGradientOperators({"x4": "x4_grad"}) sum_op = net.Proto().op[-2] self.assertEqual(sum_op.input[0], "x4_grad") self.assertEqual(sum_op.input[1], "_x2_grad_autosplit_0") self.assertEqual(sum_op.output[0], "x2_grad") self.assertEqual(input_to_grad["x1"], "x1_grad") def testSubOpInMiddle(self): # x1-->Relu--x2----------------->Sub-->x4 # | | # -->Softmax-->x3--> # # Expected gradient graph: # # x1_g<--ReluG<--x2_g<--Sum<------------<-----------------------x4_g # | | # <--_x2_g_split_0<--SoftmaxG<--x3_g<--neg net = core.Net("test_net") net.Relu("x1", "x2") net.Softmax("x2", "x3") net.Sub(["x2", "x3"], "x4") input_to_grad = net.AddGradientOperators({"x4": "x4_grad"}) print(str(net.Proto())) sum_op = net.Proto().op[-2] self.assertEqual(sum_op.input[0], "x4_grad") self.assertEqual(sum_op.input[1], "_x2_grad_autosplit_0") self.assertEqual(sum_op.output[0], "x2_grad") self.assertEqual(input_to_grad["x1"], "x1_grad") def testAddOpAtLeaf(self): # x1 # \ # -->Add-->x4 # / \ # x2 -->DotProduct-->x6 # \ / # -->Add-->x5 # / # x3 # # Expected gradient graph: # # x2_g<--Sum<--x4_g<--DotProductG<--x6_g # | | | # <---x5_g<------- net = core.Net("test_net") net.Add(["x1", "x2"], "x4") net.Add(["x2", "x3"], "x5") net.DotProduct(["x4", "x5"], "x6") input_to_grad = net.AddGradientOperators({"x6": "x6_grad"}) sum_op = net.Proto().op[-1] self.assertEqual(sum_op.input[0], "x5_grad") self.assertEqual(sum_op.input[1], "x4_grad") self.assertEqual(sum_op.output[0], "x2_grad") self.assertEqual(input_to_grad["x1"], "x4_grad") self.assertEqual(input_to_grad["x2"], "x2_grad") self.assertEqual(input_to_grad["x3"], "x5_grad") def testSubOpAtLeaf(self): # x1 # \ # -->Sub-->x4 # / \ # x2 -->DotProduct-->x6 # \ / # -->Sub-->x5 # / # x3 # # Expected gradient graph: # # x2_g<-------Sum<--x2_g_split_0<--neg<--x4_g<--DotProductG<--x6_g # | | # x3_g<--neg<--<--x5_g<-------------------------------- net = core.Net("test_net") net.Sub(["x1", "x2"], "x4") net.Sub(["x2", "x3"], "x5") net.DotProduct(["x4", "x5"], "x6") input_to_grad = net.AddGradientOperators({"x6": "x6_grad"}) sum_op = net.Proto().op[-1] self.assertEqual(sum_op.input[0], "x5_grad") self.assertEqual(sum_op.input[1], "_x2_grad_autosplit_0") self.assertEqual(sum_op.output[0], "x2_grad") self.assertEqual(input_to_grad["x1"], "x4_grad") self.assertEqual(input_to_grad["x2"], "x2_grad") self.assertEqual(input_to_grad["x3"], "x3_grad") def testMultiLayerAddOps(self): # x1 # \ # -->Add-->x4 # / \ # x2 -->Add-->x6 # \ / # -->Add-->x5 # / # x3 # # Expected gradient graph: # # x2_g<--Sum<-----x6_g # | | # <-------- net = core.Net("test_net") net.Add(["x1", "x2"], "x4") net.Add(["x2", "x3"], "x5") net.Add(["x4", "x5"], "x6") input_to_grad = net.AddGradientOperators({"x6": "x6_grad"}) sum_op = net.Proto().op[-1] self.assertEqual(sum_op.input[0], "x6_grad") self.assertEqual(sum_op.input[1], "x6_grad") self.assertEqual(sum_op.output[0], "x2_grad") self.assertEqual(input_to_grad["x1"], "x6_grad") self.assertEqual(input_to_grad["x2"], "x2_grad") self.assertEqual(input_to_grad["x3"], "x6_grad") def testMultiLayerSubOps(self): # x1 # \ # -->Sub-->x4 # / \ # x2 -->Sub-->x6 # \ / # -->Sub-->x5 # / # x3 # # Expected gradient graph: # # x2_g<--Sum<-----x6_g # | | # <-------- net = core.Net("test_net") net.Sub(["x1", "x2"], "x4") net.Sub(["x2", "x3"], "x5") net.Sub(["x4", "x5"], "x6") input_to_grad = net.AddGradientOperators({"x6": "x6_grad"}) sum_op = net.Proto().op[-1] self.assertEqual(sum_op.input[0], "x5_grad") self.assertEqual(sum_op.input[1], "_x2_grad_autosplit_0") self.assertEqual(sum_op.output[0], "x2_grad") self.assertEqual(input_to_grad["x1"], "x6_grad") self.assertEqual(input_to_grad["x2"], "x2_grad") self.assertEqual(input_to_grad["x3"], "x3_grad") if __name__ == '__main__': unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/control.py
572
""" Implement functions for controlling execution of nets and steps, including Do DoParallel For-loop While-loop Do-While-loop Switch If """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core # Used to generate names of the steps created by the control functions. # It is actually the internal index of these steps. _current_idx = 1 _used_step_names = set() def _get_next_step_name(control_name, base_name): global _current_idx, _used_step_names concat_name = '%s/%s' % (base_name, control_name) next_name = concat_name while next_name in _used_step_names: next_name = '%s_%d' % (concat_name, _current_idx) _current_idx += 1 _used_step_names.add(next_name) return next_name def _MakeList(input): """ input is a tuple. Example: (a, b, c) --> [a, b, c] (a) --> [a] ([a, b, c]) --> [a, b, c] """ if len(input) == 0: raise ValueError( 'input cannot be empty.') elif len(input) == 1: output = input[0] if not isinstance(output, list): output = [output] else: output = list(input) return output def _IsNets(nets_or_steps): if isinstance(nets_or_steps, list): return all(isinstance(n, core.Net) for n in nets_or_steps) else: return isinstance(nets_or_steps, core.Net) def _PrependNets(nets_or_steps, *nets): nets_or_steps = _MakeList((nets_or_steps,)) nets = _MakeList(nets) if _IsNets(nets_or_steps): return nets + nets_or_steps else: return [Do('prepend', nets)] + nets_or_steps def _AppendNets(nets_or_steps, *nets): nets_or_steps = _MakeList((nets_or_steps,)) nets = _MakeList(nets) if _IsNets(nets_or_steps): return nets_or_steps + nets else: return nets_or_steps + [Do('append', nets)] def GetConditionBlobFromNet(condition_net): """ The condition blob is the last external_output that must be a single bool """ assert len(condition_net.Proto().external_output) > 0, ( "Condition net %s must has at least one external output" % condition_net.Proto.name) # we need to use a blob reference here instead of a string # otherwise, it will add another name_scope to the input later # when we create new ops (such as OR of two inputs) return core.BlobReference(condition_net.Proto().external_output[-1]) def BoolNet(*blobs_with_bool_value): """A net assigning constant bool values to blobs. It is mainly used for initializing condition blobs, for example, in multi-task learning, we need to access reader_done blobs before reader_net run. In that case, the reader_done blobs must be initialized. Args: blobs_with_bool_value: one or more (blob, bool_value) pairs. The net will assign each bool_value to the corresponding blob. returns bool_net: A net assigning constant bool values to blobs. Examples: - BoolNet((blob_1, bool_value_1), ..., (blob_n, bool_value_n)) - BoolNet([(blob_1, net1), ..., (blob_n, bool_value_n)]) - BoolNet((cond_1, bool_value_1)) """ blobs_with_bool_value = _MakeList(blobs_with_bool_value) bool_net = core.Net('bool_net') for blob, bool_value in blobs_with_bool_value: out_blob = bool_net.ConstantFill( [], [blob], shape=[], value=bool_value, dtype=core.DataType.BOOL) bool_net.AddExternalOutput(out_blob) return bool_net def NotNet(condition_blob_or_net): """Not of a condition blob or net Args: condition_blob_or_net can be either blob or net. If condition_blob_or_net is Net, the condition is its last external_output that must be a single bool. returns not_net: the net NOT the input out_blob: the output blob of the not_net """ if isinstance(condition_blob_or_net, core.Net): condition_blob = GetConditionBlobFromNet(condition_blob_or_net) else: condition_blob = condition_blob_or_net not_net = core.Net('not_net') out_blob = not_net.Not(condition_blob) not_net.AddExternalOutput(out_blob) return not_net, out_blob def _CopyConditionBlobNet(condition_blob): """Make a condition net that copies the condition_blob Args: condition_blob is a single bool. returns not_net: the net NOT the input out_blob: the output blob of the not_net """ condition_net = core.Net('copy_condition_blob_net') out_blob = condition_net.Copy(condition_blob) condition_net.AddExternalOutput(out_blob) return condition_net, out_blob def MergeConditionNets(name, condition_nets, relation): """ Merge multi condition nets into a single condition nets. Args: name: name of the new condition net. condition_nets: a list of condition nets. The last external_output of each condition net must be single bool value. relation: can be 'And' or 'Or'. Returns: - A new condition net. Its last external output is relation of all condition_nets. """ if not isinstance(condition_nets, list): return condition_nets if len(condition_nets) <= 1: return condition_nets[0] if condition_nets else None merged_net = core.Net(name) for i in range(len(condition_nets)): net_proto = condition_nets[i].Proto() assert net_proto.device_option == merged_net.Proto().device_option assert net_proto.type == merged_net.Proto().type merged_net.Proto().op.extend(net_proto.op) merged_net.Proto().external_input.extend(net_proto.external_input) # discard external outputs as we're combining them together curr_cond = GetConditionBlobFromNet(condition_nets[i]) if i == 0: last_cond = curr_cond else: last_cond = merged_net.__getattr__(relation)([last_cond, curr_cond]) # merge attributes for k, v in condition_nets[i]._attr_dict.items(): merged_net._attr_dict[k] += v merged_net.AddExternalOutput(last_cond) return merged_net def CombineConditions(name, condition_nets, relation): """ Combine conditions of multi nets into a single condition nets. Unlike MergeConditionNets, the actual body of condition_nets is not copied into the combine condition net. One example is about multi readers. Each reader net has a reader_done condition. When we want to check whether all readers are done, we can use this function to build a new net. Args: name: name of the new condition net. condition_nets: a list of condition nets. The last external_output of each condition net must be single bool value. relation: can be 'And' or 'Or'. Returns: - A new condition net. Its last external output is relation of all condition_nets. """ if not condition_nets: return None if not isinstance(condition_nets, list): raise ValueError('condition_nets must be a list of nets.') if len(condition_nets) == 1: condition_blob = GetConditionBlobFromNet(condition_nets[0]) condition_net, _ = _CopyConditionBlobNet(condition_blob) return condition_net combined_net = core.Net(name) for i in range(len(condition_nets)): curr_cond = GetConditionBlobFromNet(condition_nets[i]) if i == 0: last_cond = curr_cond else: last_cond = combined_net.__getattr__(relation)( [last_cond, curr_cond]) combined_net.AddExternalOutput(last_cond) return combined_net def Do(name, *nets_or_steps): """ Execute the sequence of nets or steps once. Examples: - Do('myDo', net1, net2, ..., net_n) - Do('myDo', list_of_nets) - Do('myDo', step1, step2, ..., step_n) - Do('myDo', list_of_steps) """ nets_or_steps = _MakeList(nets_or_steps) if (len(nets_or_steps) == 1 and isinstance( nets_or_steps[0], core.ExecutionStep)): return nets_or_steps[0] else: return core.scoped_execution_step( _get_next_step_name('Do', name), nets_or_steps) def DoParallel(name, *nets_or_steps): """ Execute the nets or steps in parallel, waiting for all of them to finish Examples: - DoParallel('pDo', net1, net2, ..., net_n) - DoParallel('pDo', list_of_nets) - DoParallel('pDo', step1, step2, ..., step_n) - DoParallel('pDo', list_of_steps) """ nets_or_steps = _MakeList(nets_or_steps) if (len(nets_or_steps) == 1 and isinstance( nets_or_steps[0], core.ExecutionStep)): return nets_or_steps[0] else: return core.scoped_execution_step( _get_next_step_name('DoParallel', name), nets_or_steps, concurrent_substeps=True) def _RunOnceIf(name, condition_blob_or_net, nets_or_steps): """ Execute nets_or_steps once if condition_blob_or_net evaluates as true. If condition_blob_or_net is Net, the condition is its last external_output that must be a single bool. And this net will be executed before nets_or_steps so as to get the condition. """ condition_not_net, stop_blob = NotNet(condition_blob_or_net) if isinstance(condition_blob_or_net, core.Net): nets_or_steps = _PrependNets( nets_or_steps, condition_blob_or_net, condition_not_net) else: nets_or_steps = _PrependNets(nets_or_steps, condition_not_net) def if_step(control_name): return core.scoped_execution_step( _get_next_step_name(control_name, name), nets_or_steps, should_stop_blob=stop_blob, only_once=True, ) if _IsNets(nets_or_steps): bool_net = BoolNet((stop_blob, False)) return Do(name + '/_RunOnceIf', bool_net, if_step('_RunOnceIf-inner')) else: return if_step('_RunOnceIf') def _RunOnceIfNot(name, condition_blob_or_net, nets_or_steps): """ Similar to _RunOnceIf() but Execute nets_or_steps once if condition_blob_or_net evaluates as false. """ if isinstance(condition_blob_or_net, core.Net): condition_blob = GetConditionBlobFromNet(condition_blob_or_net) nets_or_steps = _PrependNets(nets_or_steps, condition_blob_or_net) else: copy_net, condition_blob = _CopyConditionBlobNet(condition_blob_or_net) nets_or_steps = _PrependNets(nets_or_steps, copy_net) return core.scoped_execution_step( _get_next_step_name('_RunOnceIfNot', name), nets_or_steps, should_stop_blob=condition_blob, only_once=True, ) def For(name, nets_or_steps, iter_num): """ Execute nets_or_steps iter_num times. Args: nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or a list nets. iter_num: the number times to execute the nets_or_steps. Returns: A ExecutionStep instance. """ init_net = core.Net('init-net') iter_cnt = init_net.CreateCounter([], init_count=iter_num) iter_net = core.Net('For-iter') iter_done = iter_net.CountDown([iter_cnt]) for_step = core.scoped_execution_step( _get_next_step_name('For-inner', name), _PrependNets(nets_or_steps, iter_net), should_stop_blob=iter_done) return Do(name + '/For', Do(name + '/For-init-net', init_net), for_step) def While(name, condition_blob_or_net, nets_or_steps): """ Execute nets_or_steps when condition_blob_or_net returns true. Args: condition_blob_or_net: If it is an instance of Net, its last external_output must be a single bool. nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or a list nets. Returns: A ExecutionStep instance. """ condition_not_net, stop_blob = NotNet(condition_blob_or_net) if isinstance(condition_blob_or_net, core.Net): nets_or_steps = _PrependNets( nets_or_steps, condition_blob_or_net, condition_not_net) else: nets_or_steps = _PrependNets(nets_or_steps, condition_not_net) def while_step(control_name): return core.scoped_execution_step( _get_next_step_name(control_name, name), nets_or_steps, should_stop_blob=stop_blob, ) if _IsNets(nets_or_steps): # In this case, while_step has sub-nets: # [condition_blob_or_net, condition_not_net, nets_or_steps] # If stop_blob is pre-set to True (this may happen when While() is # called twice), the loop will exit after executing # condition_blob_or_net. So we use BootNet to set stop_blob to # False. bool_net = BoolNet((stop_blob, False)) return Do(name + '/While', bool_net, while_step('While-inner')) else: return while_step('While') def Until(name, condition_blob_or_net, nets_or_steps): """ Similar to While() but execute nets_or_steps when condition_blob_or_net returns false """ if isinstance(condition_blob_or_net, core.Net): stop_blob = GetConditionBlobFromNet(condition_blob_or_net) nets_or_steps = _PrependNets(nets_or_steps, condition_blob_or_net) else: stop_blob = core.BlobReference(str(condition_blob_or_net)) return core.scoped_execution_step( _get_next_step_name('Until', name), nets_or_steps, should_stop_blob=stop_blob) def DoWhile(name, condition_blob_or_net, nets_or_steps): """ Execute nets_or_steps when condition_blob_or_net returns true. It will execute nets_or_steps before evaluating condition_blob_or_net. Args: condition_blob_or_net: if it is an instance of Net, tts last external_output must be a single bool. nets_or_steps: a ExecutionStep or a Net or a list of ExecutionSteps or a list nets. Returns: A ExecutionStep instance. """ condition_not_net, stop_blob = NotNet(condition_blob_or_net) if isinstance(condition_blob_or_net, core.Net): nets_or_steps = _AppendNets( nets_or_steps, condition_blob_or_net, condition_not_net) else: nets_or_steps = _AppendNets(nets_or_steps, condition_not_net) # If stop_blob is pre-set to True (this may happen when DoWhile() is # called twice), the loop will exit after executing the first net/step # in nets_or_steps. This is not what we want. So we use BootNet to # set stop_blob to False. bool_net = BoolNet((stop_blob, False)) return Do(name + '/DoWhile', bool_net, core.scoped_execution_step( _get_next_step_name('DoWhile-inner', name), nets_or_steps, should_stop_blob=stop_blob, )) def DoUntil(name, condition_blob_or_net, nets_or_steps): """ Similar to DoWhile() but execute nets_or_steps when condition_blob_or_net returns false. It will execute nets_or_steps before evaluating condition_blob_or_net. Special case: if condition_blob_or_net is a blob and is pre-set to true, then only the first net/step of nets_or_steps will be executed and loop is exited. So you need to be careful about the initial value the condition blob when using DoUntil(), esp when DoUntil() is called twice. """ if not isinstance(condition_blob_or_net, core.Net): stop_blob = core.BlobReference(condition_blob_or_net) return core.scoped_execution_step( _get_next_step_name('DoUntil', name), nets_or_steps, should_stop_blob=stop_blob) nets_or_steps = _AppendNets(nets_or_steps, condition_blob_or_net) stop_blob = GetConditionBlobFromNet(condition_blob_or_net) # If stop_blob is pre-set to True (this may happen when DoWhile() is # called twice), the loop will exit after executing the first net/step # in nets_or_steps. This is not what we want. So we use BootNet to # set stop_blob to False. bool_net = BoolNet((stop_blob, False)) return Do(name + '/DoUntil', bool_net, core.scoped_execution_step( _get_next_step_name('DoUntil-inner', name), nets_or_steps, should_stop_blob=stop_blob, )) def Switch(name, *conditions): """ Execute the steps for which the condition is true. Each condition is a tuple (condition_blob_or_net, nets_or_steps). Note: 1. Multi steps can be executed if their conditions are true. 2. The conditions_blob_or_net (if it is Net) of all steps will be executed once. Examples: - Switch('name', (cond_1, net_1), (cond_2, net_2), ..., (cond_n, net_n)) - Switch('name', [(cond_1, net1), (cond_2, net_2), ..., (cond_n, net_n)]) - Switch('name', (cond_1, net_1)) """ conditions = _MakeList(conditions) return core.scoped_execution_step( _get_next_step_name('Switch', name), [_RunOnceIf(name + '/Switch', cond, step) for cond, step in conditions]) def SwitchNot(name, *conditions): """ Similar to Switch() but execute the steps for which the condition is False. """ conditions = _MakeList(conditions) return core.scoped_execution_step( _get_next_step_name('SwitchNot', name), [_RunOnceIfNot(name + '/SwitchNot', cond, step) for cond, step in conditions]) def If(name, condition_blob_or_net, true_nets_or_steps, false_nets_or_steps=None): """ condition_blob_or_net is first evaluated or executed. If the condition is true, true_nets_or_steps is then executed, otherwise, false_nets_or_steps is executed. If condition_blob_or_net is Net, the condition is its last external_output that must be a single bool. And this Net will be executred before both true/false_nets_or_steps so as to get the condition. """ if not false_nets_or_steps: return _RunOnceIf(name + '/If', condition_blob_or_net, true_nets_or_steps) if isinstance(condition_blob_or_net, core.Net): condition_blob = GetConditionBlobFromNet(condition_blob_or_net) else: condition_blob = condition_blob_or_net return Do( name + '/If', _RunOnceIf(name + '/If-true', condition_blob_or_net, true_nets_or_steps), _RunOnceIfNot(name + '/If-false', condition_blob, false_nets_or_steps) ) def IfNot(name, condition_blob_or_net, true_nets_or_steps, false_nets_or_steps=None): """ If condition_blob_or_net returns false, executes true_nets_or_steps, otherwise executes false_nets_or_steps """ if not false_nets_or_steps: return _RunOnceIfNot(name + '/IfNot', condition_blob_or_net, true_nets_or_steps) if isinstance(condition_blob_or_net, core.Net): condition_blob = GetConditionBlobFromNet(condition_blob_or_net) else: condition_blob = condition_blob_or_net return Do( name + '/IfNot', _RunOnceIfNot(name + '/IfNot-true', condition_blob_or_net, true_nets_or_steps), _RunOnceIf(name + '/IfNot-false', condition_blob, false_nets_or_steps) )
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/visualize.py
173
"""Functions that could be used to visualize Tensors. This is adapted from the old-time iceberk package that Yangqing wrote... Oh gold memories. Before decaf and caffe. Why iceberk? Because I was at Berkeley, bears are vegetarian, and iceberg lettuce has layers of leaves. (This joke is so lame.) """ import numpy as np from matplotlib import cm, pyplot def ChannelFirst(arr): """Convert a HWC array to CHW.""" ndim = arr.ndim return arr.swapaxes(ndim - 1, ndim - 2).swapaxes(ndim - 2, ndim - 3) def ChannelLast(arr): """Convert a CHW array to HWC.""" ndim = arr.ndim return arr.swapaxes(ndim - 3, ndim - 2).swapaxes(ndim - 2, ndim - 1) class PatchVisualizer(object): """PatchVisualizer visualizes patches. """ def __init__(self, gap=1): self.gap = gap def ShowSingle(self, patch, cmap=None): """Visualizes one single patch. The input patch could be a vector (in which case we try to infer the shape of the patch), a 2-D matrix, or a 3-D matrix whose 3rd dimension has 3 channels. """ if len(patch.shape) == 1: patch = patch.reshape(self.get_patch_shape(patch)) elif len(patch.shape) > 2 and patch.shape[2] != 3: raise ValueError("The input patch shape isn't correct.") # determine color if len(patch.shape) == 2 and cmap is None: cmap = cm.gray pyplot.imshow(patch, cmap=cmap) return patch def ShowMultiple(self, patches, ncols=None, cmap=None, bg_func=np.mean): """Visualize multiple patches. In the passed in patches matrix, each row is a patch, in the shape of either n*n, n*n*1 or n*n*3, either in a flattened format (so patches would be a 2-D array), or a multi-dimensional tensor. We will try our best to figure out automatically the patch size. """ num_patches = patches.shape[0] if ncols is None: ncols = int(np.ceil(np.sqrt(num_patches))) nrows = int(np.ceil(num_patches / float(ncols))) if len(patches.shape) == 2: patches = patches.reshape( (patches.shape[0], ) + self.get_patch_shape(patches[0]) ) patch_size_expand = np.array(patches.shape[1:3]) + self.gap image_size = patch_size_expand * np.array([nrows, ncols]) - self.gap if len(patches.shape) == 4: if patches.shape[3] == 1: # gray patches patches = patches.reshape(patches.shape[:-1]) image_shape = tuple(image_size) if cmap is None: cmap = cm.gray elif patches.shape[3] == 3: # color patches image_shape = tuple(image_size) + (3, ) else: raise ValueError("The input patch shape isn't expected.") else: image_shape = tuple(image_size) if cmap is None: cmap = cm.gray image = np.ones(image_shape) * bg_func(patches) for pid in range(num_patches): row = pid / ncols * patch_size_expand[0] col = pid % ncols * patch_size_expand[1] image[row:row+patches.shape[1], col:col+patches.shape[2]] = \ patches[pid] pyplot.imshow(image, cmap=cmap, interpolation='nearest') pyplot.axis('off') return image def ShowImages(self, patches, *args, **kwargs): """Similar to ShowMultiple, but always normalize the values between 0 and 1 for better visualization of image-type data. """ patches = patches - np.min(patches) patches /= np.max(patches) + np.finfo(np.float64).eps return self.ShowMultiple(patches, *args, **kwargs) def ShowChannels(self, patch, cmap=None, bg_func=np.mean): """ This function shows the channels of a patch. The incoming patch should have shape [w, h, num_channels], and each channel will be visualized as a separate gray patch. """ if len(patch.shape) != 3: raise ValueError("The input patch shape isn't correct.") patch_reordered = np.swapaxes(patch.T, 1, 2) return self.ShowMultiple(patch_reordered, cmap=cmap, bg_func=bg_func) def get_patch_shape(self, patch): """Gets the shape of a single patch. Basically it tries to interprete the patch as a square, and also check if it is in color (3 channels) """ edgeLen = np.sqrt(patch.size) if edgeLen != np.floor(edgeLen): # we are given color patches edgeLen = np.sqrt(patch.size / 3.) if edgeLen != np.floor(edgeLen): raise ValueError("I can't figure out the patch shape.") return (edgeLen, edgeLen, 3) else: edgeLen = int(edgeLen) return (edgeLen, edgeLen) _default_visualizer = PatchVisualizer() """Utility functions that directly point to functions in the default visualizer. These functions don't return anything, so you won't see annoying printouts of the visualized images. If you want to save the images for example, you should explicitly instantiate a patch visualizer, and call those functions. """ class NHWC(object): @staticmethod def ShowSingle(*args, **kwargs): _default_visualizer.ShowSingle(*args, **kwargs) @staticmethod def ShowMultiple(*args, **kwargs): _default_visualizer.ShowMultiple(*args, **kwargs) @staticmethod def ShowImages(*args, **kwargs): _default_visualizer.ShowImages(*args, **kwargs) @staticmethod def ShowChannels(*args, **kwargs): _default_visualizer.ShowChannels(*args, **kwargs) class NCHW(object): @staticmethod def ShowSingle(patch, *args, **kwargs): _default_visualizer.ShowSingle(ChannelLast(patch), *args, **kwargs) @staticmethod def ShowMultiple(patch, *args, **kwargs): _default_visualizer.ShowMultiple(ChannelLast(patch), *args, **kwargs) @staticmethod def ShowImages(patch, *args, **kwargs): _default_visualizer.ShowImages(ChannelLast(patch), *args, **kwargs) @staticmethod def ShowChannels(patch, *args, **kwargs): _default_visualizer.ShowChannels(ChannelLast(patch), *args, **kwargs)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/control_test.py
331
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import control, core, test_util, workspace import logging logger = logging.getLogger(__name__) class TestControl(test_util.TestCase): def setUp(self): super(TestControl, self).setUp() self.N_ = 10 self.init_net_ = core.Net("init-net") cnt = self.init_net_.CreateCounter([], init_count=0) const_n = self.init_net_.ConstantFill( [], shape=[], value=self.N_, dtype=core.DataType.INT64) const_0 = self.init_net_.ConstantFill( [], shape=[], value=0, dtype=core.DataType.INT64) self.cnt_net_ = core.Net("cnt-net") self.cnt_net_.CountUp([cnt]) curr_cnt = self.cnt_net_.RetrieveCount([cnt]) self.init_net_.ConstantFill( [], [curr_cnt], shape=[], value=0, dtype=core.DataType.INT64) self.cnt_net_.AddExternalOutput(curr_cnt) self.cnt_2_net_ = core.Net("cnt-2-net") self.cnt_2_net_.CountUp([cnt]) self.cnt_2_net_.CountUp([cnt]) curr_cnt_2 = self.cnt_2_net_.RetrieveCount([cnt]) self.init_net_.ConstantFill( [], [curr_cnt_2], shape=[], value=0, dtype=core.DataType.INT64) self.cnt_2_net_.AddExternalOutput(curr_cnt_2) self.cond_net_ = core.Net("cond-net") cond_blob = self.cond_net_.LT([curr_cnt, const_n]) self.cond_net_.AddExternalOutput(cond_blob) self.not_cond_net_ = core.Net("not-cond-net") cond_blob = self.not_cond_net_.GE([curr_cnt, const_n]) self.not_cond_net_.AddExternalOutput(cond_blob) self.true_cond_net_ = core.Net("true-cond-net") true_blob = self.true_cond_net_.LT([const_0, const_n]) self.true_cond_net_.AddExternalOutput(true_blob) self.false_cond_net_ = core.Net("false-cond-net") false_blob = self.false_cond_net_.GT([const_0, const_n]) self.false_cond_net_.AddExternalOutput(false_blob) self.idle_net_ = core.Net("idle-net") self.idle_net_.ConstantFill( [], shape=[], value=0, dtype=core.DataType.INT64) def CheckNetOutput(self, nets_and_expects): """ Check the net output is expected nets_and_expects is a list of tuples (net, expect) """ for net, expect in nets_and_expects: output = workspace.FetchBlob( net.Proto().external_output[-1]) self.assertEqual(output, expect) def CheckNetAllOutput(self, net, expects): """ Check the net output is expected expects is a list of bools. """ self.assertEqual(len(net.Proto().external_output), len(expects)) for i in range(len(expects)): output = workspace.FetchBlob( net.Proto().external_output[i]) self.assertEqual(output, expects[i]) def BuildAndRunPlan(self, step): plan = core.Plan("test") plan.AddStep(control.Do('init', self.init_net_)) plan.AddStep(step) self.assertEqual(workspace.RunPlan(plan), True) def ForLoopTest(self, nets_or_steps): step = control.For('myFor', nets_or_steps, self.N_) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, self.N_)]) def testForLoopWithNets(self): self.ForLoopTest(self.cnt_net_) self.ForLoopTest([self.cnt_net_, self.idle_net_]) def testForLoopWithStep(self): step = control.Do('count', self.cnt_net_) self.ForLoopTest(step) self.ForLoopTest([step, self.idle_net_]) def WhileLoopTest(self, nets_or_steps): step = control.While('myWhile', self.cond_net_, nets_or_steps) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, self.N_)]) def testWhileLoopWithNet(self): self.WhileLoopTest(self.cnt_net_) self.WhileLoopTest([self.cnt_net_, self.idle_net_]) def testWhileLoopWithStep(self): step = control.Do('count', self.cnt_net_) self.WhileLoopTest(step) self.WhileLoopTest([step, self.idle_net_]) def UntilLoopTest(self, nets_or_steps): step = control.Until('myUntil', self.not_cond_net_, nets_or_steps) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, self.N_)]) def testUntilLoopWithNet(self): self.UntilLoopTest(self.cnt_net_) self.UntilLoopTest([self.cnt_net_, self.idle_net_]) def testUntilLoopWithStep(self): step = control.Do('count', self.cnt_net_) self.UntilLoopTest(step) self.UntilLoopTest([step, self.idle_net_]) def DoWhileLoopTest(self, nets_or_steps): step = control.DoWhile('myDoWhile', self.cond_net_, nets_or_steps) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, self.N_)]) def testDoWhileLoopWithNet(self): self.DoWhileLoopTest(self.cnt_net_) self.DoWhileLoopTest([self.idle_net_, self.cnt_net_]) def testDoWhileLoopWithStep(self): step = control.Do('count', self.cnt_net_) self.DoWhileLoopTest(step) self.DoWhileLoopTest([self.idle_net_, step]) def DoUntilLoopTest(self, nets_or_steps): step = control.DoUntil('myDoUntil', self.not_cond_net_, nets_or_steps) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, self.N_)]) def testDoUntilLoopWithNet(self): self.DoUntilLoopTest(self.cnt_net_) self.DoUntilLoopTest([self.cnt_net_, self.idle_net_]) def testDoUntilLoopWithStep(self): step = control.Do('count', self.cnt_net_) self.DoUntilLoopTest(step) self.DoUntilLoopTest([self.idle_net_, step]) def IfCondTest(self, cond_net, expect, cond_on_blob): if cond_on_blob: step = control.Do( 'if-all', control.Do('count', cond_net), control.If('myIf', cond_net.Proto().external_output[-1], self.cnt_net_)) else: step = control.If('myIf', cond_net, self.cnt_net_) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, expect)]) def testIfCondTrueOnNet(self): self.IfCondTest(self.true_cond_net_, 1, False) def testIfCondTrueOnBlob(self): self.IfCondTest(self.true_cond_net_, 1, True) def testIfCondFalseOnNet(self): self.IfCondTest(self.false_cond_net_, 0, False) def testIfCondFalseOnBlob(self): self.IfCondTest(self.false_cond_net_, 0, True) def IfElseCondTest(self, cond_net, cond_value, expect, cond_on_blob): if cond_value: run_net = self.cnt_net_ else: run_net = self.cnt_2_net_ if cond_on_blob: step = control.Do( 'if-else-all', control.Do('count', cond_net), control.If('myIfElse', cond_net.Proto().external_output[-1], self.cnt_net_, self.cnt_2_net_)) else: step = control.If('myIfElse', cond_net, self.cnt_net_, self.cnt_2_net_) self.BuildAndRunPlan(step) self.CheckNetOutput([(run_net, expect)]) def testIfElseCondTrueOnNet(self): self.IfElseCondTest(self.true_cond_net_, True, 1, False) def testIfElseCondTrueOnBlob(self): self.IfElseCondTest(self.true_cond_net_, True, 1, True) def testIfElseCondFalseOnNet(self): self.IfElseCondTest(self.false_cond_net_, False, 2, False) def testIfElseCondFalseOnBlob(self): self.IfElseCondTest(self.false_cond_net_, False, 2, True) def IfNotCondTest(self, cond_net, expect, cond_on_blob): if cond_on_blob: step = control.Do( 'if-not', control.Do('count', cond_net), control.IfNot('myIfNot', cond_net.Proto().external_output[-1], self.cnt_net_)) else: step = control.IfNot('myIfNot', cond_net, self.cnt_net_) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, expect)]) def testIfNotCondTrueOnNet(self): self.IfNotCondTest(self.true_cond_net_, 0, False) def testIfNotCondTrueOnBlob(self): self.IfNotCondTest(self.true_cond_net_, 0, True) def testIfNotCondFalseOnNet(self): self.IfNotCondTest(self.false_cond_net_, 1, False) def testIfNotCondFalseOnBlob(self): self.IfNotCondTest(self.false_cond_net_, 1, True) def IfNotElseCondTest(self, cond_net, cond_value, expect, cond_on_blob): if cond_value: run_net = self.cnt_2_net_ else: run_net = self.cnt_net_ if cond_on_blob: step = control.Do( 'if-not-else', control.Do('count', cond_net), control.IfNot('myIfNotElse', cond_net.Proto().external_output[-1], self.cnt_net_, self.cnt_2_net_)) else: step = control.IfNot('myIfNotElse', cond_net, self.cnt_net_, self.cnt_2_net_) self.BuildAndRunPlan(step) self.CheckNetOutput([(run_net, expect)]) def testIfNotElseCondTrueOnNet(self): self.IfNotElseCondTest(self.true_cond_net_, True, 2, False) def testIfNotElseCondTrueOnBlob(self): self.IfNotElseCondTest(self.true_cond_net_, True, 2, True) def testIfNotElseCondFalseOnNet(self): self.IfNotElseCondTest(self.false_cond_net_, False, 1, False) def testIfNotElseCondFalseOnBlob(self): self.IfNotElseCondTest(self.false_cond_net_, False, 1, True) def testSwitch(self): step = control.Switch( 'mySwitch', (self.false_cond_net_, self.cnt_net_), (self.true_cond_net_, self.cnt_2_net_) ) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, 0), (self.cnt_2_net_, 2)]) def testSwitchNot(self): step = control.SwitchNot( 'mySwitchNot', (self.false_cond_net_, self.cnt_net_), (self.true_cond_net_, self.cnt_2_net_) ) self.BuildAndRunPlan(step) self.CheckNetOutput([(self.cnt_net_, 1), (self.cnt_2_net_, 0)]) def testBoolNet(self): bool_net = control.BoolNet(('a', True)) step = control.Do('bool', bool_net) self.BuildAndRunPlan(step) self.CheckNetAllOutput(bool_net, [True]) bool_net = control.BoolNet(('a', True), ('b', False)) step = control.Do('bool', bool_net) self.BuildAndRunPlan(step) self.CheckNetAllOutput(bool_net, [True, False]) bool_net = control.BoolNet([('a', True), ('b', False)]) step = control.Do('bool', bool_net) self.BuildAndRunPlan(step) self.CheckNetAllOutput(bool_net, [True, False]) def testCombineConditions(self): # combined by 'Or' combine_net = control.CombineConditions( 'test', [self.true_cond_net_, self.false_cond_net_], 'Or') step = control.Do('combine', self.true_cond_net_, self.false_cond_net_, combine_net) self.BuildAndRunPlan(step) self.CheckNetOutput([(combine_net, True)]) # combined by 'And' combine_net = control.CombineConditions( 'test', [self.true_cond_net_, self.false_cond_net_], 'And') step = control.Do('combine', self.true_cond_net_, self.false_cond_net_, combine_net) self.BuildAndRunPlan(step) self.CheckNetOutput([(combine_net, False)]) def testMergeConditionNets(self): # merged by 'Or' merge_net = control.MergeConditionNets( 'test', [self.true_cond_net_, self.false_cond_net_], 'Or') step = control.Do('merge', merge_net) self.BuildAndRunPlan(step) self.CheckNetOutput([(merge_net, True)]) # merged by 'And' merge_net = control.MergeConditionNets( 'test', [self.true_cond_net_, self.false_cond_net_], 'And') step = control.Do('merge', merge_net) self.BuildAndRunPlan(step) self.CheckNetOutput([(merge_net, False)])
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/experiments/python/SparseTransformer.py
189
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import workspace import scipy.sparse class NetDefNode(): def __init__(self, name, optype, p=None, op=None): self.name = name self.optype = optype self.ops = {} self.prev = {} self.insertInput(p) self.visited = False self.op = op def insertInput(self, p): """ Insert input of this op also maintain the output of previous op p: a node or a list of node """ if isinstance(p, list): for i in p: self.prev[i.name] = i i.ops[self.name] = self elif isinstance(p, NetDefNode): self.prev[p.name] = p p.ops[self.name] = self def deleteInput(self, p): if isinstance(p, NetDefNode): del self.prev[p.name] del p.ops[self.name] def maskNallocate(weight_name): """ Combine mask and weights create wcsr, iw, jw, return their names """ w = workspace.FetchBlob(weight_name) w_csr = scipy.sparse.csr_matrix(w) wcsr = w_csr.data iw = w_csr.indptr jw = w_csr.indices workspace.FeedBlob(weight_name + "wcsr", wcsr) workspace.FeedBlob(weight_name + "iw", iw) workspace.FeedBlob(weight_name + "jw", jw) return weight_name + "wcsr", weight_name + "iw", weight_name + "jw" def transFCRelu(cur, id2node, name2id, ops, model): """ Add trans before and after this FC_Prune->(Relu)->FC_Prune chain. """ # 1. add trans before the start of this chain # assuming that cur is an FC_Prune, and it has only one input pre = cur.prev.itervalues().next() # Create an node /op and insert it. # TODO(wyiming): check whether it is correct here current_blob = model.Transpose(cur.op.input[0], cur.op.input[0] + "_trans") # print model.net.Proto() trans_op = model.net.Proto().op[-1] trans_node = NetDefNode(trans_op.output[0], "Transpose", pre, trans_op) trans_node.visited = True pre_new = trans_node # 2. use while loop to visit the chain while True: # breakup with the parent cur.deleteInput(pre) if not (cur.optype == "FC_Prune" or cur.optype == "Relu"): print("Reaching the end of the chain") break if len(cur.ops) > 1: print("A FC/Relu giving more than 1 useful outputs") if cur.optype == "FC_Prune": op = cur.op wcsr, iw, jw = maskNallocate(op.input[1]) bias_name = op.input[3] # TODO(wyiming): create a new Op here current_blob = model.FC_Sparse(current_blob, cur.op.output[0] + "_Sparse", wcsr, iw, jw, bias_name) sps_op = model.net.Proto().op[-1] sps_node = NetDefNode(cur.op.output[0] + "_Sparse", "FC_Sparse", pre_new, sps_op) sps_node.visited = True pre_new = sps_node if cur.optype == "Relu": op = cur.op current_blob = model.Relu(current_blob, current_blob) rel_op = model.net.Proto().op[-1] rel_node = NetDefNode(str(current_blob), "Relu", pre_new, rel_op) rel_node.visited = True pre_new = rel_node cur.visited = True pre = cur flag = False for _, temp in cur.ops.iteritems(): if temp.optype == "Relu" or temp.optype == "FC_Prune": flag = True cur = temp if not flag: # assume that there is only 1 output that is not PrintOP cur = cur.ops.itervalues().next() cur.deleteInput(pre) print("No FC/RElu children") print(cur.op.type) break # 3. add trans after this chain like 1. current_blob = model.Transpose(current_blob, pre.op.output[0]) trans_op = model.net.Proto().op[-1] trans_node = NetDefNode(str(current_blob), "Transpose", pre_new, trans_op) trans_node.visited = True cur.insertInput(trans_node) print(cur.prev) print(trans_node.ops) def Prune2Sparse(cur, id2node, name2id, ops, model): # Assume that FC and Relu takes in only 1 input; # If not raise warning if not cur.visited and cur.optype == "FC_Prune": transFCRelu(cur, id2node, name2id, ops, model) cur.visited = True for name, n in cur.ops.iteritems(): Prune2Sparse(n, id2node, name2id, ops, model) def net2list(net_root): """ Use topological order(BFS) to print the op of a net in a list """ bfs_queue = [] op_list = [] cur = net_root for _, n in cur.ops.iteritems(): bfs_queue.append(n) while bfs_queue: node = bfs_queue[0] bfs_queue = bfs_queue[1:] op_list.append(node.op) for _, n in node.ops.iteritems(): bfs_queue.append(n) return op_list def netbuilder(model): print("Welcome to model checker") proto = model.net.Proto() net_name2id = {} net_id2node = {} net_root = NetDefNode("net_root", "root", None) for op_id, op in enumerate(proto.op): if op.type == "Print": continue op_name = '%s/%s (op#%d)' % (op.name, op.type, op_id) \ if op.name else '%s (op#%d)' % (op.type, op_id) # print(op_name) op_node = NetDefNode(op_name, op.type, op=op) net_id2node[op_id] = op_node if_has_layer_input = False for input_name in op.input: if input_name not in net_name2id: # assume that un_occured name are non_layers # TODO: write a non-layer checker and log it continue op_node.insertInput(net_id2node[net_name2id[input_name]]) if_has_layer_input = True if not if_has_layer_input: op_node.insertInput(net_root) for output_name in op.output: net_name2id[output_name] = op_id return net_root, net_name2id, net_id2node
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/checkpoint.py
272
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import logging from caffe2.python import core, context from caffe2.python.task import Node, Task, TaskGroup, TaskOutput, WorkspaceType logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) @context.define_context() class Job(object): """ A Job defines three TaskGroups: the `init_group`, the `epoch_group` and the `exit_group` which will be run by a JobRunner. The `init_group` will be run only once at startup. Its role is to initialize globally persistent blobs such as model weights, accumulators and data file lists. The `epoch_group` will be run in a loop after init_group. The loop will exit when any of the stop signals added with `add_stop_signal` is True at the end of an epoch. The `exit_group` will be run only once at the very end of the job, when one of the stopping criterias for `epoch_group` was met. The role of this group is save the results of training in the end of the job. Jobs are context-driven, so that Tasks can be added to the active Job without having to explicitly pass the job object around. Example of usage: def build_reader(partitions): with Job.current().init_group: reader = HiveReader(init_reader, ..., partitions) Task(step=init_reader) with Job.current().epoch_group: limited_reader = ReaderWithLimit(reader, num_iter=10000) data_queue = pipe(limited_reader, num_threads=8) Job.current().add_stop_signal(limited_reader.data_finished()) return data_queue def build_hogwild_trainer(reader, model): with Job.current().init_group: Task(step=model.param_init_net) with Job.current().epoch_group: pipe(reader, processor=model, num_threads=8) with Job.current().exit_group: Task(step=model.save_model_net) with Job() as job: reader = build_reader(partitions) model = build_model(params) build_hogwild_trainer(reader, model) """ def __init__(self): self.init_group = TaskGroup(workspace_type=WorkspaceType.GLOBAL) self.epoch_group = TaskGroup() self.exit_group = TaskGroup() self.stop_signals = [] def __enter__(self): self.epoch_group.__enter__() return self def __exit__(self, *args): self.epoch_group.__exit__() def add_stop_signal(self, output): if isinstance(output, core.BlobReference): t = Task(outputs=[output], group=self.epoch_group) output = t.outputs()[0] assert isinstance(output, TaskOutput) self.stop_signals.append(output) class CheckpointManager(object): """ Controls saving and loading of workspaces on every epoch boundary of a job. If a CheckpointManager instance is passed to JobRunner, then JobRunner will call `init`, `read` and `save` at different moments in between epoch runs. """ def __init__(self, db, db_type): self._db = db self._db_type = db_type # make sure these blobs are the first in the checkpoint file. self._net = core.Net('!!checkpoint_mngr') self._blob_names = self._net.AddExternalInput('blob_names') self._names_output = None def init(self, nodes=None, retrieve_from_epoch=None): """ Build a Task that will be run once after the job's `init_group` is run. This task will determine which blobs need to be checkpointed. If retrieve_from_epoch is not None, then the checkpoint metadata is retrieved from a previously saved checkpoint. """ assert nodes is None or len(nodes) == 1, ( 'CheckpointManager only supports single node.') net = core.Net('get_blob_list') if retrieve_from_epoch is None: net.GetAllBlobNames( [], self._blob_names, include_shared=False) else: net.Load( [], self._blob_names, db=self._dbname(retrieve_from_epoch), db_type=self._db_type, absolute_path=True) task = Task(step=net, outputs=[self._blob_names]) self._names_output = task.outputs()[0] return task def blob_list(self): assert self._names_output return self._names_output.fetch().tolist() def _dbname(self, epoch): return '%s.%06d' % (self._db, epoch) def load(self, epoch): """ Build a Task that will be run by JobRunner when the job is to be resumed from a given epoch. This task will run a Load op that will load and deserialize all relevant blobs from a persistent storage. """ net = core.Net('get_blob_list') net.Load( [], self.blob_list(), db=self._dbname(epoch), db_type=self._db_type, absolute_path=True) return Task(step=net) def save(self, epoch): """ Build a Task that is run once after `init_group` and after each epoch is run. This will execute a Save ops to serialize and persist blobs present in the global workspaace. """ net = core.Net('checkpoint_save') net.Save( self.blob_list(), [], db=self._dbname(epoch), db_type=self._db_type, absolute_path=True) return Task(step=net) class MultiNodeCheckpointManager(object): """ Coordinates checkpointing and checkpointing across multiple nodes. Each of `init`, `load` and `save` will build TaskGroups which will trigger checkpointing on each of the nodes involved in a distributed job. """ def __init__( self, db_prefix, db_type, node_manager_class=CheckpointManager): self._node_manager_class = node_manager_class self._node_managers = None self._db_prefix = db_prefix self._db_type = db_type def _task_group(self, func, *args, **kw): assert self._node_managers is not None, 'init must be called first.' with TaskGroup(WorkspaceType.GLOBAL) as task_group: for node, manager in self._node_managers: with Node(node): func(manager, *args, **kw) return task_group def init(self, nodes, retrieve_from_epoch=None): if self._node_managers is not None: assert [node for node, _ in self._node_managers] == nodes return self._node_managers = [] for node in nodes: with Node(node): manager = self._node_manager_class( db=os.path.join(self._db_prefix, node), db_type=self._db_type) self._node_managers.append((node, manager)) return self._task_group( self._node_manager_class.init, nodes=[node], retrieve_from_epoch=retrieve_from_epoch) def load(self, epoch): return self._task_group(self._node_manager_class.load, epoch) def save(self, epoch): return self._task_group(self._node_manager_class.save, epoch) class JobRunner(object): """ Implement the runtime logic for jobs with checkpointing at the level of epoch. Can be used to run either single-host or distributed jobs. Job runner is a callable to be called once from the client, passing a Session as argument. This call will block until the Job execution is complete. If a checkpoint_manager is passed, checkpoints will be taken after initialization and after each epoch execution. If, in addition, `resume_from_epoch` is an epoch number, the corresponding checkpoint will be loaded and job execution will continue from the given epoch. In this case, the job's init_group will not be run. Refer to checkpoint_test.py for an example. """ def __init__(self, job, checkpoint_manager=None, resume_from_epoch=None): self.resume_from_epoch = resume_from_epoch self.checkpoint = checkpoint_manager self.job = job def __call__(self, client): from_scratch = self.resume_from_epoch is None if from_scratch: client.run(self.job.init_group) if self.checkpoint: logger.info('Preparing checkpoint ...') client.run(self.checkpoint.init( self.job.init_group.used_nodes(), retrieve_from_epoch=self.resume_from_epoch)) if from_scratch: logger.info('Saving first checkpoint ...') client.run(self.checkpoint.save(0)) logger.info('First checkpoint saved.') else: logger.info('Loading checkpoint for epoch {} ...'.format( self.resume_from_epoch)) client.run(self.checkpoint.load(self.resume_from_epoch)) logger.info('Checkpoint loaded.') epoch = 1 if from_scratch else self.resume_from_epoch + 1 while True: logger.info('Starting epoch %d.' % epoch) client.run(self.job.epoch_group) logger.info('Ran epoch %d.' % epoch) stop_signals = [o.fetch() for o in self.job.stop_signals] if self.checkpoint: logger.info('Saving checkpoint ...') client.run(self.checkpoint.save(epoch)) logger.info('Checkpoint saved.') if any(stop_signals): logger.info('Stopping.') break epoch += 1 client.run(self.job.exit_group) return epoch def epoch_limiter(num_epochs): """ Creates a task that will output True when a given number of epochs has finished. """ with Job.current().init_group: init_net = core.Net('epoch_counter_init') counter = init_net.CreateCounter([], init_count=num_epochs - 1) Task(step=init_net) epoch_net = core.Net('epoch_countdown') finished = epoch_net.CountDown(counter) output = Task(step=epoch_net, outputs=finished).outputs()[0] Job.current().add_stop_signal(output)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/experiments/python/cifar10_training.py
507
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import os import sys from libfb import pyinit from caffe2.python import core, cnn, workspace from caffe2.python import SparseTransformer import caffe2.python.models.resnet as resnet def AddInput(model, batch_size, db, db_type): """Adds the data input part.""" # Load the data from a DB. data_uint8, label_orig = model.TensorProtosDBInput( [], ["data_uint8", "label_orig"], batch_size=batch_size, db=db, db_type=db_type) # Since we are going to do float computations, what we will do is to cast # the data to float. data = model.Cast(data_uint8, "data_nhwc", to=core.DataType.FLOAT) data = model.NHWC2NCHW(data, "data") data = model.Scale(data, data, scale=float(1. / 256)) data = model.StopGradient(data, data) # Flatten the label label = model.net.FlattenToVec(label_orig, "label") return data, label def AddAccuracy(model, softmax, label): """Adds an accuracy op to the model""" accuracy = model.Accuracy([softmax, label], "accuracy") return accuracy def AddTrainingOperators(model, softmax, label, nn_model): """Adds training operators to the model.""" xent = model.LabelCrossEntropy([softmax, label], 'xent') loss = model.AveragedLoss(xent, "loss") # For bookkeeping purposes, we will also compute the accuracy of the model. AddAccuracy(model, softmax, label) # Now, this is the key part of the training model: we add all the gradient # operators to the model. The gradient is computed with respect to the loss # that we computed above. model.AddGradientOperators([loss]) # Now, here what we will do is a very simple stochastic gradient descent. ITER = model.Iter("iter") # We do a simple learning rate schedule where lr = base_lr * (t ^ gamma) # Note that we are doing minimization, so the base_lr is negative so we are # going the DOWNHILL direction. LR = model.LearningRate( ITER, "LR", base_lr=-0.01, policy="step", stepsize=15000, gamma=0.5) # ONE is a constant value that is used in the gradient update. We only need # to create it once, so it is explicitly placed in param_init_net. ONE = model.param_init_net.ConstantFill([], "ONE", shape=[1], value=1.0) # Now, for each parameter, we do the gradient updates. for param in model.params: # Note how we get the gradient of each parameter - CNNModelHelper keeps # track of that. param_grad = model.param_to_grad[param] # The update is a simple weighted sum: param = param + param_grad * LR model.WeightedSum([param, ONE, param_grad, LR], param) def AddBookkeepingOperators(model): """This adds a few bookkeeping operators that we can inspect later. These operators do not affect the training procedure: they only collect statistics and prints them to file or to logs. """ # Print basically prints out the content of the blob. to_file=1 routes the # printed output to a file. The file is going to be stored under # root_folder/[blob name] model.Print('accuracy', [], to_file=1) model.Print('loss', [], to_file=1) # Summarizes the parameters. Different from Print, Summarize gives some # statistics of the parameter, such as mean, std, min and max. for param in model.params: model.Summarize(param, [], to_file=1) model.Summarize(model.param_to_grad[param], [], to_file=1) # Now, if we really want to be very verbose, we can summarize EVERY blob # that the model produces; it is probably not a good idea, because that # is going to take time - summarization do not come for free. For this # demo, we will only show how to summarize the parameters and their # gradients. def AlexNet(model, data, args): conv1 = model.Conv( data, "conv1", 3, 64, 5, ('XavierFill', {}), ('ConstantFill', {}), pad=2 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=3, stride=2) conv2 = model.Conv( pool1, "conv2", 64, 192, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=3, stride=2) conv3 = model.Conv( pool2, "conv3", 192, 384, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = model.Relu(conv3, "conv3") conv4 = model.Conv( relu3, "conv4", 384, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = model.Relu(conv4, "conv4") conv5 = model.Conv( relu4, "conv5", 256, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = model.Relu(conv5, "conv5") pool5 = model.MaxPool(relu5, "pool5", kernel=3, stride=2) fc6 = model.FC( pool5, "fc6", 256 * 3 * 3, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu6 = model.Relu(fc6, "fc6") fc7 = model.FC( relu6, "fc7", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {}) ) relu7 = model.Relu(fc7, "fc7") fc8 = model.FC( relu7, "fc8", 4096, 10, ('XavierFill', {}), ('ConstantFill', {}) ) softmax = model.Softmax(fc8, "pred") return softmax def AlexNet_Prune(model, data, args): conv1 = model.Conv( data, "conv1", 3, 64, 5, ('XavierFill', {}), ('ConstantFill', {}), pad=2 ) relu1 = model.Relu(conv1, "conv1") pool1 = model.MaxPool(relu1, "pool1", kernel=3, stride=2) conv2 = model.Conv( pool1, "conv2", 64, 192, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu2 = model.Relu(conv2, "conv2") pool2 = model.MaxPool(relu2, "pool2", kernel=3, stride=2) conv3 = model.Conv( pool2, "conv3", 192, 384, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu3 = model.Relu(conv3, "conv3") conv4 = model.Conv( relu3, "conv4", 384, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu4 = model.Relu(conv4, "conv4") conv5 = model.Conv( relu4, "conv5", 256, 256, 3, ('XavierFill', {}), ('ConstantFill', {}), pad=1 ) relu5 = model.Relu(conv5, "conv5") pool5 = model.MaxPool(relu5, "pool5", kernel=3, stride=2) fc6 = model.FC_Prune( pool5, "fc6", 256 * 3 * 3, 4096, ('XavierFill', {}), ('ConstantFill', {}), mask_init=None, threshold=args.prune_thres * 2, need_compress_rate=True, comp_lb=args.comp_lb ) compress_fc6 = fc6[1] model.Print(compress_fc6, [], to_file=0) fc6 = fc6[0] relu6 = model.Relu(fc6, "fc6") fc7 = model.FC_Prune( relu6, "fc7", 4096, 4096, ('XavierFill', {}), ('ConstantFill', {}), mask_init=None, threshold=args.prune_thres, need_compress_rate=True, comp_lb=args.comp_lb ) compress_fc7 = fc7[1] model.Print(compress_fc7, [], to_file=0) fc7 = fc7[0] relu7 = model.Relu(fc7, "fc7") fc8 = model.FC( relu7, "fc8", 4096, 10, ('XavierFill', {}), ('ConstantFill', {}) ) softmax = model.Softmax(fc8, "pred") return softmax def ConvBNReLUDrop(model, currentblob, outputblob, input_dim, output_dim, drop_ratio=None): currentblob = model.Conv( currentblob, outputblob, input_dim, output_dim, 3, ('XavierFill', {}), ('ConstantFill', {}), stride=1, pad=1 ) currentblob = model.SpatialBN(currentblob, str(currentblob) + '_bn', output_dim, epsilon=1e-3) currentblob = model.Relu(currentblob, currentblob) if drop_ratio: currentblob = model.Dropout(currentblob, str(currentblob) + '_dropout', ratio=drop_ratio) return currentblob def VGG(model, data, args): """Adds the VGG-Like kaggle winner Model on Cifar-10 The original blog about the model can be found on: http://torch.ch/blog/2015/07/30/cifar.html """ conv1 = ConvBNReLUDrop(model, data, 'conv1', 3, 64, drop_ratio=0.3) conv2 = ConvBNReLUDrop(model, conv1, 'conv2', 64, 64) pool2 = model.MaxPool(conv2, 'pool2', kernel=2, stride=1) conv3 = ConvBNReLUDrop(model, pool2, 'conv3', 64, 128, drop_ratio=0.4) conv4 = ConvBNReLUDrop(model, conv3, 'conv4', 128, 128) pool4 = model.MaxPool(conv4, 'pool4', kernel=2, stride=2) conv5 = ConvBNReLUDrop(model, pool4, 'conv5', 128, 256, drop_ratio=0.4) conv6 = ConvBNReLUDrop(model, conv5, 'conv6', 256, 256, drop_ratio=0.4) conv7 = ConvBNReLUDrop(model, conv6, 'conv7', 256, 256) pool7 = model.MaxPool(conv7, 'pool7', kernel=2, stride=2) conv8 = ConvBNReLUDrop(model, pool7, 'conv8', 256, 512, drop_ratio=0.4) conv9 = ConvBNReLUDrop(model, conv8, 'conv9', 512, 512, drop_ratio=0.4) conv10 = ConvBNReLUDrop(model, conv9, 'conv10', 512, 512) pool10 = model.MaxPool(conv10, 'pool10', kernel=2, stride=2) conv11 = ConvBNReLUDrop(model, pool10, 'conv11', 512, 512, drop_ratio=0.4) conv12 = ConvBNReLUDrop(model, conv11, 'conv12', 512, 512, drop_ratio=0.4) conv13 = ConvBNReLUDrop(model, conv12, 'conv13', 512, 512) pool13 = model.MaxPool(conv13, 'pool13', kernel=2, stride=2) fc14 = model.FC( pool13, "fc14", 512, 512, ('XavierFill', {}), ('ConstantFill', {}) ) relu14 = model.Relu(fc14, "fc14") pred = model.FC( relu14, "pred", 512, 10, ('XavierFill', {}), ('ConstantFill', {}) ) softmax = model.Softmax(pred, 'softmax') return softmax def ResNet110(model, data, args): """ Residual net as described in section 4.2 of He at. al. (2015) """ return resnet.create_resnet_32x32( model, data, num_input_channels=3, num_groups=18, num_labels=10, ) def ResNet20(model, data, args): """ Residual net as described in section 4.2 of He at. al. (2015) """ return resnet.create_resnet_32x32( model, data, num_input_channels=3, num_groups=3, num_labels=10, ) def sparse_transform(model): print("====================================================") print(" Sparse Transformer ") print("====================================================") net_root, net_name2id, net_id2node = SparseTransformer.netbuilder(model) SparseTransformer.Prune2Sparse( net_root, net_id2node, net_name2id, model.net.Proto().op, model) op_list = SparseTransformer.net2list(net_root) del model.net.Proto().op[:] model.net.Proto().op.extend(op_list) def test_sparse(test_model): # Sparse Implementation sparse_transform(test_model) sparse_test_accuracy = np.zeros(100) for i in range(100): workspace.RunNet(test_model.net.Proto().name) sparse_test_accuracy[i] = workspace.FetchBlob('accuracy') # After the execution is done, let's plot the values. print('Sparse Test Accuracy:') print(sparse_test_accuracy) print('sparse_test_accuracy: %f' % sparse_test_accuracy.mean()) def trainNtest(model_gen, args): print("Print running on GPU: %s" % args.gpu) train_model = cnn.CNNModelHelper( "NCHW", name="Cifar_%s" % (args.model), use_cudnn=True, cudnn_exhaustive_search=True) data, label = AddInput( train_model, batch_size=64, db=args.train_input_path, db_type=args.db_type) softmax = model_gen(train_model, data, args) AddTrainingOperators(train_model, softmax, label, args.model) AddBookkeepingOperators(train_model) if args.gpu: train_model.param_init_net.RunAllOnGPU() train_model.net.RunAllOnGPU() # The parameter initialization network only needs to be run once. workspace.RunNetOnce(train_model.param_init_net) # Now, since we are going to run the main network multiple times, # we first create the network - which puts the actual network generated # from the protobuf into the workspace - and then call RunNet by # its name. workspace.CreateNet(train_model.net) # On the Python side, we will create two numpy arrays to record the accuracy # and loss for each iteration. epoch_num = 200 epoch_iters = 1000 record = 1000 accuracy = np.zeros(int(epoch_num * epoch_iters / record)) loss = np.zeros(int(epoch_num * epoch_iters / record)) # Now, we will manually run the network for 200 iterations. for e in range(epoch_num): for i in range(epoch_iters): workspace.RunNet(train_model.net.Proto().name) if i % record is 0: count = int(i / record) accuracy[count] = workspace.FetchBlob('accuracy') loss[count] = workspace.FetchBlob('loss') print('Train Loss: {}'.format(loss[count])) print('Train Accuracy: {}'.format(accuracy[count])) # Testing model. We will set the batch size to 100, so that the testing # pass is 100 iterations (10,000 images in total). # For the testing model, we need the data input part, the main LeNetModel # part, and an accuracy part. Note that init_params is set False because # we will be using the parameters obtained from the test model. test_model = cnn.CNNModelHelper( order="NCHW", name="cifar10_test", init_params=False) data, label = AddInput( test_model, batch_size=100, db=args.test_input_path, db_type=args.db_type) softmax = model_gen(test_model, data, args) AddAccuracy(test_model, softmax, label) # In[11]: if args.gpu: test_model.param_init_net.RunAllOnGPU() test_model.net.RunAllOnGPU() # Now, remember that we created the test net? We will run the test # pass and report the test accuracy here. workspace.RunNetOnce(test_model.param_init_net) workspace.CreateNet(test_model.net) # On the Python side, we will create two numpy arrays to record the accuracy # and loss for each iteration. test_accuracy = np.zeros(100) for i in range(100): workspace.RunNet(test_model.net.Proto().name) test_accuracy[i] = workspace.FetchBlob('accuracy') print('Train Loss:') print(loss) print('Train Accuracy:') print(accuracy) print('Test Accuracy:') print(test_accuracy) print('test_accuracy: %f' % test_accuracy.mean()) if args.model == 'AlexNet_Prune': test_sparse(test_model) MODEL_TYPE_FUNCTIONS = { 'AlexNet': AlexNet, 'AlexNet_Prune': AlexNet_Prune, 'VGG': VGG, 'ResNet-110': ResNet110, 'ResNet-20': ResNet20 } if __name__ == '__main__': # it's hard to init flags correctly... so here it is sys.argv.append('--caffe2_keep_on_shrink') # FbcodeArgumentParser calls initFacebook which is necessary for NNLoader # initialization parser = pyinit.FbcodeArgumentParser(description='cifar-10 Tutorial') # arguments starting with single '-' are compatible with Lua parser.add_argument("--model", type=str, default='AlexNet', choices=MODEL_TYPE_FUNCTIONS.keys(), help="The batch size of benchmark data.") parser.add_argument("--prune_thres", type=float, default=0.0001, help="Pruning threshold for FC layers.") parser.add_argument("--comp_lb", type=float, default=0.02, help="Compression Lower Bound for FC layers.") parser.add_argument("--gpu", default=False, help="Whether to run on gpu", type=bool) parser.add_argument("--train_input_path", type=str, default=None, required=True, help="Path to the database for training data") parser.add_argument("--test_input_path", type=str, default=None, required=True, help="Path to the database for test data") parser.add_argument("--db_type", type=str, default="lmbd", help="Database type") args = parser.parse_args() # If you would like to see some really detailed initializations, # you can change --caffe2_log_level=0 to --caffe2_log_level=-1 core.GlobalInit(['caffe2', '--caffe2_log_level=0']) trainNtest(MODEL_TYPE_FUNCTIONS[args.model], args)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/core_test.py
280
import unittest import numpy as np from caffe2.proto import caffe2_pb2 from caffe2.python import core, workspace, test_util class TestScopes(test_util.TestCase): def testBlobReferenceIsIndependentFromNameScope(self): blob_v = core.BlobReference("v") with core.NameScope("foo"): blob_w = core.BlobReference("w") with core.NameScope("bar"): blob_x = core.BlobReference("x") self.assertEqual(str(blob_v), "v") self.assertEqual(str(blob_w), "w") self.assertEqual(str(blob_x), "x") def testNameScopeWithOp(self): global_x = core.BlobReference("x") global_y = core.BlobReference("y") with core.NameScope("foo"): # Raw strings should have namescope prepended. op = core.CreateOperator("Relu", "x", "y") self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "foo/x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "foo/y") # BlobReferences should not. op = core.CreateOperator("Relu", global_x, global_y) self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "y") def testNameScopeWithReset(self): with core.NameScope("foo"): # foo/ op = core.CreateOperator("Relu", "x", "y") self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "foo/x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "foo/y") with core.NameScope("bar"): # foo/bar/ op = core.CreateOperator("Relu", "x", "y") self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "foo/bar/x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "foo/bar/y") # Back to foo/ op = core.CreateOperator("Relu", "x", "y") self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "foo/x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "foo/y") with core.NameScope("bar", reset=True): # bar/ op = core.CreateOperator("Relu", "x", "y") self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "bar/x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "bar/y") # Back to foo/ op = core.CreateOperator("Relu", "x", "y") self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "foo/x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "foo/y") def testDeviceScope(self): # No device op = core.CreateOperator("Relu", "x", "y") self.assertFalse(op.HasField('device_option')) # explicitly setting a device device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CUDA device_option.cuda_gpu_id = 1 op = core.CreateOperator("Relu", "x", "y", device_option=device_option) self.assertTrue(op.HasField('device_option')) self.assertEqual(op.device_option.device_type, caffe2_pb2.CUDA) self.assertEqual(op.device_option.cuda_gpu_id, 1) with core.DeviceScope(device_option): # from device scope op = core.CreateOperator("Relu", "x", "y") self.assertTrue(op.HasField('device_option')) self.assertEqual(op.device_option.device_type, caffe2_pb2.CUDA) self.assertEqual(op.device_option.cuda_gpu_id, 1) # from an overridden device option override_device = caffe2_pb2.DeviceOption() override_device.device_type = caffe2_pb2.CPU op = core.CreateOperator( "Relu", "x", "y", device_option=override_device) self.assertTrue(op.HasField('device_option')) self.assertEqual(op.device_option.device_type, caffe2_pb2.CPU) # back from normal: no device op = core.CreateOperator("Relu", "x", "y") self.assertFalse(op.HasField('device_option')) device_option = caffe2_pb2.DeviceOption() def testNameAndDeviceScopeTogether(self): device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CUDA device_option.cuda_gpu_id = 1 with core.DeviceScope(device_option): with core.NameScope("foo"): op = core.CreateOperator("Relu", "x", "y") self.assertTrue(op.HasField('device_option')) self.assertEqual(op.device_option.device_type, caffe2_pb2.CUDA) self.assertEqual(op.device_option.cuda_gpu_id, 1) self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "foo/x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "foo/y") class TestCloneNet(test_util.TestCase): def testPartialClone(self): params = core.Net('params') p1 = params.ConstantFill([], ['p1']) workspace.CreateNet(params) workspace.RunNetOnce(params) n = core.Net('original') a1 = n.AddExternalInput('a1') a2 = n.AddExternalInput('a2') b1, b2 = n.Concat([a1, a2], ['b1', 'b2'], axis=0) c1 = n.Sum([b1, p1], ['c1']) c2 = n.Sum([b2], ['c2']) d = n.Sum([c1, c2], ['d']) # test that gradient ops are ignored when partial-cloning n.AddGradientOperators([d]) # test some in-place ops k = n.Sum([p1], ['k']) e = n.Sum([d], ['e']) e = n.Sum([e, k], [e]) e = n.Sum([e], [e]) f = n.Sum(e, ['f']) def net_assert(net, num_ops, inputs, outputs, internals): self.assertEqual(len(net.Proto().op), num_ops) self.assertEqual(set(net.Proto().external_input), inputs) self.assertEqual(set(net.Proto().external_output), outputs) all_blobs = set(net.Proto().external_input) all_blobs |= set(net.Proto().external_output) for op in net.Proto().op: all_blobs |= set(op.input) | set(op.output) self.assertEqual(all_blobs, inputs | outputs | internals) # create net to make sure its valid for input in inputs: workspace.FeedBlob(input, np.array([])) workspace.CreateNet(net) n2, (d22, ) = n.ClonePartial('f1', {a1: 'a11', a2: 'a22'}, [d]) net_assert( n2, 4, {'p1', 'a11', 'a22'}, {'f1/d'}, {'f1/b1', 'f1/b2', 'f1/c1', 'f1/c2', 'p1'}) self.assertTrue(isinstance(d22, core.BlobReference)) self.assertEqual(d22.Net(), n2) self.assertEqual(str(d22), 'f1/d') n3, (d22, ) = n.ClonePartial('f2', [b1, b2], [d]) net_assert( n3, 3, {'p1', 'b1', 'b2'}, {'f2/d'}, {'f2/c1', 'f2/c2', 'p1'}) self.assertEqual(str(d22), 'f2/d') n4, (c22, ) = n.ClonePartial('f3', [b1], [c1]) net_assert(n4, 1, {'p1', 'b1'}, {'f3/c1'}, {'p1'}) self.assertEqual(str(c22), 'f3/c1') n5, (c11, c22) = n.ClonePartial('f4', [b1, b2], [c1, c2]) net_assert(n5, 2, {'p1', 'b1', 'b2'}, {'f4/c1', 'f4/c2'}, {'p1'}) self.assertEqual(str(c11), 'f4/c1') self.assertEqual(str(c22), 'f4/c2') with self.assertRaises(AssertionError): n.ClonePartial('f4', [a1, a2, c2], [d]) n6, (e22, ) = n.ClonePartial('f5', [d], [e]) net_assert(n6, 4, {'p1', 'd'}, {'f5/e'}, {'f5/k', 'p1'}) self.assertEqual(str(e22), 'f5/e') n8, (e22, f22) = n.ClonePartial('f7', [d], [e, f]) net_assert(n8, 5, {'p1', 'd'}, {'f7/e', 'f7/f'}, {'p1', 'f7/k'}) self.assertEqual(str(e22), 'f7/e') self.assertEqual(str(f22), 'f7/f') params._CheckLookupTables() n._CheckLookupTables() class TestCreateOperator(test_util.TestCase): def testCreate(self): device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CUDA device_option.cuda_gpu_id = 1 op = core.CreateOperator( "Ludicrous", "x", "y", name="ludicrous", control_input="z", device_option=device_option, engine="WARP", arg1=1, arg2="2", arg3=[1, 2, 3]) self.assertEqual(op.type, "Ludicrous") self.assertEqual(op.name, "ludicrous") self.assertEqual(op.engine, "WARP") self.assertEqual(len(op.input), 1) self.assertEqual(op.input[0], "x") self.assertEqual(len(op.output), 1) self.assertEqual(op.output[0], "y") self.assertEqual(len(op.control_input), 1) self.assertEqual(op.control_input[0], "z") self.assertTrue(op.HasField('device_option')) self.assertEqual(op.device_option.device_type, caffe2_pb2.CUDA) self.assertEqual(op.device_option.cuda_gpu_id, 1) self.assertTrue(len(op.arg), 3) self.assertEqual(op.arg[0].name, "arg1") self.assertEqual(op.arg[1].name, "arg2") self.assertEqual(op.arg[2].name, "arg3") self.assertEqual(op.arg[0].i, 1) self.assertEqual(op.arg[1].s, "2") self.assertEqual(list(op.arg[2].ints), [1, 2, 3]) def testCreateWithNoneKwarg(self): with self.assertRaises(ValueError): core.CreateOperator("Ludicrous", "x", "y", arg1=None) class TestAutoNaming(test_util.TestCase): """ Test that operators are named with different names, and that automatically named blob names don't clash intra or inter networks. """ def test_auto_naming(self): a = core.Net('net') b = core.Net('net') self.assertNotEqual(a.Proto().name, b.Proto().name) a_in1 = a.AddExternalInput('a') b_in1 = b.AddExternalInput('b') all_outputs_single = [] all_outputs_list = [] def add_ops(): all_outputs_single.append(a.Sum([a_in1, a_in1])) all_outputs_single.append(a.Sum([a_in1, a_in1])) all_outputs_single.append(b.Sum([b_in1, b_in1])) all_outputs_single.append(b.Sum([b_in1, b_in1])) all_outputs_list.append(a.Sum([a_in1, a_in1], outputs=2)) all_outputs_list.append(a.Sum([a_in1, a_in1], outputs=2)) all_outputs_list.append(b.Sum([b_in1, b_in1], outputs=2)) all_outputs_list.append(b.Sum([b_in1, b_in1], outputs=2)) add_ops() with core.NameScope('n1'): add_ops() # Force reset of lookup tables dummy = a.Proto().name with core.NameScope('n2'): add_ops() all_outputs = [] for s in all_outputs_single: all_outputs.append(str(s)) for l in all_outputs_list: for o in l: all_outputs.append(str(o)) for i, o1 in enumerate(all_outputs): for j, o2 in enumerate(all_outputs): if i != j: self.assertNotEqual(str(o1), str(o2)) a._CheckLookupTables() b._CheckLookupTables() if __name__ == '__main__': unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/workspace_test.py
473
import numpy as np import os import unittest from caffe2.proto import caffe2_pb2 from caffe2.python import core, test_util, workspace import caffe2.python.hypothesis_test_util as htu import hypothesis.strategies as st from hypothesis import given from caffe2.proto import caffe2_pb2 class TestWorkspace(unittest.TestCase): def setUp(self): self.net = core.Net("test-net") self.testblob_ref = self.net.ConstantFill( [], "testblob", shape=[1, 2, 3, 4], value=1.0) workspace.ResetWorkspace() def testRootFolder(self): self.assertEqual(workspace.ResetWorkspace(), True) self.assertEqual(workspace.RootFolder(), ".") self.assertEqual( workspace.ResetWorkspace("/tmp/caffe-workspace-test"), True) self.assertEqual(workspace.RootFolder(), "/tmp/caffe-workspace-test") def testWorkspaceHasBlobWithNonexistingName(self): self.assertEqual(workspace.HasBlob("non-existing"), False) def testRunOperatorOnce(self): self.assertEqual( workspace.RunOperatorOnce( self.net.Proto().op[0].SerializeToString() ), True ) self.assertEqual(workspace.HasBlob("testblob"), True) blobs = workspace.Blobs() self.assertEqual(len(blobs), 1) self.assertEqual(blobs[0], "testblob") def testRunNetOnce(self): self.assertEqual( workspace.RunNetOnce(self.net.Proto().SerializeToString()), True) self.assertEqual(workspace.HasBlob("testblob"), True) def testCurrentWorkspaceWrapper(self): self.assertNotIn("testblob", workspace.C.Workspace.current.blobs) self.assertEqual( workspace.RunNetOnce(self.net.Proto().SerializeToString()), True) self.assertEqual(workspace.HasBlob("testblob"), True) self.assertIn("testblob", workspace.C.Workspace.current.blobs) workspace.ResetWorkspace() self.assertNotIn("testblob", workspace.C.Workspace.current.blobs) def testRunPlan(self): plan = core.Plan("test-plan") plan.AddStep(core.ExecutionStep("test-step", self.net)) self.assertEqual( workspace.RunPlan(plan.Proto().SerializeToString()), True) self.assertEqual(workspace.HasBlob("testblob"), True) def testConstructPlanFromSteps(self): step = core.ExecutionStep("test-step-as-plan", self.net) self.assertEqual(workspace.RunPlan(step), True) self.assertEqual(workspace.HasBlob("testblob"), True) def testResetWorkspace(self): self.assertEqual( workspace.RunNetOnce(self.net.Proto().SerializeToString()), True) self.assertEqual(workspace.HasBlob("testblob"), True) self.assertEqual(workspace.ResetWorkspace(), True) self.assertEqual(workspace.HasBlob("testblob"), False) def testTensorAccess(self): ws = workspace.C.Workspace() """ test in-place modification """ ws.create_blob("tensor").feed(np.array([1.1, 1.2, 1.3])) tensor = ws.blobs["tensor"].tensor() tensor.data[0] = 3.3 val = np.array([3.3, 1.2, 1.3]) np.testing.assert_array_equal(tensor.data, val) np.testing.assert_array_equal(ws.blobs["tensor"].fetch(), val) """ test in-place initialization """ tensor.init([2, 3], core.DataType.INT32) tensor.data[1, 1] = 100 val = np.zeros([2, 3], dtype=np.int32) val[1, 1] = 100 np.testing.assert_array_equal(tensor.data, val) np.testing.assert_array_equal(ws.blobs["tensor"].fetch(), val) """ strings cannot be initialized from python """ with self.assertRaises(RuntimeError): tensor.init([3, 4], core.DataType.STRING) """ feed (copy) data into tensor """ val = np.array([['abc', 'def'], ['ghi', 'jkl']], dtype=np.object) tensor.feed(val) self.assertEquals(tensor.data[0, 0], 'abc') np.testing.assert_array_equal(ws.blobs["tensor"].fetch(), val) val = np.array([1.1, 10.2]) tensor.feed(val) val[0] = 5.2 self.assertEquals(tensor.data[0], 1.1) """ fetch (copy) data from tensor """ val = np.array([1.1, 1.2]) tensor.feed(val) val2 = tensor.fetch() tensor.data[0] = 5.2 val3 = tensor.fetch() np.testing.assert_array_equal(val, val2) self.assertEquals(val3[0], 5.2) def testFetchFeedBlob(self): self.assertEqual( workspace.RunNetOnce(self.net.Proto().SerializeToString()), True) fetched = workspace.FetchBlob("testblob") # check if fetched is correct. self.assertEqual(fetched.shape, (1, 2, 3, 4)) np.testing.assert_array_equal(fetched, 1.0) fetched[:] = 2.0 self.assertEqual(workspace.FeedBlob("testblob", fetched), True) fetched_again = workspace.FetchBlob("testblob") self.assertEqual(fetched_again.shape, (1, 2, 3, 4)) np.testing.assert_array_equal(fetched_again, 2.0) def testFetchFeedBlobViaBlobReference(self): self.assertEqual( workspace.RunNetOnce(self.net.Proto().SerializeToString()), True) fetched = workspace.FetchBlob(self.testblob_ref) # check if fetched is correct. self.assertEqual(fetched.shape, (1, 2, 3, 4)) np.testing.assert_array_equal(fetched, 1.0) fetched[:] = 2.0 self.assertEqual(workspace.FeedBlob(self.testblob_ref, fetched), True) fetched_again = workspace.FetchBlob("testblob") # fetch by name now self.assertEqual(fetched_again.shape, (1, 2, 3, 4)) np.testing.assert_array_equal(fetched_again, 2.0) def testFetchFeedBlobTypes(self): for dtype in [np.float16, np.float32, np.float64, np.bool, np.int8, np.int16, np.int32, np.int64, np.uint8, np.uint16]: try: rng = np.iinfo(dtype).max * 2 except ValueError: rng = 1000 data = ((np.random.rand(2, 3, 4) - 0.5) * rng).astype(dtype) self.assertEqual(workspace.FeedBlob("testblob_types", data), True) fetched_back = workspace.FetchBlob("testblob_types") self.assertEqual(fetched_back.shape, (2, 3, 4)) self.assertEqual(fetched_back.dtype, dtype) np.testing.assert_array_equal(fetched_back, data) def testFetchFeedBlobBool(self): """Special case for bool to ensure coverage of both true and false.""" data = np.zeros((2, 3, 4)).astype(np.bool) data.flat[::2] = True self.assertEqual(workspace.FeedBlob("testblob_types", data), True) fetched_back = workspace.FetchBlob("testblob_types") self.assertEqual(fetched_back.shape, (2, 3, 4)) self.assertEqual(fetched_back.dtype, np.bool) np.testing.assert_array_equal(fetched_back, data) def testFetchFeedBlobZeroDim(self): data = np.empty(shape=(2, 0, 3), dtype=np.float32) self.assertEqual(workspace.FeedBlob("testblob_empty", data), True) fetched_back = workspace.FetchBlob("testblob_empty") self.assertEqual(fetched_back.shape, (2, 0, 3)) self.assertEqual(fetched_back.dtype, np.float32) def testFetchFeedLongStringTensor(self): # long strings trigger array of object creation strs = np.array([ ' '.join(10 * ['long string']), ' '.join(128 * ['very long string']), 'small \0\1\2 string', "Hello, world! I have special \0 symbols \1!"]) workspace.FeedBlob('my_str_tensor', strs) strs2 = workspace.FetchBlob('my_str_tensor') self.assertEqual(strs.shape, strs2.shape) for i in range(0, strs.shape[0]): self.assertEqual(strs[i], strs2[i]) def testFetchFeedShortStringTensor(self): # small strings trigger NPY_STRING array strs = np.array(['elem1', 'elem 2', 'element 3']) workspace.FeedBlob('my_str_tensor_2', strs) strs2 = workspace.FetchBlob('my_str_tensor_2') self.assertEqual(strs.shape, strs2.shape) for i in range(0, strs.shape[0]): self.assertEqual(strs[i], strs2[i]) def testFetchFeedPlainString(self): # this is actual string, not a tensor of strings s = "Hello, world! I have special \0 symbols \1!" workspace.FeedBlob('my_plain_string', s) s2 = workspace.FetchBlob('my_plain_string') self.assertEqual(s, s2) def testFetchBlobs(self): s1 = "test1" s2 = "test2" workspace.FeedBlob('s1', s1) workspace.FeedBlob('s2', s2) fetch1, fetch2 = workspace.FetchBlobs(['s1', 's2']) self.assertEquals(s1, fetch1) self.assertEquals(s2, fetch2) def testFetchFeedViaBlobDict(self): self.assertEqual( workspace.RunNetOnce(self.net.Proto().SerializeToString()), True) fetched = workspace.blobs["testblob"] # check if fetched is correct. self.assertEqual(fetched.shape, (1, 2, 3, 4)) np.testing.assert_array_equal(fetched, 1.0) fetched[:] = 2.0 workspace.blobs["testblob"] = fetched fetched_again = workspace.blobs["testblob"] self.assertEqual(fetched_again.shape, (1, 2, 3, 4)) np.testing.assert_array_equal(fetched_again, 2.0) self.assertTrue("testblob" in workspace.blobs) self.assertFalse("non_existant" in workspace.blobs) self.assertEqual(len(workspace.blobs), 1) for key in workspace.blobs: self.assertEqual(key, "testblob") class TestMultiWorkspaces(unittest.TestCase): def setUp(self): workspace.SwitchWorkspace("default") workspace.ResetWorkspace() def testCreateWorkspace(self): self.net = core.Net("test-net") self.net.ConstantFill([], "testblob", shape=[1, 2, 3, 4], value=1.0) self.assertEqual( workspace.RunNetOnce(self.net.Proto().SerializeToString()), True ) self.assertEqual(workspace.HasBlob("testblob"), True) self.assertEqual(workspace.SwitchWorkspace("test", True), None) self.assertEqual(workspace.HasBlob("testblob"), False) self.assertEqual(workspace.SwitchWorkspace("default"), None) self.assertEqual(workspace.HasBlob("testblob"), True) try: # The following should raise an error. workspace.SwitchWorkspace("non-existing") # so this should never happen. self.assertEqual(True, False) except RuntimeError: pass workspaces = workspace.Workspaces() self.assertTrue("default" in workspaces) self.assertTrue("test" in workspaces) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support.") class TestWorkspaceGPU(test_util.TestCase): def setUp(self): workspace.ResetWorkspace() self.net = core.Net("test-net") self.net.ConstantFill([], "testblob", shape=[1, 2, 3, 4], value=1.0) self.net.RunAllOnGPU() def testFetchBlobGPU(self): self.assertEqual( workspace.RunNetOnce(self.net.Proto().SerializeToString()), True) fetched = workspace.FetchBlob("testblob") # check if fetched is correct. self.assertEqual(fetched.shape, (1, 2, 3, 4)) np.testing.assert_array_equal(fetched, 1.0) fetched[:] = 2.0 self.assertEqual(workspace.FeedBlob("testblob", fetched), True) fetched_again = workspace.FetchBlob("testblob") self.assertEqual(fetched_again.shape, (1, 2, 3, 4)) np.testing.assert_array_equal(fetched_again, 2.0) def testDefaultGPUID(self): self.assertEqual(workspace.SetDefaultGPUID(0), None) self.assertEqual(workspace.GetDefaultGPUID(), 0) def testGetCudaPeerAccessPattern(self): pattern = workspace.GetCudaPeerAccessPattern() self.assertEqual(type(pattern), np.ndarray) self.assertEqual(pattern.ndim, 2) self.assertEqual(pattern.shape[0], pattern.shape[1]) self.assertEqual(pattern.shape[0], workspace.NumCudaDevices()) @unittest.skipIf(not workspace.C.has_mkldnn, "No MKLDNN support.") class TestWorkspaceMKLDNN(test_util.TestCase): def testFeedFetchBlobMKLDNN(self): arr = np.random.randn(2, 3).astype(np.float32) workspace.FeedBlob( "testblob_mkldnn", arr, core.DeviceOption(caffe2_pb2.MKLDNN)) fetched = workspace.FetchBlob("testblob_mkldnn") np.testing.assert_array_equal(arr, fetched) class TestImmedibate(test_util.TestCase): def testImmediateEnterExit(self): workspace.StartImmediate(i_know=True) self.assertTrue(workspace.IsImmediate()) workspace.StopImmediate() self.assertFalse(workspace.IsImmediate()) def testImmediateRunsCorrectly(self): workspace.StartImmediate(i_know=True) net = core.Net("test-net") net.ConstantFill([], "testblob", shape=[1, 2, 3, 4], value=1.0) self.assertEqual( workspace.ImmediateBlobs(), ["testblob"]) content = workspace.FetchImmediate("testblob") # Also, the immediate mode should not invade the original namespace, # so we check if this is so. with self.assertRaises(RuntimeError): workspace.FetchBlob("testblob") np.testing.assert_array_equal(content, 1.0) content[:] = 2.0 self.assertTrue(workspace.FeedImmediate("testblob", content)) np.testing.assert_array_equal( workspace.FetchImmediate("testblob"), 2.0) workspace.StopImmediate() with self.assertRaises(RuntimeError): content = workspace.FetchImmediate("testblob") def testImmediateRootFolder(self): workspace.StartImmediate(i_know=True) # for testing we will look into the _immediate_root_folder variable # but in normal usage you should not access that. self.assertTrue(len(workspace._immediate_root_folder) > 0) root_folder = workspace._immediate_root_folder self.assertTrue(os.path.isdir(root_folder)) workspace.StopImmediate() self.assertTrue(len(workspace._immediate_root_folder) == 0) # After termination, immediate mode should have the root folder # deleted. self.assertFalse(os.path.exists(root_folder)) class TestCppEnforceAsException(test_util.TestCase): def testEnforce(self): op = core.CreateOperator("Relu", ["X"], ["Y"]) with self.assertRaises(RuntimeError): workspace.RunOperatorOnce(op) class TestCWorkspace(htu.HypothesisTestCase): def test_net_execution(self): ws = workspace.C.Workspace() self.assertEqual(ws.nets, {}) self.assertEqual(ws.blobs, {}) net = core.Net("test-net") net.ConstantFill([], "testblob", shape=[1, 2, 3, 4], value=1.0) ws.create_net(net) self.assertIn("testblob", ws.blobs) self.assertIn("test-net", ws.nets) net = ws.nets["test-net"].run() blob = ws.blobs["testblob"] np.testing.assert_array_equal( np.ones((1, 2, 3, 4), dtype=np.float32), blob.fetch()) @given(name=st.text(), value=st.floats(min_value=-1, max_value=1.0)) def test_operator_run(self, name, value): name = name.encode("ascii", "ignore") ws = workspace.C.Workspace() op = core.CreateOperator( "ConstantFill", [], [name], shape=[1], value=value) ws.run(op) self.assertIn(name, ws.blobs) np.testing.assert_allclose( [value], ws.blobs[name].fetch(), atol=1e-4, rtol=1e-4) @given(blob_name=st.text(), net_name=st.text(), value=st.floats(min_value=-1, max_value=1.0)) def test_net_run(self, blob_name, net_name, value): blob_name = blob_name.encode("ascii", "ignore") net_name = net_name.encode("ascii", "ignore") ws = workspace.C.Workspace() net = core.Net(net_name) net.ConstantFill([], [blob_name], shape=[1], value=value) ws.run(net) self.assertIn(blob_name, ws.blobs) self.assertNotIn(net_name, ws.nets) np.testing.assert_allclose( [value], ws.blobs[blob_name].fetch(), atol=1e-4, rtol=1e-4) @given(blob_name=st.text(), net_name=st.text(), plan_name=st.text(), value=st.floats(min_value=-1, max_value=1.0)) def test_plan_run(self, blob_name, plan_name, net_name, value): blob_name = blob_name.encode("ascii", "ignore") net_name = net_name.encode("ascii", "ignore") plan_name = plan_name.encode("ascii", "ignore") ws = workspace.C.Workspace() plan = core.Plan(plan_name) net = core.Net(net_name) net.ConstantFill([], [blob_name], shape=[1], value=value) plan.AddStep(core.ExecutionStep("step", nets=[net], num_iter=1)) ws.run(plan) self.assertIn(blob_name, ws.blobs) self.assertIn(str(net), ws.nets) np.testing.assert_allclose( [value], ws.blobs[blob_name].fetch(), atol=1e-4, rtol=1e-4) @given(blob_name=st.text(), net_name=st.text(), value=st.floats(min_value=-1, max_value=1.0)) def test_net_create(self, blob_name, net_name, value): blob_name = blob_name.encode("ascii", "ignore") net_name = net_name.encode("ascii", "ignore") ws = workspace.C.Workspace() net = core.Net(net_name) net_name = str(net) net.ConstantFill([], [blob_name], shape=[1], value=value) ws.create_net(net).run() self.assertIn(blob_name, ws.blobs) self.assertIn(net_name, ws.nets) np.testing.assert_allclose( [value], ws.blobs[blob_name].fetch(), atol=1e-4, rtol=1e-4) @given(name=st.text(), value=htu.tensor(), device_option=st.sampled_from(htu.device_options)) def test_array_serde(self, name, value, device_option): name = name.encode("ascii", "ignore") ws = workspace.C.Workspace() ws.create_blob(name).feed(value, device_option=device_option) self.assertIn(name, ws.blobs) blob = ws.blobs[name] np.testing.assert_equal(value, ws.blobs[name].fetch()) serde_blob = ws.create_blob("{}_serde".format(name)) serde_blob.deserialize(blob.serialize(name)) np.testing.assert_equal(value, serde_blob.fetch()) @given(name=st.text(), value=st.text()) def test_string_serde(self, name, value): name = name.encode("ascii", "ignore") value = value.encode("ascii", "ignore") ws = workspace.C.Workspace() ws.create_blob(name).feed(value) self.assertIn(name, ws.blobs) blob = ws.blobs[name] self.assertEqual(value, ws.blobs[name].fetch()) serde_blob = ws.create_blob("{}_serde".format(name)) serde_blob.deserialize(blob.serialize(name)) self.assertEqual(value, serde_blob.fetch()) def test_exception(self): ws = workspace.C.Workspace() with self.assertRaises(RuntimeError): ws.create_net("...") if __name__ == '__main__': unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/caffe_translator.py
552
#!/usr/bin/env python2 import argparse import copy import logging import numpy as np from caffe2.proto import caffe2_pb2, caffe2_legacy_pb2 from caffe.proto import caffe_pb2 from caffe2.python import core, utils, workspace from google.protobuf import text_format logging.basicConfig() log = logging.getLogger("caffe_translator") log.setLevel(logging.INFO) def _StateMeetsRule(state, rule): """A function that reproduces Caffe's StateMeetsRule functionality.""" if rule.HasField('phase') and rule.phase != state.phase: return False if rule.HasField('min_level') and state.level < rule.min_level: return False if rule.HasField('max_level') and state.level > rule.max_lavel: return False curr_stages = set(list(state.stage)) # all stages in rule.stages should be in, otherwise it's not a match. if len(rule.stage) and any([s not in curr_stages for s in rule.stage]): return False # none of the stage in rule.stages should be in, otherwise it's not a match. if len(rule.not_stage) and any([s in curr_stages for s in rule.not_stage]): return False # If none of the nonmatch happens, return True. return True def _ShouldInclude(net_state, layer): """A function that reproduces Caffe's inclusion and exclusion rule.""" ret = (len(layer.include) == 0) # check exclude rules: if any exclusion is met, we shouldn't include. ret &= not any([_StateMeetsRule(net_state, rule) for rule in layer.exclude]) if len(layer.include): # check include rules: if any inclusion is met, we should include. ret |= any([_StateMeetsRule(net_state, rule) for rule in layer.include]) return ret class TranslatorRegistry(object): registry_ = {} @classmethod def Register(cls, op_name): """A decorator for registering gradient mappings.""" def Wrapper(func): cls.registry_[op_name] = func return func return Wrapper @classmethod def TranslateLayer(cls, layer, pretrained_blobs, is_test): try: caffe_ops, params = cls.registry_[layer.type]( layer, pretrained_blobs, is_test) except KeyError: raise KeyError('No translator registered for layer: %s yet.' % str(layer)) if caffe_ops is None: caffe_ops = [] if type(caffe_ops) is not list: caffe_ops = [caffe_ops] return caffe_ops, params @classmethod def TranslateModel( cls, caffe_net, pretrained_net, is_test=False, net_state=None, ): net_state = caffe_pb2.NetState() if net_state is None else net_state net = caffe2_pb2.NetDef() net.name = caffe_net.name net_params = caffe2_pb2.TensorProtos() if len(caffe_net.layer) == 0: raise ValueError( 'I think something is wrong. This translation script ' 'only accepts new style layers that are stored in the ' 'layer field.' ) for layer in caffe_net.layer: if not _ShouldInclude(net_state, layer): log.info('Current net state does not need layer {}' .format(layer.name)) continue log.info('Translate layer {}'.format(layer.name)) # Get pretrained one pretrained_layers = ( [l for l in pretrained_net.layer if l.name == layer.name] + [l for l in pretrained_net.layers if l.name == layer.name] ) if len(pretrained_layers) > 1: raise ValueError( 'huh? more than one pretrained layer of one name?') elif len(pretrained_layers) == 1: pretrained_blobs = [ utils.CaffeBlobToNumpyArray(blob) for blob in pretrained_layers[0].blobs ] else: # No pretrained layer for the given layer name. We'll just pass # no parameter blobs. # print 'No pretrained layer for layer', layer.name pretrained_blobs = [] operators, params = cls.TranslateLayer( layer, pretrained_blobs, is_test) net.op.extend(operators) net_params.protos.extend(params) return net, net_params def TranslateModel(*args, **kwargs): return TranslatorRegistry.TranslateModel(*args, **kwargs) def ConvertTensorProtosToInitNet(net_params): """Takes the net_params returned from TranslateModel, and wrap it as an init net that contain GivenTensorFill. This is a very simple feature that only works with float tensors, and is only intended to be used in an environment where you want a single initialization file - for more complex cases, use a db to store the parameters. """ init_net = caffe2_pb2.NetDef() for tensor in net_params.protos: if len(tensor.float_data) == 0: raise RuntimeError( "Only float tensors are supported in this util.") op = core.CreateOperator( "GivenTensorFill", [], [tensor.name], arg=[ utils.MakeArgument("shape", list(tensor.dims)), utils.MakeArgument("values", tensor.float_data)]) init_net.op.extend([op]) return init_net def BaseTranslate(layer, caffe2_type): """A simple translate interface that maps the layer input and output.""" caffe2_op = caffe2_pb2.OperatorDef() caffe2_op.type = caffe2_type caffe2_op.input.extend(layer.bottom) caffe2_op.output.extend(layer.top) return caffe2_op def AddArgument(op, key, value): """Makes an argument based on the value type.""" op.arg.extend([utils.MakeArgument(key, value)]) ################################################################################ # Common translators for layers. ################################################################################ @TranslatorRegistry.Register("Input") def TranslateInput(layer, pretrained_blobs, is_test): return [], [] @TranslatorRegistry.Register("Data") def TranslateData(layer, pretrained_blobs, is_test): return [], [] # A function used in convolution, pooling and deconvolution to deal with # conv pool specific parameters. def _TranslateStridePadKernelHelper(param, caffe_op): try: if (len(param.stride) > 1 or len(param.kernel_size) > 1 or len(param.pad) > 1): raise NotImplementedError( "Translator currently does not support non-conventional " "pad/kernel/stride settings." ) stride = param.stride[0] if len(param.stride) else 1 pad = param.pad[0] if len(param.pad) else 0 kernel = param.kernel_size[0] if len(param.kernel_size) else 0 except TypeError: # This catches the case of a PoolingParameter, in which case we are # having non-repeating pad, stride and kernel. stride = param.stride pad = param.pad kernel = param.kernel_size # Get stride if param.HasField("stride_h") or param.HasField("stride_w"): AddArgument(caffe_op, "stride_h", param.stride_h) AddArgument(caffe_op, "stride_w", param.stride_w) else: AddArgument(caffe_op, "stride", stride) # Get pad if param.HasField("pad_h") or param.HasField("pad_w"): if param.pad_h == param.pad_w: AddArgument(caffe_op, "pad", param.pad_h) else: AddArgument(caffe_op, "pad_t", param.pad_h) AddArgument(caffe_op, "pad_b", param.pad_h) AddArgument(caffe_op, "pad_l", param.pad_w) AddArgument(caffe_op, "pad_r", param.pad_w) else: AddArgument(caffe_op, "pad", pad) # Get kernel if param.HasField("kernel_h") or param.HasField("kernel_w"): AddArgument(caffe_op, "kernel_h", param.kernel_h) AddArgument(caffe_op, "kernel_w", param.kernel_w) else: AddArgument(caffe_op, "kernel", kernel) @TranslatorRegistry.Register("Convolution") def TranslateConv(layer, pretrained_blobs, is_test): param = layer.convolution_param caffe_op = BaseTranslate(layer, "Conv") output = caffe_op.output[0] caffe_op.input.append(output + '_w') _TranslateStridePadKernelHelper(param, caffe_op) # weight params = [ utils.NumpyArrayToCaffe2Tensor(pretrained_blobs[0], output + '_w')] # bias if len(pretrained_blobs) == 2: caffe_op.input.append(output + '_b') params.append( utils.NumpyArrayToCaffe2Tensor( pretrained_blobs[1].flatten(), output + '_b')) # Group convolution option if param.group != 1: AddArgument(caffe_op, "group", param.group) # Get dilation - not tested. If you have a model and this checks out, # please provide a test and uncomment this. if len(param.dilation) > 0: if len(param.dilation) == 1: AddArgument(caffe_op, "dilation", param.dilation[0]) elif len(param.dilation) == 2: AddArgument(caffe_op, "dilation_h", param.dilation[0]) AddArgument(caffe_op, "dilation_w", param.dilation[1]) return caffe_op, params @TranslatorRegistry.Register("Deconvolution") def TranslateDeconv(layer, pretrained_blobs, is_test): param = layer.convolution_param if param.group > 1: raise NotImplementedError( "Translator currently does not support group deconvolution." ) caffe_op = BaseTranslate(layer, "ConvTranspose") output = caffe_op.output[0] _TranslateStridePadKernelHelper(param, caffe_op) caffe_op.input.extend([output + '_w', output + '_b']) AddArgument(caffe_op, "order", "NCHW") weight = utils.NumpyArrayToCaffe2Tensor(pretrained_blobs[0], output + '_w') bias = utils.NumpyArrayToCaffe2Tensor( pretrained_blobs[1].flatten(), output + '_b' ) return caffe_op, [weight, bias] @TranslatorRegistry.Register("ReLU") def TranslateRelu(layer, pretrained_blobs, is_test): return BaseTranslate(layer, "Relu"), [] @TranslatorRegistry.Register("Pooling") def TranslatePool(layer, pretrained_blobs, is_test): param = layer.pooling_param if param.pool == caffe_pb2.PoolingParameter.MAX: caffe_op = BaseTranslate(layer, "MaxPool") elif param.pool == caffe_pb2.PoolingParameter.AVE: caffe_op = BaseTranslate(layer, "AveragePool") _TranslateStridePadKernelHelper(param, caffe_op) AddArgument(caffe_op, "order", "NCHW") if param.HasField('torch_pooling') and param.torch_pooling: # In the Facebook port of Caffe, a torch_pooling field was added to # map the pooling computation of Torch. Essentially, it uses # floor((height + 2 * padding - kernel) / stride) + 1 # instead of # ceil((height + 2 * padding - kernel) / stride) + 1 # which is Caffe's version. # Torch pooling is actually the same as Caffe2 pooling, so we don't # need to do anything. pass else: AddArgument(caffe_op, "legacy_pad", caffe2_legacy_pb2.CAFFE_LEGACY_POOLING) if param.global_pooling: AddArgument(caffe_op, "global_pooling", 1) return caffe_op, [] @TranslatorRegistry.Register("LRN") def TranslateLRN(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "LRN") caffe_op.output.extend(['_' + caffe_op.output[0] + '_scale']) param = layer.lrn_param if param.norm_region != caffe_pb2.LRNParameter.ACROSS_CHANNELS: raise ValueError( "Does not support norm region other than across channels.") AddArgument(caffe_op, "size", int(param.local_size)) AddArgument(caffe_op, "alpha", float(param.alpha)) AddArgument(caffe_op, "beta", float(param.beta)) AddArgument(caffe_op, "bias", float(param.k)) AddArgument(caffe_op, "order", "NCHW") return caffe_op, [] @TranslatorRegistry.Register("InnerProduct") def TranslateInnerProduct(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "FC") output = caffe_op.output[0] caffe_op.input.extend([output + '_w', output + '_b']) weight = utils.NumpyArrayToCaffe2Tensor( pretrained_blobs[0], output + '_w' ) bias = utils.NumpyArrayToCaffe2Tensor( pretrained_blobs[1].flatten(), output + '_b' ) return caffe_op, [weight, bias] @TranslatorRegistry.Register("Dropout") def TranslateDropout(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "Dropout") caffe_op.output.extend(['_' + caffe_op.output[0] + '_mask']) param = layer.dropout_param AddArgument(caffe_op, "ratio", param.dropout_ratio) if (is_test): AddArgument(caffe_op, "is_test", 1) return caffe_op, [] @TranslatorRegistry.Register("Softmax") def TranslateSoftmax(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "Softmax") return caffe_op, [] @TranslatorRegistry.Register("SoftmaxWithLoss") def TranslateSoftmaxWithLoss(layer, pretrained_blobs, is_test): softmax_op = core.CreateOperator( "Softmax", [layer.bottom[0]], layer.bottom[0] + "_translator_autogen_softmax") xent_op = core.CreateOperator( "LabelCrossEntropy", [softmax_op.output[0], layer.bottom[1]], layer.bottom[0] + "_translator_autogen_xent") loss_op = core.CreateOperator( "AveragedLoss", xent_op.output[0], layer.top[0]) return [softmax_op, xent_op, loss_op], [] @TranslatorRegistry.Register("Accuracy") def TranslateAccuracy(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "Accuracy") if layer.accuracy_param.top_k != 1: AddArgument(caffe_op, "top_k", layer.accuracy_param.top_k) return caffe_op, [] @TranslatorRegistry.Register("Concat") def TranslateConcat(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "Concat") caffe_op.output.extend(['_' + caffe_op.output[0] + '_dims']) AddArgument(caffe_op, "order", "NCHW") return caffe_op, [] @TranslatorRegistry.Register("TanH") def TranslateTanH(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "Tanh") return caffe_op, [] @TranslatorRegistry.Register("InstanceNorm") def TranslateInstanceNorm(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "InstanceNorm") output = caffe_op.output[0] weight = utils.NumpyArrayToCaffe2Tensor( pretrained_blobs[0].flatten(), output + '_w') bias = utils.NumpyArrayToCaffe2Tensor( pretrained_blobs[1].flatten(), output + '_b') caffe_op.input.extend([output + '_w', output + '_b']) AddArgument(caffe_op, "order", "NCHW") return caffe_op, [weight, bias] @TranslatorRegistry.Register("Eltwise") def TranslateElementWise(layer, pretrained_blobs, is_test): param = layer.eltwise_param # TODO(jiayq): if we have a protobuf that uses this, lift this constraint # and verify that we can correctly translate. if len(param.coeff) or param.operation != 1: raise RuntimeError("This eltwise layer is not yet supported.") caffe_op = BaseTranslate(layer, "Sum") return caffe_op, [] @TranslatorRegistry.Register("Scale") def TranslateScale(layer, pretrained_blobs, is_test): mul_op = BaseTranslate(layer, "Mul") scale_param = layer.scale_param AddArgument(mul_op, "axis", scale_param.axis) AddArgument(mul_op, "broadcast", True) if len(mul_op.input) == 1: # the scale parameter is in pretrained blobs if scale_param.num_axes != 1: raise RuntimeError("This path has not been verified yet.") output = mul_op.output[0] mul_op_param = output + '_w' mul_op.input.append(mul_op_param) weights = [] weights.append(utils.NumpyArrayToCaffe2Tensor( pretrained_blobs[0].flatten(), mul_op_param)) add_op = None if len(pretrained_blobs) == 1: # No bias-term in Scale layer pass elif len(pretrained_blobs) == 2: # Caffe Scale layer supports a bias term such that it computes # (scale_param * X + bias), whereas Caffe2 Mul op doesn't. # Include a separate Add op for the bias followed by Mul. add_op = copy.deepcopy(mul_op) add_op.type = "Add" add_op_param = output + '_b' internal_blob = output + "_internal" del mul_op.output[:] mul_op.output.append(internal_blob) del add_op.input[:] add_op.input.append(internal_blob) add_op.input.append(add_op_param) weights.append(utils.NumpyArrayToCaffe2Tensor( pretrained_blobs[1].flatten(), add_op_param)) else: raise RuntimeError("Unexpected number of pretrained blobs in Scale") caffe_ops = [mul_op] if add_op: caffe_ops.append(add_op) assert len(caffe_ops) == len(weights) return caffe_ops, weights elif len(mul_op.input) == 2: # TODO(jiayq): find a protobuf that uses this and verify. raise RuntimeError("This path has not been verified yet.") else: raise RuntimeError("Unexpected number of inputs.") @TranslatorRegistry.Register("Reshape") def TranslateReshape(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "Reshape") caffe_op.output.append("_" + caffe_op.input[0] + "_dims") reshape_param = layer.reshape_param AddArgument(caffe_op, 'shape', reshape_param.shape.dim) return caffe_op, [] @TranslatorRegistry.Register("Flatten") def TranslateFlatten(layer, pretrained_blobs, is_test): param = layer.flatten_param if param.end_axis != -1: raise NotImplementedError("flatten_param.end_axis not supported yet.") if param.axis == 0: caffe_op = BaseTranslate(layer, "FlattenToVec") elif param.axis == 1: caffe_op = BaseTranslate(layer, "Flatten") else: # This could be a Reshape op, but dim size is not known here. raise NotImplementedError( "Not supported yet for flatten_param.axis {}.".format(param.axis)) return caffe_op, [] @TranslatorRegistry.Register("Sigmoid") def TranslateSigmoid(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "Sigmoid") return caffe_op, [] @TranslatorRegistry.Register("ROIPooling") def TranslateROIPooling(layer, pretrained_blobs, is_test): caffe_op = BaseTranslate(layer, "RoIPool") AddArgument(caffe_op, "order", "NCHW") if is_test: AddArgument(caffe_op, "is_test", is_test) else: # Only used for gradient computation caffe_op.output.append(caffe_op.output[0] + '_argmaxes') param = layer.roi_pooling_param if param.HasField('pooled_h'): AddArgument(caffe_op, 'pooled_h', param.pooled_h) if param.HasField('pooled_w'): AddArgument(caffe_op, 'pooled_w', param.pooled_w) if param.HasField('spatial_scale'): AddArgument(caffe_op, 'spatial_scale', param.spatial_scale) return caffe_op, [] if __name__ == '__main__': parser = argparse.ArgumentParser( description="Utilitity to convert pretrained caffe models to Caffe2 models.") parser.add_argument("prototext", help="Caffe prototext.") parser.add_argument("caffemodel", help="Caffe trained model.") parser.add_argument("--init_net", help="Caffe2 initialization net.", default="init_net.pb") parser.add_argument("--predict_net", help="Caffe2 prediction net.", default="predict_net.pb") args = parser.parse_args() caffenet = caffe_pb2.NetParameter() caffenet_pretrained = caffe_pb2.NetParameter() input_proto = args.prototext input_caffemodel = args.caffemodel output_init_net = args.init_net output_predict_net = args.predict_net text_format.Merge( open(input_proto).read(), caffenet ) caffenet_pretrained.ParseFromString( open(input_caffemodel).read() ) net, pretrained_params = TranslateModel( caffenet, caffenet_pretrained, is_test=True ) for param in pretrained_params.protos: workspace.FeedBlob(param.name, utils.Caffe2TensorToNumpyArray(param)) with open(output_predict_net, 'wb') as f: f.write(str(net)) with open(output_init_net, 'wb') as f: f.write(pretrained_params.SerializeToString())
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/mint/app.py
185
import argparse import flask import glob import numpy as np import nvd3 import os import sys import tornado.httpserver import tornado.wsgi __folder__ = os.path.abspath(os.path.dirname(__file__)) app = flask.Flask( __name__, template_folder=os.path.join(__folder__, "templates"), static_folder=os.path.join(__folder__, "static") ) args = None def jsonify_nvd3(chart): chart.buildcontent() # Note(Yangqing): python-nvd3 does not seem to separate the built HTML part # and the script part. Luckily, it seems to be the case that the HTML part is # only a <div>, which can be accessed by chart.container; the script part, # while the script part occupies the rest of the html content, which we can # then find by chart.htmlcontent.find['<script>']. script_start = chart.htmlcontent.find('<script>') + 8 script_end = chart.htmlcontent.find('</script>') return flask.jsonify( result=chart.container, script=chart.htmlcontent[script_start:script_end].strip() ) def visualize_summary(filename): try: data = np.loadtxt(filename) except Exception as e: return 'Cannot load file {}: {}'.format(filename, str(e)) chart_name = os.path.splitext(os.path.basename(filename))[0] chart = nvd3.lineChart( name=chart_name + '_summary_chart', height=args.chart_height, y_axis_format='.03g' ) if args.sample < 0: step = max(data.shape[0] / -args.sample, 1) else: step = args.sample xdata = np.arange(0, data.shape[0], step) # data should have 4 dimensions. chart.add_serie(x=xdata, y=data[xdata, 0], name='min') chart.add_serie(x=xdata, y=data[xdata, 1], name='max') chart.add_serie(x=xdata, y=data[xdata, 2], name='mean') chart.add_serie(x=xdata, y=data[xdata, 2] + data[xdata, 3], name='m+std') chart.add_serie(x=xdata, y=data[xdata, 2] - data[xdata, 3], name='m-std') return jsonify_nvd3(chart) def visualize_print_log(filename): try: data = np.loadtxt(filename) if data.ndim == 1: data = data[:, np.newaxis] except Exception as e: return 'Cannot load file {}: {}'.format(filename, str(e)) chart_name = os.path.splitext(os.path.basename(filename))[0] chart = nvd3.lineChart( name=chart_name + '_log_chart', height=args.chart_height, y_axis_format='.03g' ) if args.sample < 0: step = max(data.shape[0] / -args.sample, 1) else: step = args.sample xdata = np.arange(0, data.shape[0], step) # if there is only one curve, we also show the running min and max if data.shape[1] == 1: # We also print the running min and max for the steps. trunc_size = data.shape[0] / step running_mat = data[:trunc_size * step].reshape((trunc_size, step)) chart.add_serie( x=xdata[:trunc_size], y=running_mat.min(axis=1), name='running_min' ) chart.add_serie( x=xdata[:trunc_size], y=running_mat.max(axis=1), name='running_max' ) chart.add_serie(x=xdata, y=data[xdata, 0], name=chart_name) else: for i in range(0, min(data.shape[1], args.max_curves)): # data should have 4 dimensions. chart.add_serie( x=xdata, y=data[xdata, i], name='{}[{}]'.format(chart_name, i) ) return jsonify_nvd3(chart) def visualize_file(filename): fullname = os.path.join(args.root, filename) if filename.endswith('summary'): return visualize_summary(fullname) elif filename.endswith('log'): return visualize_print_log(fullname) else: return flask.jsonify( result='Unsupport file: {}'.format(filename), script='' ) @app.route('/') def index(): files = glob.glob(os.path.join(args.root, "*.*")) files.sort() names = [os.path.basename(f) for f in files] return flask.render_template( 'index.html', root=args.root, names=names, debug_messages=names ) @app.route('/visualization/<string:name>') def visualization(name): ret = visualize_file(name) return ret def main(argv): parser = argparse.ArgumentParser("The mint visualizer.") parser.add_argument( '-p', '--port', type=int, default=5000, help="The flask port to use." ) parser.add_argument( '-r', '--root', type=str, default='.', help="The root folder to read files for visualization." ) parser.add_argument( '--max_curves', type=int, default=5, help="The max number of curves to show in a dump tensor." ) parser.add_argument( '--chart_height', type=int, default=300, help="The chart height for nvd3." ) parser.add_argument( '-s', '--sample', type=int, default=-200, help="Sample every given number of data points. A negative " "number means the total points we will sample on the " "whole curve. Default 100 points." ) global args args = parser.parse_args(argv) server = tornado.httpserver.HTTPServer(tornado.wsgi.WSGIContainer(app)) server.listen(args.port) print("Tornado server starting on port {}.".format(args.port)) tornado.ioloop.IOLoop.instance().start() if __name__ == '__main__': main(sys.argv[1:])
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/task.py
506
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, context from caffe2.python.schema import Field, from_blob_list from collections import defaultdict @context.define_context(allow_default=True) class Cluster(object): """ Context that keeps track of all the node names used. Users shouldn't have to use them directly, since a Cluster is automatically generated at the first usage of 'Node'. """ def __init__(self): # list instead of set to keep order self._nodes = [] def add_node(self, node): if str(node) not in self._nodes: self._nodes.append(str(node)) def nodes(self): """ Returns the list of unique node names used within this context. """ return self._nodes @context.define_context(allow_default=True) class Node(object): """ A Node context is used to indicate that all Tasks instantiated within will run on the given node name. (Only the name of the node actually counts.) Example: with TaskGroup() as tg: with Node('node1'): s1 = execution_step(...) Task(step=s1) with Node('node2'): s2 = execution_step(...) with Node('node1'): s3 = execution_step(...) In this example, all three execution steps will run in parallel. Moreover, s1 and s3 will run on the same node, and can see each others blobs. """ def __init__(self, node='local'): self._name = str(node) Cluster.current().add_node(self) def __str__(self): return self._name class WorkspaceType(object): """ Determines whether tasks of a TaskGroup will run directly at the global workspace, which is kept alive across runs, or whether a new child workspace will be created for the run and destroyed afterwards. """ PRIVATE = 'private' GLOBAL = 'global' def get_setup_nets(key, steps, target): init_net = core.Net(key + '/init') exit_net = core.Net(key + '/exit') init_nets = [] exit_nets = [] objs = [] for step in steps: if step is not None: objs += step.get_all_attributes(key) for obj in objs: # these are needed in order to allow nesting of TaskGroup, which # is a feature not yet implemented. if hasattr(obj, '_setup_used') and obj._setup_used: continue if hasattr(obj, '_setup_target') and obj._setup_target != target: continue if hasattr(obj, 'setup'): nets = obj.setup(init_net) if isinstance(nets, (list, tuple)): init_nets += nets elif isinstance(nets, (core.Net, core.ExecutionStep)): init_nets.append(nets) elif nets is not None: raise TypeError('Unsupported type for setup: %s' % type(nets)) obj._setup_used = True if hasattr(obj, 'exit'): nets = obj.exit(exit_net) if isinstance(nets, (list, tuple)): exit_nets += nets elif isinstance(nets, (core.Net, core.ExecutionStep)): exit_nets.append(nets) elif nets is not None: raise TypeError('Unsupported type for setup: %s' % type(nets)) obj._setup_used = True if len(init_net.Proto().op) > 0: init_nets.insert(0, init_net) if len(exit_net.Proto().op) > 0: exit_nets.insert(0, exit_net) return init_nets, exit_nets @context.define_context(allow_default=False) class TaskGroup(object): """ Context that gathers tasks which will run concurrently, potentially on multiple nodes. All tasks in the same node will share the same workspace and thus can share blobs, while tasks running in different nodes won't be able to directly share data. All tasks of the task group will start concurrently, and the task group will finish execution when the last task of the group finishes. Example: # supose that s1 ... s5 are execution steps or nets. with TaskGroup() as tg: # these tasks go to default node 'local' Task(step=s1) Task(step=s2) with Node('n2'): Task(step=s3) with Node('n1'): Task(step=s4) with Node('n2'): Task(step=s5) # this will run all steps in parallel. # s1 and s2 will run at default node 'local' # s3 and s5 will run at node 'n2' # s4 will run at node 'n1' session.run(tg) """ LOCAL_SETUP = 'local_setup' def __init__(self, workspace_type=None): self._plan_cache = None self._tasks = [] self._already_used = False self._prev_active = None self._tasks_to_add = [] self._report_nets = {} self._workspace_type = workspace_type self._tasks_by_node = None def add(self, task): assert not self._already_used, ( 'Cannot add Task to an already used TaskGroup.') assert ( self._workspace_type is None or task._workspace_type is None or self._workspace_type == task._workspace_type) if task._workspace_type is None: task._workspace_type = ( self._workspace_type or WorkspaceType.PRIVATE) if self._workspace_type is None: self._workspace_type = task._workspace_type task._notify_used() self._tasks.append(task) def tasks(self): for task in self._tasks_to_add: self.add(task) self._tasks_to_add = [] self._already_used = True return self._tasks def num_registered_tasks(self): return len(self._tasks_to_add) + len(self._tasks) def used_nodes(self): # use list to keep order used = [] for task in self.tasks(): if task.node not in used: used.append(task.node) return used def report_net(self, net=None, node=None, report_interval=5): """ Get or set the `report_net`, which is a net that runs repeatedly every `report_interval` seconds for the duration of the TaskGroup execution on each of the nodes. Each node has it's own report net. Example: with TaskGroup() as tg: for i in range(0, 2): with Node('trainer:%d' % i): report_net = tg.report_net() report_net.LogInfo('5s passed in trainer %d' % i) This will print '5s passed in trainer {}' every 5s on each one of the trainer nodes. """ node = str(Node.current(node)) assert net is None or node not in self._report_nets if node not in self._report_nets: self._report_nets[node] = ( net if net else core.Net('%s/reporter' % node), report_interval) return self._report_nets[node][0] def tasks_by_node(self, node_remap=None): # tasks_by_node can't be called twice because the setup won't # work properly a second time. node_map = {} for task in self.tasks(): node_map[task.node] =\ node_remap(task.node) if node_remap else task.node if self._tasks_by_node is not None: tasks_by_node, prev_node_map = self._tasks_by_node assert prev_node_map == node_map, ( 'Cannot call tasks_by_node multiple times.') return tasks_by_node tasks_by_node = defaultdict(list) for task in self.tasks(): tasks_by_node[node_map[task.node]].append(task) grouped_by_node = TaskGroup() for node, tasks in tasks_by_node.items(): node_inits, node_exits = get_setup_nets( TaskGroup.LOCAL_SETUP, [t.get_step() for t in tasks], self) # shortcut for single task with no queue steps = [] outputs = [] workspace_type = tasks[0].workspace_type() for task in tasks: step = task.get_step() if step is not None: steps.append(step) outputs += task.outputs() assert workspace_type == task.workspace_type(), ( 'All tasks for a given node need same workspace type.') if len(steps) == 0: steps.append(core.execution_step('empty', [])) if len(steps) == 1: step = steps[0] else: step = core.execution_step( '%s:body' % node, steps, concurrent_substeps=True) if node in self._report_nets: net, interval = self._report_nets[node] step.SetReportNet(net, interval) if len(node_inits) > 0 or len(node_exits) > 0: steps = [] if len(node_inits) > 0: steps.append( core.execution_step('%s:init' % node, node_inits)) steps.append(step) if len(node_exits) > 0: steps.append( core.execution_step('%s:exit' % node, node_exits)) step = core.execution_step(node, steps) Task( node=node, step=step, outputs=outputs, group=grouped_by_node, workspace_type=workspace_type) self._tasks_by_node = (grouped_by_node, node_map) return grouped_by_node def to_task(self, node='local'): tasks = self.tasks_by_node(lambda x: 'local').tasks() if len(tasks) == 0: return Task() return tasks[0] class TaskOutput(object): """ Represents the output of a task. An output can be a blob, a list of blob, or a record. """ def __init__(self, names): self._schema = None self._is_scalar = False if isinstance(names, Field): self._schema = names names = self._schema.field_blobs() self._is_scalar = type(names) not in (tuple, list) if self._is_scalar: names = [names] self.names = names self._values = None def set(self, values, _fetch_func=None): assert len(values) == len(self.names) self._values = values self._fetch_func = _fetch_func def get(self): assert self._values is not None, 'Output value not set yet.' if self._is_scalar: return self._values[0] elif self._schema: return from_blob_list(self._schema, self._values) else: return self._values def fetch(self): assert self._fetch_func is not None, ( 'Cannot fetch value for this output.') fetched_vals = [self._fetch_func(v) for v in self._values] if self._is_scalar: return fetched_vals[0] elif self._schema: return from_blob_list(self._schema, fetched_vals) else: return fetched_vals def final_output(blob_or_record): """ Adds an output to the current Task, or if no task is active, create a dummy task that returns the given blob or record to the client. This will return the value of the blob or record when the last task of the TaskGroup for a given node finishes. """ cur_task = Task.current(required=False) or Task() return cur_task.add_output(blob_or_record) @context.define_context() class Task(object): """ A Task is composed of an execution step and zero or more outputs. Tasks are executed in the context of a TaskGroup, which, in turn, can be run by a Session. Task outputs are fetched by the session at the end of the run. """ TASK_SETUP = 'task_setup' def __init__( self, step=None, outputs=None, workspace_type=None, group=None, node=None): """ Instantiate a Task and add it to the current TaskGroup and Node. """ # register this node name with active context self.node = str(Node.current(None if node is None else Node(node))) group = TaskGroup.current(group, required=False) if group is not None: group._tasks_to_add.append(self) self._already_used = False self._step = None self._step_with_setup = None self._outputs = [] if step is not None: self.set_step(step) if outputs is not None: self.add_outputs(outputs) self._pipeline = None self._is_pipeline_context = False self._workspace_type = workspace_type def __enter__(self): self._assert_not_used() assert self._step is None, 'This Task already has an execution step.' from caffe2.python import net_builder self._net_builder = net_builder.NetBuilder() self._net_builder.__enter__() return self def __exit__(self, type, value, traceback): if type is None: self.set_step(self._net_builder) self._net_builder.__exit__(type, value, traceback) self._net_builder = None def workspace_type(self): return self._workspace_type def _assert_not_used(self): assert not self._already_used, ( 'Cannot modify task since it is already been used.') def add_output(self, output): self._assert_not_used() output = ( output if isinstance(output, TaskOutput) else TaskOutput(output)) self._outputs.append(output) return output def add_outputs(self, outputs): self._assert_not_used() if type(outputs) not in (list, tuple): return self.add_output(outputs) else: return [self.add_output(output) for output in outputs] def set_step(self, step): self._assert_not_used() self._step = core.to_execution_step(step) def get_step(self): if self._step is not None and self._step_with_setup is None: init_nets, exit_nets = get_setup_nets( Task.TASK_SETUP, [self._step], self) if len(self._outputs) == 0: output_net = core.Net("output_net") self.add_output(output_net.ConstantFill( [], 1, dtype=core.DataType.INT32, value=0)) exit_nets.append(output_net) self._step_with_setup = core.execution_step( 'task', [ core.execution_step('task_init', init_nets), self._step, core.execution_step('task_exit', exit_nets), ] ) elif self._step_with_setup is None: self._step_with_setup = core.execution_step('task', []) return self._step_with_setup def outputs(self): return self._outputs def output_names(self): """ Retrive the output names. TODO(azzolini): make this schema-based. """ names = [] for o in self._outputs: names += o.names return names def set_outputs(self, values, _fetch_func): """ Set output values. TODO(azzolini): make this schema-based. """ offset = 0 for o in self._outputs: num = len(o.names) o.set(values[offset:offset + num], _fetch_func) offset += num assert offset == len(values), 'Wrong number of output values.' def resolved_outputs(self): return [output.get() for output in self._outputs] def _notify_used(self): self.get_step() self._already_used = True class SetupNets(object): """ Allow to register a list of nets to be run at initialization and finalization of Tasks or TaskGroups. For example, let's say you have the following: init_net = core.Net('init') my_val = init_net.ConstantFill([], 'my_val', value=0) net = core.Net('counter') net.Add([my_val, net.Const(1),], [my_val]) with TaskGroup() as task_group: with Node('trainer'): my_task = Task(step=[net]) In order to have `init_net` run once before `net` runs for the first time, you can do one of the following: net.add_object(Task.TASK_SETUP, SetupNets([init_net])) or net.add_object(TaskGroup.LOCAL_SETUP, SetupNets([init_net])) - With Task.TASK_SETUP, init_net will run once at my_task startup. - With TaskGroup.LOCAL_SETUP, init_net will run once on node 'trainer', before any task of the task group is run on that node. The same SetupNets object can be added to multiple nets. It will only run once per Task/TaskGroup run. """ def __init__(self, init_nets=None, exit_nets=None): self.init_nets = init_nets self.exit_nets = exit_nets def setup(self, init_net): return self.init_nets def exit(self, exit_net): return self.exit_nets
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/instance_norm_test.py
261
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import given import hypothesis.strategies as st from itertools import izip from caffe2.python import core, cnn import caffe2.python.hypothesis_test_util as hu class TestInstanceNorm(hu.HypothesisTestCase): def _get_inputs(self, N, C, H, W, order): if order == 'NCHW': input_data = np.random.rand(N, C, H, W).astype(np.float32) elif order == 'NHWC': # Allocate in the same order as NCHW and transpose to make sure # the inputs are identical on freshly-seeded calls. input_data = np.random.rand(N, C, H, W).astype(np.float32) input_data = np.transpose(input_data, axes=(0, 2, 3, 1)) else: raise Exception('unknown order type ({})'.format(order)) scale_data = np.random.rand(C).astype(np.float32) bias_data = np.random.rand(C).astype(np.float32) return input_data, scale_data, bias_data def _get_op(self, device_option, store_mean, store_inv_stdev, epsilon, order): outputs = ['output'] if store_mean or store_inv_stdev: outputs += ['mean'] if store_inv_stdev: outputs += ['inv_stdev'] op = core.CreateOperator( 'InstanceNorm', ['input', 'scale', 'bias'], outputs, order=order, epsilon=epsilon, device_option=device_option) return op def _feed_inputs(self, input_blobs, device_option): names = ['input', 'scale', 'bias'] for name, blob in izip(names, input_blobs): self.ws.create_blob(name).feed(blob, device_option=device_option) @given(gc=hu.gcs['gc'], dc=hu.gcs['dc'], N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), order=st.sampled_from(['NCHW', 'NHWC']), epsilon=st.floats(1e-6, 1e-4), store_mean=st.booleans(), seed=st.integers(0, 1000), store_inv_stdev=st.booleans()) def test_instance_norm_gradients( self, gc, dc, N, C, H, W, order, store_mean, store_inv_stdev, epsilon, seed): np.random.seed(seed) # force store_inv_stdev if store_mean to match existing forward pass # implementation store_inv_stdev |= store_mean op = self._get_op( device_option=gc, store_mean=store_mean, store_inv_stdev=store_inv_stdev, epsilon=epsilon, order=order) input_blobs = self._get_inputs(N, C, H, W, order) output_indices = [0] # if store_inv_stdev is turned on, store_mean must also be forced on if store_mean or store_inv_stdev: output_indices += [1] if store_inv_stdev: output_indices += [2] self.assertDeviceChecks(dc, op, input_blobs, output_indices) # The gradient only flows from output #0 since the other two only # store the temporary mean and inv_stdev buffers. # Check dl/dinput self.assertGradientChecks(gc, op, input_blobs, 0, [0]) # Check dl/dscale self.assertGradientChecks(gc, op, input_blobs, 1, [0]) # Check dl/dbias self.assertGradientChecks(gc, op, input_blobs, 2, [0]) @given(gc=hu.gcs['gc'], dc=hu.gcs['dc'], N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), seed=st.integers(0, 1000), epsilon=st.floats(1e-6, 1e-4), store_mean=st.booleans(), store_inv_stdev=st.booleans()) def test_instance_norm_layout(self, gc, dc, N, C, H, W, store_mean, store_inv_stdev, epsilon, seed): # force store_inv_stdev if store_mean to match existing forward pass # implementation store_inv_stdev |= store_mean outputs = {} for order in ('NCHW', 'NHWC'): np.random.seed(seed) input_blobs = self._get_inputs(N, C, H, W, order) self._feed_inputs(input_blobs, device_option=gc) op = self._get_op( device_option=gc, store_mean=store_mean, store_inv_stdev=store_inv_stdev, epsilon=epsilon, order=order) self.ws.run(op) outputs[order] = self.ws.blobs['output'].fetch() np.testing.assert_allclose( outputs['NCHW'], outputs['NHWC'].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) @given(gc=hu.gcs['gc'], dc=hu.gcs['dc'], N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), order=st.sampled_from(['NCHW', 'NHWC']), epsilon=st.floats(1e-6, 1e-4), store_mean=st.booleans(), seed=st.integers(0, 1000), store_inv_stdev=st.booleans()) def test_instance_norm_reference_check( self, gc, dc, N, C, H, W, order, store_mean, store_inv_stdev, epsilon, seed): np.random.seed(seed) # force store_inv_stdev if store_mean to match existing forward pass # implementation store_inv_stdev |= store_mean inputs = self._get_inputs(N, C, H, W, order) op = self._get_op( device_option=gc, store_mean=store_mean, store_inv_stdev=store_inv_stdev, epsilon=epsilon, order=order) def ref(input_blob, scale_blob, bias_blob): if order == 'NHWC': input_blob = np.transpose(input_blob, axes=(0, 3, 1, 2)) mean_blob = input_blob.reshape((N, C, -1)).mean(axis=2) inv_stdev_blob = 1.0 / \ np.sqrt(input_blob.reshape((N, C, -1)).var(axis=2) + epsilon) # _bc indicates blobs that are reshaped for broadcast scale_bc = scale_blob[np.newaxis, :, np.newaxis, np.newaxis] mean_bc = mean_blob[:, :, np.newaxis, np.newaxis] inv_stdev_bc = inv_stdev_blob[:, :, np.newaxis, np.newaxis] bias_bc = bias_blob[np.newaxis, :, np.newaxis, np.newaxis] normalized_blob = scale_bc * (input_blob - mean_bc) * inv_stdev_bc \ + bias_bc if order == 'NHWC': normalized_blob = np.transpose( normalized_blob, axes=(0, 2, 3, 1)) if not store_mean and not store_inv_stdev: return normalized_blob, elif not store_inv_stdev: return normalized_blob, mean_blob else: return normalized_blob, mean_blob, inv_stdev_blob self.assertReferenceChecks(gc, op, inputs, ref) @given(gc=hu.gcs['gc'], dc=hu.gcs['dc'], N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), order=st.sampled_from(['NCHW', 'NHWC']), epsilon=st.floats(1e-6, 1e-4), store_mean=st.booleans(), seed=st.integers(0, 1000), store_inv_stdev=st.booleans()) def test_instance_norm_device_check( self, gc, dc, N, C, H, W, order, store_mean, store_inv_stdev, epsilon, seed): np.random.seed(seed) # force store_inv_stdev if store_mean to match existing forward pass # implementation store_inv_stdev |= store_mean inputs = self._get_inputs(N, C, H, W, order) op = self._get_op( device_option=gc, store_mean=store_mean, store_inv_stdev=store_inv_stdev, epsilon=epsilon, order=order) self.assertDeviceChecks(dc, op, inputs, [0]) @given(is_test=st.booleans(), N=st.integers(2, 10), C=st.integers(3, 10), H=st.integers(5, 10), W=st.integers(7, 10), order=st.sampled_from(['NCHW', 'NHWC']), epsilon=st.floats(1e-6, 1e-4), seed=st.integers(0, 1000)) def test_instance_norm_cnn_helper(self, N, C, H, W, order, epsilon, seed, is_test): np.random.seed(seed) model = cnn.CNNModelHelper(order=order) model.InstanceNorm( 'input', 'output', C, epsilon=epsilon, is_test=is_test) input_blob = np.random.rand(N, C, H, W).astype(np.float32) if order == 'NHWC': input_blob = np.transpose(input_blob, axes=(0, 2, 3, 1)) self.ws.create_blob('input').feed(input_blob) self.ws.create_net(model.param_init_net).run() self.ws.create_net(model.net).run() if is_test: scale = self.ws.blobs['output_s'].fetch() assert scale is not None assert scale.shape == (C, ) bias = self.ws.blobs['output_b'].fetch() assert bias is not None assert bias.shape == (C, ) output_blob = self.ws.blobs['output'].fetch() if order == 'NHWC': output_blob = np.transpose(output_blob, axes=(0, 3, 1, 2)) assert output_blob.shape == (N, C, H, W) if __name__ == '__main__': import unittest unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/mpi_test.py
198
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from hypothesis import given import hypothesis.strategies as st import numpy as np import unittest from caffe2.python import core, workspace, dyndep import caffe2.python.hypothesis_test_util as hu dyndep.InitOpsLibrary("@/caffe2/caffe2/mpi:mpi_ops") _has_mpi =False COMM = None RANK = 0 SIZE = 0 def SetupMPI(): try: from mpi4py import MPI global _has_mpi, COMM, RANK, SIZE _has_mpi = core.IsOperatorWithEngine("CreateCommonWorld", "MPI") COMM = MPI.COMM_WORLD RANK = COMM.Get_rank() SIZE = COMM.Get_size() except ImportError: _has_mpi = False @unittest.skipIf(not _has_mpi, "MPI is not available. Skipping.") class TestMPI(hu.HypothesisTestCase): @given(X=hu.tensor(), root=st.integers(min_value=0, max_value=SIZE - 1), device_option=st.sampled_from(hu.device_options), **hu.gcs) def test_broadcast(self, X, root, device_option, gc, dc): # Use mpi4py's broadcast to make sure that all nodes inherit the # same hypothesis test. X = COMM.bcast(X) root = COMM.bcast(root) device_option = COMM.bcast(device_option) X[:] = RANK self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "CreateCommonWorld", [], "comm", engine="MPI", device_option=device_option))) self.assertTrue(workspace.FeedBlob("X", X, device_option)) mpi_op = core.CreateOperator( "Broadcast", ["comm", "X"], "X", engine="MPI", root=root, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) new_X = workspace.FetchBlob("X") np.testing.assert_array_equal(new_X, root) workspace.ResetWorkspace() @given(X=hu.tensor(), root=st.integers(min_value=0, max_value=SIZE - 1), device_option=st.sampled_from(hu.device_options), **hu.gcs) def test_reduce(self, X, root, device_option, gc, dc): # Use mpi4py's broadcast to make sure that all nodes inherit the # same hypothesis test. X = COMM.bcast(X) root = COMM.bcast(root) device_option = COMM.bcast(device_option) X[:] = RANK self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "CreateCommonWorld", [], "comm", engine="MPI", device_option=device_option))) self.assertTrue(workspace.FeedBlob("X", X, device_option)) mpi_op = core.CreateOperator( "Reduce", ["comm", "X"], "X_reduced", engine="MPI", root=root, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) if (RANK == root): new_X = workspace.FetchBlob("X") np.testing.assert_array_equal(new_X, root) workspace.ResetWorkspace() @given(X=hu.tensor(), root=st.integers(min_value=0, max_value=SIZE - 1), device_option=st.sampled_from(hu.device_options), inplace=st.booleans(), **hu.gcs) def test_allreduce(self, X, root, device_option, inplace, gc, dc): # Use mpi4py's broadcast to make sure that all nodes inherit the # same hypothesis test. X = COMM.bcast(X) root = COMM.bcast(root) device_option = COMM.bcast(device_option) inplace = COMM.bcast(inplace) X[:] = RANK self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "CreateCommonWorld", [], "comm", engine="MPI", device_option=device_option))) # Use mpi4py's broadcast to make sure that all copies have the same # tensor size. X = COMM.bcast(X) X[:] = RANK self.assertTrue(workspace.FeedBlob("X", X, device_option)) mpi_op = core.CreateOperator( "Allreduce", ["comm", "X"], "X" if inplace else "X_reduced", engine="MPI", root=root, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) new_X = workspace.FetchBlob("X" if inplace else "X_reduced") np.testing.assert_array_equal(new_X, SIZE * (SIZE - 1) / 2) workspace.ResetWorkspace() @given(X=hu.tensor(), device_option=st.sampled_from(hu.device_options), specify_send_blob=st.booleans(), specify_recv_blob=st.booleans(), **hu.gcs) def test_sendrecv( self, X, device_option, specify_send_blob, specify_recv_blob, gc, dc): # Use mpi4py's broadcast to make sure that all nodes inherit the # same hypothesis test. X = COMM.bcast(X) device_option = COMM.bcast(device_option) specify_send_blob = COMM.bcast(specify_send_blob) specify_recv_blob = COMM.bcast(specify_recv_blob) X[:] = RANK self.assertTrue( workspace.RunOperatorOnce( core.CreateOperator( "CreateCommonWorld", [], "comm", engine="MPI", device_option=device_option))) self.assertTrue(workspace.FeedBlob("X", X, device_option)) for src in range(SIZE): for dst in range(SIZE): tag = src * SIZE + dst if src == dst: continue elif RANK == src: X[:] = RANK self.assertTrue(workspace.FeedBlob("X", X, device_option)) if specify_send_blob: self.assertTrue(workspace.FeedBlob( "dst", np.array(dst, dtype=np.int32))) self.assertTrue(workspace.FeedBlob( "tag", np.array(tag, dtype=np.int32))) mpi_op = core.CreateOperator( "SendTensor", ["comm", "X", "dst", "tag"], [], engine="MPI", raw_buffer=True, device_option=device_option) else: mpi_op = core.CreateOperator( "SendTensor", ["comm", "X"], [], engine="MPI", dst=dst, tag=tag, raw_buffer=True, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) elif RANK == dst: if specify_recv_blob: self.assertTrue(workspace.FeedBlob( "src", np.array(src, dtype=np.int32))) self.assertTrue(workspace.FeedBlob( "tag", np.array(tag, dtype=np.int32))) mpi_op = core.CreateOperator( "ReceiveTensor", ["comm", "X", "src", "tag"], ["X", "src", "tag"], engine="MPI", src=src, tag=tag, raw_buffer=True, device_option=device_option) else: mpi_op = core.CreateOperator( "ReceiveTensor", ["comm", "X"], ["X", "src", "tag"], engine="MPI", src=src, tag=tag, raw_buffer=True, device_option=device_option) self.assertTrue(workspace.RunOperatorOnce(mpi_op)) received = workspace.FetchBlob("X") np.testing.assert_array_equal(received, src) src_blob = workspace.FetchBlob("src") np.testing.assert_array_equal(src_blob, src) tag_blob = workspace.FetchBlob("tag") np.testing.assert_array_equal(tag_blob, tag) # simply wait for the guys to finish COMM.barrier() workspace.ResetWorkspace() if __name__ == "__main__": SetupMPI() import unittest unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/utils.py
182
from caffe2.proto import caffe2_pb2 from google.protobuf.message import DecodeError, Message from google.protobuf import text_format import collections import functools import numpy as np import sys if sys.version_info > (3,): # This is python 3. We will define a few stuff that we used. basestring = str long = int def CaffeBlobToNumpyArray(blob): if (blob.num != 0): # old style caffe blob. return (np.asarray(blob.data, dtype=np.float32) .reshape(blob.num, blob.channels, blob.height, blob.width)) else: # new style caffe blob. return (np.asarray(blob.data, dtype=np.float32) .reshape(blob.shape.dim)) def Caffe2TensorToNumpyArray(tensor): return np.asarray(tensor.float_data, dtype=np.float32).reshape(tensor.dims) def NumpyArrayToCaffe2Tensor(arr, name): tensor = caffe2_pb2.TensorProto() tensor.data_type = caffe2_pb2.TensorProto.FLOAT tensor.name = name tensor.dims.extend(arr.shape) tensor.float_data.extend(list(arr.flatten().astype(float))) return tensor def MakeArgument(key, value): """Makes an argument based on the value type.""" argument = caffe2_pb2.Argument() argument.name = key iterable = isinstance(value, collections.Iterable) if isinstance(value, np.ndarray): value = value.flatten().tolist() elif isinstance(value, np.generic): # convert numpy scalar to native python type value = np.asscalar(value) if type(value) is float: argument.f = value elif type(value) is int or type(value) is bool or type(value) is long: # We make a relaxation that a boolean variable will also be stored as # int. argument.i = value elif isinstance(value, basestring): argument.s = (value if type(value) is bytes else value.encode('utf-8')) elif isinstance(value, Message): argument.s = value.SerializeToString() elif iterable and all(type(v) in [float, np.float_] for v in value): argument.floats.extend(value) elif iterable and all(type(v) in [int, bool, long, np.int_] for v in value): argument.ints.extend(value) elif iterable and all(isinstance(v, basestring) for v in value): argument.strings.extend([ (v if type(v) is bytes else v.encode('utf-8')) for v in value]) elif iterable and all(isinstance(v, Message) for v in value): argument.strings.extend([v.SerializeToString() for v in value]) else: raise ValueError( "Unknown argument type: key=%s value=%s, value type=%s" % (key, str(value), str(type(value))) ) return argument def TryReadProtoWithClass(cls, s): """Reads a protobuffer with the given proto class. Inputs: cls: a protobuffer class. s: a string of either binary or text protobuffer content. Outputs: proto: the protobuffer of cls Throws: google.protobuf.message.DecodeError: if we cannot decode the message. """ obj = cls() try: text_format.Parse(s, obj) return obj except text_format.ParseError: obj.ParseFromString(s) return obj def GetContentFromProto(obj, function_map): """Gets a specific field from a protocol buffer that matches the given class """ for cls, func in function_map.items(): if type(obj) is cls: return func(obj) def GetContentFromProtoString(s, function_map): for cls, func in function_map.items(): try: obj = TryReadProtoWithClass(cls, s) return func(obj) except DecodeError: continue else: raise DecodeError("Cannot find a fit protobuffer class.") def ConvertProtoToBinary(proto_class, filename, out_filename): """Convert a text file of the given protobuf class to binary.""" proto = TryReadProtoWithClass(proto_class, open(filename).read()) with open(out_filename, 'w') as fid: fid.write(proto.SerializeToString()) class DebugMode(object): ''' This class allows to drop you into an interactive debugger if there is an unhandled exception in your python script Example of usage: def main(): # your code here pass if __name__ == '__main__': from caffe2.python.utils import DebugMode DebugMode.run(main) ''' @classmethod def run(cls, func): try: return func() except KeyboardInterrupt: raise except Exception: import pdb print( 'Entering interactive debugger. Type "bt" to print ' 'the full stacktrace. Type "help" to see command listing.') print(sys.exc_info()[1]) print pdb.post_mortem() sys.exit(1) raise def debug(f): ''' Use this method to decorate your function with DebugMode's functionality Example: @debug def test_foo(self): raise Exception("Bar") ''' @functools.wraps(f) def wrapper(*args, **kwargs): def func(): return f(*args, **kwargs) DebugMode.run(func) return wrapper
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/data_parallel_model.py
563
from __future__ import absolute_import from __future__ import division from __future__ import print_function from collections import OrderedDict import logging from caffe2.python import model_helper, dyndep, scope, workspace, core, memonger from caffe2.proto import caffe2_pb2 dyndep.InitOpsLibrary("@/caffe2/caffe2/contrib/nccl:nccl_ops") log = logging.getLogger("data_parallel_model") log.setLevel(logging.INFO) def Parallelize_GPU( model_helper_obj, input_builder_fun, forward_pass_builder_fun, param_update_builder_fun, devices=range(0, workspace.NumCudaDevices()), rendezvous=None, net_type='dag', broadcast_computed_params=True, optimize_gradient_memory=False, ): ''' Function to create a model that can run on many GPUs. model_helper_obj: an object of ModelHelperBase, such as CNNModelHelper input_builder_fun: Function that adds the input operators Note: Remember to instantiate reader outside of this function so all GPUs share same reader object. Signature: input_builder_fun(model) forward_pass_builder_fun: Function to add the operators to the model. Must return list of loss-blob references that are used to build the gradient. Signature: forward_pass_builder_fun(model) param_update_builder_fun: Function that adds operators that are run after gradient update, such as updating the weights and weight decaying. Function is also passed the learning rate scaling factor. You should multiple the learning rate by the factor to maintain invariant of same results with same total batch size, regardless of number of gpus. Signature: param_update_builder_fun(model, lr_scale) devices: List of GPU ids, such as [0, 1, 2, 3], rendezvous: used for rendezvous in distributed computation, if None then only one node is used. To create rendezvous, use <TBD>. net_type: Network type ''' log.info("Parallelizing model for devices: {}".format(devices)) extra_workers = 8 if rendezvous is not None else 0 # best-guess model_helper_obj.net.Proto().num_workers = len(devices) * 4 + extra_workers model_helper_obj.net.Proto().type = net_type # Store some information in the model -- a bit ugly model_helper_obj._devices = devices model_helper_obj._rendezvous = rendezvous model_helper_obj._grad_names = [] assert isinstance(model_helper_obj, model_helper.ModelHelperBase) assert model_helper_obj.params == [], "Model needs to be empty" # Add input and model log.info("Create input and model training operators") losses_by_gpu = {} for device in devices: device_opt = core.DeviceOption(caffe2_pb2.CUDA, device) with core.DeviceScope(device_opt): with core.NameScope("gpu_{}".format(device)): log.info("Model for GPU: {}".format(device)) input_builder_fun(model_helper_obj) losses = forward_pass_builder_fun(model_helper_obj) # Losses are not needed for test net if param_update_builder_fun is not None: assert isinstance(losses, list), \ 'Model builder function must return list of loss blobs' for loss in losses: assert isinstance(loss, core.BlobReference), \ 'Model builder func must return list of loss blobs' losses_by_gpu[device] = losses # Create parameter map model_helper_obj._device_grouped_blobs =\ _GroupByDevice(devices, model_helper_obj.params) # computed params computed_params_grouped =\ _GroupByDevice(devices, model_helper_obj.computed_params) model_helper_obj._device_grouped_blobs.update(computed_params_grouped) model_helper_obj._param_names =\ model_helper_obj._device_grouped_blobs.keys() model_helper_obj._computed_param_names = computed_params_grouped.keys() if (param_update_builder_fun is None): log.info("Parameter update function not defined --> only forward") return log.info("Adding gradient operators") _AddGradientOperators(devices, model_helper_obj, losses_by_gpu) # Group gradients by device and register to blob lookup param_to_grad = model_helper_obj.param_to_grad grads_ordered = [param_to_grad[p] for p in model_helper_obj.params if p in param_to_grad] gradients_grouped = _GroupByDevice( devices, grads_ordered, ) model_helper_obj._device_grouped_blobs.update(gradients_grouped) model_helper_obj._grad_names = gradients_grouped.keys() log.info("Add gradient all-reduces for SyncSGD") if broadcast_computed_params: _BroadcastComputedParams(devices, model_helper_obj, rendezvous) _AllReduceGradients( devices, model_helper_obj, rendezvous ) log.info("Post-iteration operators for updating params") num_shards = 1 if rendezvous is None else rendezvous['num_shards'] lr_scale = 1.0 / (len(devices) * num_shards) for device in devices: device_opt = core.DeviceOption(caffe2_pb2.CUDA, device) with core.DeviceScope(device_opt): with core.NameScope("gpu_{}".format(device)): param_update_builder_fun(model_helper_obj, lr_scale) _AnalyzeOperators(model_helper_obj) # Configure dagnet to run with only one worker on the first iteration, # to prevent concurrency problems with allocs and nccl. arg = model_helper_obj.Proto().arg.add() arg.name = "first_iter_only_one_worker" arg.i = 1 # Add initial parameter syncs log.info("Add initial parameter sync") if (rendezvous is not None): _AddDistributedParameterSync( devices, model_helper_obj, model_helper_obj.param_init_net, model_helper_obj.param_init_net, rendezvous, ) _SyncParams(devices, model_helper_obj, model_helper_obj.param_init_net) if optimize_gradient_memory: _OptimizeGradientMemory(model_helper_obj, losses_by_gpu, devices) def _AddGradientOperators(devices, model, losses_by_gpu): def create_grad(lossp): return model.ConstantFill(lossp, str(lossp) + "_grad", value=1.0) loss_grad = {} # Explicitly need to create gradients on each GPU for gpu_id in devices: device = core.DeviceOption(caffe2_pb2.CUDA, gpu_id) with core.DeviceScope(device): for l in losses_by_gpu[gpu_id]: lg = create_grad(l) loss_grad[str(l)] = str(lg) model.AddGradientOperators(loss_grad) def FinalizeAfterCheckpoint(model, blobs, sync_iter=True): if not hasattr(model, "_checkpoint_net"): uniq_blob_names = [stripParamName(p) for p in blobs] # Synchronize to the blob lookup map, as the provided # blobs might have non-parameters, such as momemtum blobs. log.info("Creating checkpoint synchronization net") devices = model.GetDevices() for name in uniq_blob_names: if name not in model._device_grouped_blobs: grouped = { d: core.BlobReference("gpu_{}{}{}".format( d, scope._NAMESCOPE_SEPARATOR, name) ) for d in devices} model._device_grouped_blobs[name] = grouped model._checkpoint_net = core.Net("checkpoint_sync_net") model._checkpoint_net.RunAllOnGPU() if (model._rendezvous is not None): checkpoint_init_net = core.Net("checkpoint_init_net") checkpoint_init_net.RunAllOnGPU() _AddDistributedParameterSync( devices, model, checkpoint_init_net, model._checkpoint_net, model._rendezvous, uniq_blob_names, ) workspace.RunNetOnce(checkpoint_init_net) # Setup sync of initial params _SyncParams(devices, model, model._checkpoint_net, uniq_blob_names) # Sync ITER -- which is in CPU scope if sync_iter: with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)): for gpu_idx in devices[1:]: model._checkpoint_net.Copy( "gpu_{}/ITER".format(devices[0]), "gpu_{}/ITER".format(gpu_idx), ) workspace.CreateNet(model._checkpoint_net) # Run the sync log.info("Run checkpoint net") workspace.RunNet(model._checkpoint_net.Proto().name) def _Broadcast(devices, model, net, param): # TODO(akyrola): replace with NCCLBroadcast when it's working # Copy params from gpu_0 to other master_gpu = devices[0] for gpu_idx in devices[1:]: device_opt = core.DeviceOption(caffe2_pb2.CUDA, gpu_idx) with core.DeviceScope(device_opt): net.Copy( model._device_grouped_blobs[param][master_gpu], model._device_grouped_blobs[param][gpu_idx] ) def _SyncParams(devices, model, net, unique_param_names=None): if unique_param_names is None: unique_param_names = model._param_names for param in unique_param_names: _Broadcast(devices, model, net, param) def _AddDistributedParameterSync( devices, model, init_net, net, rendezvous, uniq_param_names=None, ): if uniq_param_names is None: uniq_param_names = model._param_names device_opt = core.DeviceOption(caffe2_pb2.CUDA, devices[0]) # ITER is in CPU scope :( with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)): comm_world = init_net.CreateCommonWorld( rendezvous['kv_handler'], "iter_cw", name=net.Proto().name + ".iter_cw_op", size=rendezvous['num_shards'], rank=rendezvous['shard_id'], engine=rendezvous['engine'], ) net.Broadcast( inputs=[comm_world, "gpu_{}/ITER".format(devices[0])], outputs=["gpu_{}/ITER".format(devices[0])], engine=rendezvous['engine'], ) for param_name in sorted(uniq_param_names): param = model._device_grouped_blobs[param_name][devices[0]] with core.DeviceScope(device_opt): param_cpu = net.CopyGPUToCPU(param, str(param) + "cpu") with core.DeviceScope(core.DeviceOption(caffe2_pb2.CPU)): comm_world = init_net.CreateCommonWorld( rendezvous['kv_handler'], "{}_cw".format(param_name), name=net.Proto().name + ".{}_cw_op".format(param_name), size=rendezvous['num_shards'], rank=rendezvous['shard_id'], engine=rendezvous['engine'], ) # Temp: copy to CPU net.Broadcast( inputs=[comm_world, param_cpu], outputs=[param_cpu], engine=rendezvous['engine'], ) with core.DeviceScope(device_opt): net.CopyCPUToGPU(param_cpu, param) def _AllReduceGradients(devices, model, rendezvous): if rendezvous is None: _AllReduceGradientsSingleHost(devices, model) else: _AllReduceGradientsDistributed(devices, model, rendezvous) def _AllReduceGradientsDistributed( devices, model, rendezvous, ): num_workers = model.net.Proto().num_workers assert num_workers > 1, "Please specify more than 1 worker" all_reduce_engine = rendezvous['engine'] # Make list of gradients in reverse order reverse_ordered_grads = _GetReverseOrderedGrads(model) # Step 1: sum gradients from local GPUs to master GPU master_device_opt = core.DeviceOption(caffe2_pb2.CUDA, devices[0]) reducing_device_opt = master_device_opt if all_reduce_engine == "RDMA_TCP": reducing_device_opt = core.DeviceOption(caffe2_pb2.CPU, 0) # We need to specify a partial order using control_input to # ensure progress (since all machines need to do same all reduces # in parallel) num_controls = min(4, num_workers - 1) cyclical_controls = [] counter = 0 nccl_control_blob = None # Note: sorted order to ensure each host puts the operators in # same order. for grad_name in reverse_ordered_grads: master_grad = model._device_grouped_blobs[grad_name][devices[0]] grads_group = model._device_grouped_blobs[grad_name].values() assert master_grad in grads_group # Remark: NCCLReduce does not support in-place modifications # so we need a temporary gradient blob reduced_grad = str(master_grad) + "_red" with core.DeviceScope(master_device_opt): model.ConstantFill(master_grad, reduced_grad, value=0.0) # Temp fix since NCCLReduce does not work model.net.NCCLAllreduce( grads_group, grads_group, control_input=nccl_control_blob, ) nccl_control_blob = grads_group[0] model.net.Copy(master_grad, reduced_grad) # RDMA_TCP works only on CPU context, so we need a temporary # cpu-bound scratch blob. if all_reduce_engine == "RDMA_TCP": with core.DeviceScope(reducing_device_opt): model.param_init_net.ConstantFill( [], reduced_grad + "cpu", shape=[1], value=0.0 ) with core.DeviceScope(master_device_opt): # Hack to ensure the cpu-scratch blob is initialized # prior to running the net. model.param_init_net.CopyGPUToCPU( str(master_grad).replace("_grad", ""), reduced_grad + "cpu" ) model.net.CopyGPUToCPU(reduced_grad, reduced_grad + "cpu") reduced_grad = reduced_grad + "cpu" control_input = None if len(cyclical_controls) < num_controls \ else cyclical_controls[counter % num_controls] with core.DeviceScope(reducing_device_opt): # Step 2: allreduce between all hosts, between master GPUs comm_world = model.param_init_net.CreateCommonWorld( rendezvous['kv_handler'], "{}_cw".format(grad_name), name="{}_cw_op".format(grad_name), size=rendezvous['num_shards'], rank=rendezvous['shard_id'], engine=rendezvous['engine'], ) model.net.Allreduce( inputs=[comm_world, reduced_grad], outputs=[reduced_grad], engine=all_reduce_engine, control_input=control_input, ) if reducing_device_opt != master_device_opt: with core.DeviceScope(master_device_opt): model.net.CopyCPUToGPU(reduced_grad, master_grad) else: with core.DeviceScope(master_device_opt): model.net.Copy(reduced_grad, master_grad) if len(cyclical_controls) < num_controls: cyclical_controls.append(reduced_grad) else: cyclical_controls[counter % num_controls] = reduced_grad counter += 1 # Step 3: broadcast locally _Broadcast(devices, model, model.net, grad_name) def _AllReduceGradientsSingleHost(devices, model): """Performs NCCL AllReduce to distribute gradients to all the GPUs.""" if len(devices) == 1: return # Gradients in reverse order reverse_ordered_grads = _GetReverseOrderedGrads(model) # Now we need to Allreduce gradients on all the GPUs. # Pick GPU #0 as a master GPU. master_device_opt = core.DeviceOption(caffe2_pb2.CUDA, devices[0]) last_out = None for grad_name in reverse_ordered_grads: with core.DeviceScope(master_device_opt): # Group by grads for reduce. grads_group = model._device_grouped_blobs[grad_name].values() assert len(grads_group) == len(devices), \ "Each GPU from {}, should have a copy of {}.".format( devices, grad_name) model.NCCLAllreduce( grads_group, grads_group, control_input=last_out, ) # last_out is used to serialize the execution of nccls last_out = grads_group[0] def _BroadcastComputedParams(devices, model, rendezvous): if rendezvous is None: _BroadcastComputedParamsSingleHost(devices, model) else: _BroadcastComputedParamsDistributed(devices, model, rendezvous) def _BroadcastComputedParamsDistributed( devices, model, rendezvous, ): _BroadcastComputedParamsSingleHost(devices, model) log.warn("Distributed computed params all-reduce not implemented yet") def _BroadcastComputedParamsSingleHost(devices, model): ''' Average computed params over all devices ''' if len(devices) == 1: return for param_name in model._computed_param_names: # Copy from master to others -- averaging would be perhaps better, # but currently NCCLAllReduce is too prone to deadlock _Broadcast(devices, model, model.net, param_name) def _GetReverseOrderedGrads(model): ''' Returns the gradients in reverse order (namespace stripped), for the optimal synchronization order. ''' return list(reversed(model._grad_names)) # A helper function to extract a parameter's name def stripParamName(param): # Format is "a/b/c/d" -> d name = str(param) sep = scope._NAMESCOPE_SEPARATOR return name[name.rindex(sep) + 1:] def _AnalyzeOperators(model): ''' Look at all the operators and check that they do not cross device scopes ''' for op in model.Proto().op: if "NCCL" in op.type or "Copy" in op.type: continue op_dev = op.device_option op_gpu = op_dev.cuda_gpu_id # This avoids failing on operators that are only for CPU if op_dev.device_type == caffe2_pb2.CPU: continue namescope = "gpu_{}/".format(op_gpu) for inp in list(op.input) + list(op.output): if inp.startswith("gpu_") and not inp.startswith(namescope): raise Exception( "Blob {} of op {}, should have namescope {}. Op: {}".format( inp, op.type, "gpu_{}/".format(op_gpu), str(op), )) def _GroupByDevice(devices, params): ''' Groups blobs by device, returning a map of [blobname] = {0: BlobRef, 1: ..}. Returns ordered dictionary, ensuring the original order. ''' grouped = OrderedDict() assert len(params) % len(devices) == 0,\ "There should be equal number of params per device" num_params_per_device = int(len(params) / len(devices)) for i, p in enumerate(params): assert isinstance(p, core.BlobReference), \ "Param {} is not of type BlobReference".format(p) name = stripParamName(p) gpuid = devices[i // num_params_per_device] assert "gpu_{}/".format(gpuid) in p.GetNameScope(),\ "Param {} expected to have namescope 'gpu_{}'".format(str(p), gpuid) if name not in grouped: grouped[name] = {} grouped[name][gpuid] = p # Confirm consistency for j, (p, ps) in enumerate(grouped.items()): assert \ len(ps) == len(devices), \ "Param {} does not have value for each device (only {}: {})".format( p, len(ps), ps, ) # Ensure ordering assert(ps[devices[0]] == params[j]) return grouped def _OptimizeGradientMemory(model, losses_by_gpu, devices): for device in devices: namescope = "gpu_{}/".format(device) model.net._net = memonger.share_grad_blobs( model.net, losses_by_gpu[device], set(model.param_to_grad.values()), namescope, )
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/hypothesis_test_util.py
489
""" The Hypothesis library uses *property-based testing* to check invariants about the code under test under a variety of random inputs. The key idea here is to express properties of the code under test (e.g. that it passes a gradient check, that it implements a reference function, etc), and then generate random instances and verify they satisfy these properties. The main functions of interest are exposed on `HypothesisTestCase`. You can usually just add a short function in this to generate an arbitrary number of test cases for your operator. The key functions are: - `assertDeviceChecks(devices, op, inputs, outputs)`. This asserts that the operator computes the same outputs, regardless of which device it is executed on. - `assertGradientChecks(device, op, inputs, output_, outputs_with_grads)`. This implements a standard numerical gradient checker for the operator in question. - `assertReferenceChecks(device, op, inputs, reference)`. This runs the reference function (effectively calling `reference(*inputs)`, and comparing that to the output of output. `hypothesis_test_util.py` exposes some useful pre-built samplers. - `hu.gcs` - a gradient checker device (`gc`) and device checker devices (`dc`) - `hu.gcs_cpu_only` - a CPU-only gradient checker device (`gc`) and device checker devices (`dc`). Used for when your operator is only implemented on the CPU. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.proto import caffe2_pb2 from caffe2.python import ( workspace, device_checker, gradient_checker, test_util, core) import contextlib import copy import hypothesis import hypothesis.extra.numpy import hypothesis.strategies as st import numpy as np import os def is_sandcastle(): if os.getenv('SANDCASTLE') == '1': return True elif os.getenv('TW_JOB_USER') == 'sandcastle': return True return False hypothesis.settings.register_profile( "sandcastle", hypothesis.settings( derandomize=True, suppress_health_check=[hypothesis.HealthCheck.too_slow], database=None, max_examples=100, verbosity=hypothesis.Verbosity.verbose)) hypothesis.settings.register_profile( "dev", hypothesis.settings( suppress_health_check=[hypothesis.HealthCheck.too_slow], database=None, max_examples=10, verbosity=hypothesis.Verbosity.verbose)) hypothesis.settings.register_profile( "debug", hypothesis.settings( suppress_health_check=[hypothesis.HealthCheck.too_slow], database=None, max_examples=1000, verbosity=hypothesis.Verbosity.verbose)) hypothesis.settings.load_profile( 'sandcastle' if is_sandcastle() else os.getenv('CAFFE2_HYPOTHESIS_PROFILE', 'dev') ) def dims(min_value=1, max_value=5): return st.integers(min_value=min_value, max_value=max_value) def elements_of_type(dtype=np.float32, filter_=None): elems = None if dtype in (np.float32, np.float64): elems = st.floats(min_value=-1.0, max_value=1.0) elif dtype is np.int32: elems = st.integers(min_value=0, max_value=2 ** 31 - 1) elif dtype is np.int64: elems = st.integers(min_value=0, max_value=2 ** 63 - 1) elif dtype is np.bool: elems = st.booleans() else: raise ValueError("Unexpected dtype without elements provided") return elems if filter_ is None else elems.filter(filter_) def arrays(dims, dtype=np.float32, elements=None): if elements is None: elements = elements_of_type(dtype) return hypothesis.extra.numpy.arrays(dtype, dims, elements=elements) def tensor(min_dim=1, max_dim=4, dtype=np.float32, elements=None, **kwargs): dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim) return dims_.flatmap(lambda dims: arrays(dims, dtype, elements)) def segment_ids(size, is_sorted): if size == 0: return st.just(np.empty(shape=[0], dtype=np.int32)) if is_sorted: return arrays( [size], dtype=np.int32, elements=st.booleans()).map( lambda x: np.cumsum(x, dtype=np.int32) - x[0]) else: return arrays( [size], dtype=np.int32, elements=st.integers(min_value=0, max_value=2 * size)) def lengths(size, **kwargs): # First generate number of boarders between segments # Then create boarder values and add 0 and size # By sorting and computing diff we convert them to lengths of # possible 0 value if size == 0: return st.just(np.empty(shape=[0], dtype=np.int32)) return st.integers( min_value=0, max_value=size - 1 ).flatmap(lambda num_boarders: hypothesis.extra.numpy.arrays( np.int32, num_boarders, elements=st.integers( min_value=0, max_value=size ) ) ).map(lambda x: np.append(x, np.array([0, size], dtype=np.int32)) ).map(sorted).map(np.diff) def segmented_tensor( min_dim=1, max_dim=4, dtype=np.float32, is_sorted=True, elements=None, segment_generator=segment_ids, allow_empty=False, **kwargs ): gen_empty = st.booleans() if allow_empty else st.just(False) data_dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim) data_dims_ = st.tuples( gen_empty, data_dims_ ).map(lambda pair: ([0] if pair[0] else []) + pair[1]) return data_dims_.flatmap(lambda data_dims: st.tuples( arrays(data_dims, dtype, elements), segment_generator(data_dims[0], is_sorted=is_sorted), )) def lengths_tensor(*args, **kwargs): return segmented_tensor(*args, segment_generator=lengths, **kwargs) def sparse_segmented_tensor(min_dim=1, max_dim=4, dtype=np.float32, is_sorted=True, elements=None, allow_empty=False, segment_generator=segment_ids, **kwargs): gen_empty = st.booleans() if allow_empty else st.just(False) data_dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim) all_dims_ = st.tuples(gen_empty, data_dims_).flatmap( lambda pair: st.tuples( st.just(pair[1]), (st.integers(min_value=1, max_value=pair[1][0]) if not pair[0] else st.just(0)), )) return all_dims_.flatmap(lambda dims: st.tuples( arrays(dims[0], dtype, elements), arrays(dims[1], dtype=np.int64, elements=st.integers( min_value=0, max_value=dims[0][0] - 1)), segment_generator(dims[1], is_sorted=is_sorted), )) def sparse_lengths_tensor(**kwargs): return sparse_segmented_tensor(segment_generator=lengths, **kwargs) def tensors(n, min_dim=1, max_dim=4, dtype=np.float32, elements=None, **kwargs): dims_ = st.lists(dims(**kwargs), min_size=min_dim, max_size=max_dim) return dims_.flatmap( lambda dims: st.lists(arrays(dims, dtype, elements), min_size=n, max_size=n)) cpu_do = caffe2_pb2.DeviceOption() gpu_do = caffe2_pb2.DeviceOption(device_type=caffe2_pb2.CUDA) device_options = [cpu_do] + ([gpu_do] if workspace.has_gpu_support else []) # Include device option for each GPU expanded_device_options = [cpu_do] + ( [caffe2_pb2.DeviceOption(device_type=caffe2_pb2.CUDA, cuda_gpu_id=i) for i in range(workspace.NumCudaDevices())] if workspace.has_gpu_support else []) def device_checker_device_options(): return st.just(device_options) def gradient_checker_device_option(): return st.sampled_from(device_options) gcs = dict( gc=gradient_checker_device_option(), dc=device_checker_device_options() ) gcs_cpu_only = dict(gc=st.sampled_from([cpu_do]), dc=st.just([cpu_do])) gcs_gpu_only = dict(gc=st.sampled_from([gpu_do]), dc=st.just([gpu_do])) @contextlib.contextmanager def temp_workspace(name=b"temp_ws"): old_ws_name = workspace.CurrentWorkspace() workspace.SwitchWorkspace(name, True) yield workspace.ResetWorkspace() workspace.SwitchWorkspace(old_ws_name) def runOpBenchmark( device_option, op, inputs, input_device_options={}, iterations=10, ): op = copy.deepcopy(op) op.device_option.CopyFrom(device_option) net = caffe2_pb2.NetDef() net.op.extend([op]) net.name = op.name if op.name else "test" with temp_workspace(): for (n, b) in zip(op.input, inputs): workspace.FeedBlob( n, b, device_option=input_device_options.get(n, device_option) ) workspace.CreateNet(net) ret = workspace.BenchmarkNet(net.name, 1, iterations, True) return ret class HypothesisTestCase(test_util.TestCase): """ A unittest.TestCase subclass with some helper functions for utilizing the `hypothesis` (hypothesis.readthedocs.io) library. """ def assertDeviceChecks( self, device_options, op, inputs, outputs_to_check, input_device_options=None, threshold=0.01 ): """ Asserts that the operator computes the same outputs, regardless of which device it is executed on. Useful for checking the consistency of GPU and CPU implementations of operators. Usage example: @given(inputs=hu.tensors(n=2), in_place=st.booleans(), **hu.gcs) def test_sum(self, inputs, in_place, gc, dc): op = core.CreateOperator("Sum", ["X1", "X2"], ["Y" if not in_place else "X1"]) X1, X2 = inputs self.assertDeviceChecks(dc, op, [X1, X2], [0]) """ dc = device_checker.DeviceChecker( threshold, device_options=device_options ) self.assertTrue( dc.CheckSimple(op, inputs, outputs_to_check, input_device_options) ) def assertGradientChecks( self, device_option, op, inputs, outputs_to_check, outputs_with_grads, grad_ops=None, threshold=0.005, stepsize=0.05, input_device_options=None, ): """ Implements a standard numerical gradient checker for the operator in question. Useful for checking the consistency of the forward and backward implementations of operators. Usage example: @given(inputs=hu.tensors(n=2), in_place=st.booleans(), **hu.gcs) def test_sum(self, inputs, in_place, gc, dc): op = core.CreateOperator("Sum", ["X1", "X2"], ["Y" if not in_place else "X1"]) X1, X2 = inputs self.assertGradientChecks(gc, op, [X1, X2], 0, [0]) """ gc = gradient_checker.GradientChecker( stepsize=stepsize, threshold=threshold, device_option=device_option, workspace_name=str(device_option), ) res, grad, grad_estimated = gc.CheckSimple( op, inputs, outputs_to_check, outputs_with_grads, grad_ops=grad_ops, input_device_options=input_device_options ) self.assertEqual(grad.shape, grad_estimated.shape) self.assertTrue(res, "Gradient checks failed") def _assertGradReferenceChecks( self, op, inputs, ref_outputs, output_to_grad, grad_reference, threshold=1e-4, ): grad_blob_name = output_to_grad + '_grad' grad_ops, grad_map = core.GradientRegistry.GetBackwardPass( [op], {output_to_grad: grad_blob_name}) output_grad = workspace.FetchBlob(output_to_grad) grad_ref_outputs = grad_reference(output_grad, ref_outputs, inputs) workspace.FeedBlob(grad_blob_name, workspace.FetchBlob(output_to_grad)) workspace.RunOperatorsOnce(grad_ops) self.assertEqual(len(grad_ref_outputs), len(inputs)) for (n, ref) in zip(op.input, grad_ref_outputs): grad_names = grad_map.get(n) if not grad_names: # no grad for this input self.assertIsNone(ref) else: if isinstance(grad_names, core.BlobReference): # dense gradient ref_vals = ref ref_indices = None val_name = grad_names else: # sparse gradient ref_vals, ref_indices = ref val_name = grad_names.values vals = workspace.FetchBlob(str(val_name)) np.testing.assert_allclose(vals, ref_vals, atol=threshold, rtol=threshold) if ref_indices is not None: indices = workspace.FetchBlob(str(grad_names.indices)) np.testing.assert_allclose(indices, ref_indices, atol=1e-4, rtol=1e-4) def assertReferenceChecks( self, device_option, op, inputs, reference, input_device_options={}, threshold=1e-4, output_to_grad=None, grad_reference=None, atol=None, outputs_to_check=None, ): """ This runs the reference Python function implementation (effectively calling `reference(*inputs)`, and compares that to the output of output, with an absolute/relative tolerance given by the `threshold` parameter. Useful for checking the implementation matches the Python (typically NumPy) implementation of the same functionality. Usage example: @given(X=hu.tensor(), inplace=st.booleans(), **hu.gcs) def test_softsign(self, X, inplace, gc, dc): op = core.CreateOperator( "Softsign", ["X"], ["X" if inplace else "Y"]) def softsign(X): return (X / (1 + np.abs(X)),) self.assertReferenceChecks(gc, op, [X], softsign) """ op = copy.deepcopy(op) op.device_option.CopyFrom(device_option) with temp_workspace(): for (n, b) in zip(op.input, inputs): workspace.FeedBlob( n, b, device_option=input_device_options.get(n, device_option) ) workspace.RunOperatorOnce(op) reference_outputs = reference(*inputs) if not (isinstance(reference_outputs, tuple) or isinstance(reference_outputs, list)): raise RuntimeError( "You are providing a wrong reference implementation. A " "proper one should return a tuple/list of numpy arrays.") if not outputs_to_check: self.assertEqual(len(reference_outputs), len(op.output)) outputs_to_check = range(len(op.output)) outs = [] for (output_index, ref) in zip(outputs_to_check, reference_outputs): output_blob_name = op.output[output_index] output = workspace.FetchBlob(output_blob_name) if output.dtype.kind in ('S', 'O'): np.testing.assert_array_equal(output, ref) else: if atol is None: atol = threshold np.testing.assert_allclose( output, ref, atol=atol, rtol=threshold) outs.append(output) if grad_reference and output_to_grad: self._assertGradReferenceChecks( op, inputs, reference_outputs, output_to_grad, grad_reference) return outs def assertValidationChecks( self, device_option, op, inputs, validator, input_device_options={}, as_kwargs=True ): if as_kwargs: assert len(set(list(op.input) + list(op.output))) == \ len(op.input) + len(op.output), \ "in-place ops are not supported in as_kwargs mode" op = copy.deepcopy(op) op.device_option.CopyFrom(device_option) with temp_workspace(): for (n, b) in zip(op.input, inputs): workspace.FeedBlob( n, b, device_option=input_device_options.get(n, device_option) ) workspace.RunOperatorOnce(op) outputs = [workspace.FetchBlob(n) for n in op.output] if as_kwargs: validator(**dict(zip( list(op.input) + list(op.output), inputs + outputs))) else: validator(inputs=inputs, outputs=outputs)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/recurrent_network_test.py
283
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, recurrent, workspace from caffe2.python.utils import debug from caffe2.python.model_helper import ModelHelperBase from caffe2.python.cnn import CNNModelHelper from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np def sigmoid(x): return 1.0 / (1.0 + np.exp(-x)) def tanh(x): return 2.0 * sigmoid(2.0 * x) - 1 def lstm_unit(cell_t_prev, gates, seq_lengths, timestep): D = cell_t_prev.shape[2] G = gates.shape[2] N = gates.shape[1] t = (timestep[0].reshape(1, 1) * np.ones(shape=(N, D))).astype(np.int32) assert t.shape == (N, D) seq_lengths = (np.ones(shape=(N, D)) * seq_lengths.reshape(N, 1)).astype(np.int32) assert seq_lengths.shape == (N, D) assert G == 4 * D # Resize to avoid broadcasting inconsistencies with NumPy gates = gates.reshape(N, 4, D) cell_t_prev = cell_t_prev.reshape(N, D) i_t = gates[:, 0, :].reshape(N, D) f_t = gates[:, 1, :].reshape(N, D) o_t = gates[:, 2, :].reshape(N, D) g_t = gates[:, 3, :].reshape(N, D) i_t = sigmoid(i_t) f_t = sigmoid(f_t) o_t = sigmoid(o_t) g_t = tanh(g_t) valid = (t < seq_lengths).astype(np.int32) assert valid.shape == (N, D) cell_t = ((f_t * cell_t_prev) + (i_t * g_t)) * (valid) + \ (1 - valid) * cell_t_prev assert cell_t.shape == (N, D) hidden_t = (o_t * tanh(cell_t)) * valid hidden_t = hidden_t.reshape(1, N, D) cell_t = cell_t.reshape(1, N, D) return hidden_t, cell_t def lstm_reference(input, hidden_input, cell_input, gates_w, gates_b, seq_lengths): T = input.shape[0] N = input.shape[1] G = input.shape[2] D = hidden_input.shape[2] hidden = np.zeros(shape=(T + 1, N, D)) cell = np.zeros(shape=(T + 1, N, D)) assert hidden.shape[0] == T + 1 assert cell.shape[0] == T + 1 assert hidden.shape[1] == N assert cell.shape[1] == N cell[0, :, :] = cell_input hidden[0, :, :] = hidden_input for t in range(T): timestep = np.asarray([t]).astype(np.int32) input_t = input[t].reshape(1, N, G) hidden_t_prev = hidden[t].reshape(1, N, D) cell_t_prev = cell[t].reshape(1, N, D) gates = np.dot(hidden_t_prev, gates_w.T) + gates_b gates = gates + input_t hidden_t, cell_t = lstm_unit(cell_t_prev, gates, seq_lengths, timestep) hidden[t + 1] = hidden_t cell[t + 1] = cell_t return ( hidden[1:], hidden[-1].reshape(1, N, D), cell[1:], cell[-1].reshape(1, N, D) ) def old_lstm_reference( input, seq_lengths, gates_w, gates_b, hidden_init, cell_init): output, last_output, cell_states, last_state = lstm_reference( input, hidden_init, cell_init, gates_w, gates_b, seq_lengths) return (output, last_output, last_state) class RecurrentNetworkTest(hu.HypothesisTestCase): @given(t=st.integers(1, 4), n=st.integers(1, 5), d=st.integers(1, 5)) def test_lstm_new(self, t, n, d): model = ModelHelperBase(name='external') def create_lstm( model, input_blob, seq_lengths, init, dim_in, dim_out, scope): recurrent.LSTM( model, input_blob, seq_lengths, init, dim_in, dim_out, scope="external/recurrent") self.lstm(model, create_lstm, t, n, d, lstm_reference, gradients_to_check=[0, 3, 4], outputs_to_check=[0, 1, 2, 3]) @given(t=st.integers(1, 4), n=st.integers(1, 5), d=st.integers(1, 5)) def test_lstm_old(self, t, n, d): model = CNNModelHelper(name='external') def create_lstm( model, input_blob, seq_lengths, init, dim_in, dim_out, scope): model.LSTM( input_blob, seq_lengths, init, dim_in, dim_out, scope="external/recurrent") # CNNModelHelper.LSTM returns only 3 outputs. But the operator itself # returns 5. We ignore the rest. self.lstm(model, create_lstm, t, n, d, old_lstm_reference, gradients_to_check=[0, 2, 3], outputs_to_check=[0, 3, 4]) @debug def lstm(self, model, create_lstm, t, n, d, ref, gradients_to_check, outputs_to_check=None): input_blob, seq_lengths, hidden_init, cell_init = ( model.net.AddExternalInputs( 'input_blob', 'seq_lengths', 'hidden_init', 'cell_init')) create_lstm( model, input_blob, seq_lengths, (hidden_init, cell_init), d, d, scope="external/recurrent") op = model.net._net.op[-1] def extract_param_name(model, param_substr): result = [] for p in model.params: if param_substr in str(p): result.append(str(p)) assert len(result) == 1 return result[0] workspace.RunNetOnce(model.param_init_net) input_blob = op.input[0] workspace.FeedBlob( str(input_blob), np.random.randn(t, n, d * 4).astype(np.float32)) workspace.FeedBlob( "hidden_init", np.random.randn(1, n, d).astype(np.float32)) workspace.FeedBlob( "cell_init", np.random.randn(1, n, d).astype(np.float32)) workspace.FeedBlob( "seq_lengths", np.random.randint(0, t, size=(n,)).astype(np.int32)) inputs = [workspace.FetchBlob(name) for name in op.input] print(op.input) print(inputs) self.assertReferenceChecks( hu.cpu_do, op, inputs, ref, outputs_to_check=outputs_to_check, ) # Checking for input, gates_t_w and gates_t_b gradients for param in gradients_to_check: self.assertGradientChecks( device_option=hu.cpu_do, op=op, inputs=inputs, outputs_to_check=param, outputs_with_grads=[0], threshold=0.01, ) @given(T=st.integers(1, 4), n=st.integers(1, 5), d=st.integers(1, 5)) def test_mul_rnn(self, T, n, d): model = ModelHelperBase(name='external') one_blob = model.param_init_net.ConstantFill( [], value=1.0, shape=[1, n, d]) input_blob = model.net.AddExternalInput('input') step = ModelHelperBase(name='step', param_model=model) input_t, output_t_prev = step.net.AddExternalInput( 'input_t', 'output_t_prev') output_t = step.net.Mul([input_t, output_t_prev]) step.net.AddExternalOutput(output_t) recurrent.recurrent_net( net=model.net, cell_net=step.net, inputs=[(input_t, input_blob)], initial_cell_inputs=[(output_t_prev, one_blob)], links={output_t_prev: output_t}, scratch_sizes=[], scope="test_mul_rnn", ) workspace.FeedBlob( str(input_blob), np.random.randn(T, n, d).astype(np.float32)) workspace.RunNetOnce(model.param_init_net) op = model.net._net.op[-1] def reference(input, initial_input): recurrent_input = initial_input result = np.zeros(shape=input.shape) for t_cur in range(T): recurrent_input = recurrent_input * input[t_cur] result[t_cur] = recurrent_input shape = list(input.shape) shape[0] = 1 return (result, result[-1].reshape(shape)) def grad_reference(output_grad, ref_output, inputs): input = inputs[0] output = ref_output[0] initial_input = inputs[1] input_grad = np.zeros(shape=input.shape) right_grad = 0 for t_cur in range(T - 1, -1, -1): prev_output = output[t_cur - 1] if t_cur > 0 else initial_input input_grad[t_cur] = (output_grad[t_cur] + right_grad) * prev_output right_grad = input[t_cur] * (output_grad[t_cur] + right_grad) return (input_grad, np.zeros(shape=[T, n, d]).astype(np.float32)) self.assertReferenceChecks( device_option=hu.cpu_do, op=op, inputs=[ workspace.FetchBlob(name) for name in [input_blob, one_blob] ], reference=reference, grad_reference=grad_reference, output_to_grad=op.output[0], outputs_to_check=[0, 1], ) @given(n=st.integers(1, 10), d=st.integers(1, 10), t=st.integers(1, 10), **hu.gcs) def test_lstm_unit_recurrent_network(self, n, d, t, dc, gc): op = core.CreateOperator( "LSTMUnit", ["cell_t_prev", "gates_t", "seq_lengths", "timestep"], ["hidden_t", "cell_t"]) cell_t_prev = np.random.randn(1, n, d).astype(np.float32) gates = np.random.randn(1, n, 4 * d).astype(np.float32) seq_lengths = np.random.randint(0, t, size=(n,)).astype(np.int32) timestep = np.random.randint(0, t, size=(1,)).astype(np.int32) inputs = [cell_t_prev, gates, seq_lengths, timestep] input_device_options = {"timestep": hu.cpu_do} self.assertDeviceChecks( dc, op, inputs, [0], input_device_options=input_device_options) self.assertReferenceChecks( gc, op, inputs, lstm_unit, input_device_options=input_device_options) for i in range(2): self.assertGradientChecks( gc, op, inputs, i, [0, 1], input_device_options=input_device_options)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/tt_core.py
239
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np """ The following methods are various utility methods for using the Tensor-Train decomposition, or TT-decomposition introduced by I. V. Oseledets (2011) in his paper (http://epubs.siam.org/doi/abs/10.1137/090752286). Broadly speaking, these methods are used to replace fully connected layers in neural networks with Tensor-Train layers introduced by A. Novikov et. al. (2015) in their paper (http://arxiv.org/abs/1509.06569). More details about each of the methods are provided in each respective docstring. """ def init_tt_cores(inp_sizes, out_sizes, tt_ranks, seed=1234): """ Initialize randomized orthogonalized TT-cores. This method should be used when a TT-layer will trained from scratch. The sizes of each of the cores are specified by the inp_sizes and out_sizes, and the respective tt_ranks will dictate the ranks of each of the cores. Note that a larger set of tt_ranks will result in slower computation but will result in more accurate approximations. The size of the ith core is: tt_ranks[i] * inp_sizes[i] * out_sizes[i] * tt_ranks[i + 1]. Note that the following relationships of lengths of each input is expected: len(inp_sizes) == len(out_sizes) == len(tt_ranks) - 1. Args: inp_sizes: list of the input dimensions of the respective cores out_sizes: list of the output dimensions of the respective cores tt_ranks: list of the ranks of the respective cores seed: integer to seed the random number generator Returns: cores: One-dimensional list of cores concatentated along an axis """ np.random.seed(seed) # Assert that the sizes of each input is correct assert(len(inp_sizes) == len(out_sizes)), \ "The number of input dimensions (" + str(len(inp_sizes)) + \ ") must be equal to the number of output dimensions (" + \ str(len(out_sizes)) + ")." assert(len(tt_ranks) == len(inp_sizes) + 1), \ "The number of tt-ranks (" + str(len(tt_ranks)) + ") must be " + \ "one more than the number of input and output dims (" + \ str(len(out_sizes)) + ")." # Convert to numpy arrays inp_sizes = np.array(inp_sizes) out_sizes = np.array(out_sizes) tt_ranks = np.array(tt_ranks) # Initialize the cores array cores_len = np.sum( inp_sizes * out_sizes * tt_ranks[1:] * tt_ranks[:-1]) cores = np.zeros(cores_len) cores_idx = 0 rv = 1 # Compute the full list of cores by computing each individual one for i in range(inp_sizes.shape[0]): shape = [tt_ranks[i], inp_sizes[i], out_sizes[i], tt_ranks[i + 1]] # Precompute the shape of each core tall_shape = (np.prod(shape[:3]), shape[3]) # Randomly initialize the current core using a normal distribution curr_core = np.dot(rv, np.random.normal( 0, 1, size=(shape[0], np.prod(shape[1:])))) curr_core = curr_core.reshape(tall_shape) # Orthogonalize the initialized current core and append to cores list if i < inp_sizes.shape[0] - 1: curr_core, rv = np.linalg.qr(curr_core) cores[cores_idx:cores_idx + curr_core.size] = curr_core.flatten() cores_idx += curr_core.size # Normalize the list of arrays using this Glarot trick glarot_style = (np.prod(inp_sizes) * np.prod(tt_ranks))**(1.0 / inp_sizes.shape[0]) return (0.1 / glarot_style) * np.array(cores).astype(np.float32) def matrix_to_tt(W, inp_sizes, out_sizes, tt_ranks): """ Convert a matrix into the TT-format. This method will consume an a 2D weight matrix such as those used in fully connected layers in a neural network and will compute the TT-decomposition of the weight matrix and return the TT-cores of the resulting computation. This method should be used when converting a trained, fully connected layer, into a TT-layer for increased speed and decreased parameter size. The size of the ith core is: tt_ranks[i] * inp_sizes[i] * out_sizes[i] * tt_ranks[i + 1]. Note that the following relationships of lengths of each input is expected: len(inp_sizes) == len(out_sizes) == len(tt_ranks) - 1. We also require that np.prod(inp_sizes) == W.shape[0] and that np.prod(out_sizes) == W.shape[1]. Args: W: two-dimensional weight matrix numpy array representing a fully connected layer to be converted to TT-format; note that the weight matrix is transposed before decomposed because we want to emulate the X * W^T operation that the FC layer performs. inp_sizes: list of the input dimensions of the respective cores out_sizes: list of the output dimensions of the respective cores tt_ranks: list of the ranks of the respective cores Returns: new_cores: One-dimensional list of cores concatentated along an axis """ # Assert that the sizes of each input is correct assert(len(inp_sizes) == len(out_sizes)), \ "The number of input dimensions (" + str(len(inp_sizes)) + \ ") must be equal to the number of output dimensions (" + \ str(len(out_sizes)) + ")." assert(len(tt_ranks) == len(inp_sizes) + 1), \ "The number of tt-ranks (" + str(len(tt_ranks)) + ") must be " + \ "one more than the number of input and output dimensions (" + \ str(len(out_sizes)) + ")." assert(W.shape[0] == np.prod(inp_sizes)), \ "The product of the input sizes (" + str(np.prod(inp_sizes)) + \ ") must be equal to first dimension of W (" + str(W.shape[0]) + ")." assert(W.shape[1] == np.prod(out_sizes)), \ "The product of the output sizes (" + str(np.prod(out_sizes)) + \ ") must be equal to second dimension of W (" + str(W.shape[1]) + ")." # W is transposed so that the multiplication X * W^T can be computed, just # as it is in the FC layer. W = W.transpose() # Convert to numpy arrays inp_sizes = np.array(inp_sizes) out_sizes = np.array(out_sizes) tt_ranks = np.array(tt_ranks) # Copy the original weight matrix in order to permute and reshape the weight # matrix. In addition, the inp_sizes and out_sizes are combined to a single # sizes array to use the tt_svd helper method, which only consumes a single # sizes array. W_copy = W.copy() total_inp_size = inp_sizes.size W_copy = np.reshape(W_copy, np.concatenate((inp_sizes, out_sizes))) order = np.repeat(np.arange(0, total_inp_size), 2) + \ np.tile([0, total_inp_size], total_inp_size) W_copy = np.transpose(W_copy, axes=order) W_copy = np.reshape(W_copy, inp_sizes * out_sizes) # Use helper method to convert the W matrix copy into the preliminary # cores array. cores = tt_svd(W_copy, inp_sizes * out_sizes, tt_ranks) # Permute the dimensions of each of the cores to be compatible with the # TT-layer. new_cores = np.zeros(cores.shape).astype(np.float32) idx = 0 for i in range(len(inp_sizes)): shape = (tt_ranks[i], inp_sizes[i], out_sizes[i], tt_ranks[i + 1]) current_core = cores[idx:idx + np.prod(shape)].reshape(shape) current_core = current_core.transpose((1, 3, 0, 2)) new_cores[new_cores.shape[0] - idx - np.prod(shape): new_cores.shape[0] - idx] \ = current_core.flatten() idx += np.prod(shape) return new_cores def tt_svd(W, sizes, tt_ranks): """ Helper method for the matrix_to_tt() method performing the TT-SVD decomposition. Uses the TT-decomposition algorithm to convert a matrix to TT-format using multiple reduced SVD operations. Args: W: two-dimensional weight matrix representing a fully connected layer to be converted to TT-format preprocessed by the matrix_to_tt() method. sizes: list of the dimensions of each of the cores tt_ranks: list of the ranks of the respective cores Returns: cores: One-dimensional list of cores concatentated along an axis """ assert(len(tt_ranks) == len(sizes) + 1) C = W.copy() total_size = sizes.size core = np.zeros(np.sum(tt_ranks[:-1] * sizes * tt_ranks[1:]), dtype='float32') # Compute iterative reduced SVD operations and store each resulting U matrix # as an individual core. pos = 0 for i in range(0, total_size - 1): shape = tt_ranks[i] * sizes[i] C = np.reshape(C, [shape, -1]) U, S, V = np.linalg.svd(C, full_matrices=False) U = U[:, 0:tt_ranks[i + 1]] S = S[0:tt_ranks[i + 1]] V = V[0:tt_ranks[i + 1], :] core[pos:pos + tt_ranks[i] * sizes[i] * tt_ranks[i + 1]] = U.ravel() pos += tt_ranks[i] * sizes[i] * tt_ranks[i + 1] C = np.dot(np.diag(S), V) core[pos:pos + tt_ranks[total_size - 1] * sizes[total_size - 1] * tt_ranks[total_size]] = C.ravel() return core # TODO(Surya) Write a method to convert an entire network where all fully # connected layers are replaced by an TT layer. def fc_net_to_tt_net(net): pass
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/memonger.py
286
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import networkx as nx import collections import time import copy from caffe2.python import workspace import logging log = logging.getLogger("memonger") log.setLevel(logging.INFO) LiveRange = collections.namedtuple('LiveRange', ["defined", "used"]) def share_grad_blobs(net, losses, param_grads, namescope): ''' Implements similar optimization as Torch's shareGradInput(): for the gradients that are passed between layers, share blobs between operators when possible. This yields significant memory savings with deep networks. Returns an optimized protobuf (assign to net._net) ''' def is_grad_blob(b): name = str(b) # Note: need to look at _{namescope} pattern as it matches # to handle the auto-split gradients return "_grad" in name and (name.startswith(namescope) or name.startswith("_" + namescope)) and name not in param_grads def is_grad_op(op): # TODO: something smarter for inp in op.input: if is_grad_blob(inp): return True for out in op.output: if is_grad_blob(out): return True return False start_time = time.time() log.warn("NOTE: Executing *experimental* memonger to " + "optimize gradient memory") # Collect ops that have something to do with # gradients if not namescope.endswith("/"): namescope += "/" netproto = copy.deepcopy(net.Proto()) grad_ops = [op for op in netproto.op if is_grad_op(op)] # Create mapping from blobs to ops blobs_to_ops = collections.defaultdict(lambda: []) blob_input_count = collections.defaultdict(lambda: 0) op_inputs = collections.defaultdict(lambda: 0) op_visit_count = collections.defaultdict(lambda: 0) for i, op in enumerate(grad_ops): for inp in op.input: if is_grad_blob(inp) or inp in losses: # Ignore in-place transformation ops (self cycles) if inp not in op.output: blobs_to_ops[inp].append(i) op_inputs[i] += 1 # Traverse operators starting from the loss blobs. # Keep tabs on when blobs are seen first and last, and also # when operators have their input satisfied. Share blobs only # under same branch, avoiding problems with parallel workers. output_blobs = set() mapping = {} def descend(op_idx, free_blobs): cur_op = grad_ops[op_idx] new_free_blobs = set() for inp in cur_op.input: if is_grad_blob(inp): blob_input_count[inp] += 1 if blob_input_count[inp] == len(blobs_to_ops[inp]): actual_blob = inp if inp not in mapping else mapping[inp] new_free_blobs.add(actual_blob) for outp in cur_op.output: if is_grad_blob(outp): if outp not in output_blobs: # First seen this blob as output, can assign to a free blob for freeb in free_blobs: mapping[outp] = freeb free_blobs.remove(freeb) break output_blobs.add(outp) free_blobs.update(new_free_blobs) first_branch = True for outp in cur_op.output: for inp_op_idx in blobs_to_ops[outp]: op_visit_count[inp_op_idx] += 1 # Descend only if we have satisfied all inputs if op_visit_count[inp_op_idx] == op_inputs[inp_op_idx]: free_blobs_fwd = free_blobs if first_branch else set() first_branch = False descend(inp_op_idx, free_blobs_fwd) # Start DFS from the losses for loss in losses: for op_idx in blobs_to_ops[loss]: descend(op_idx, set()) # Rename the shared blobs shared_blobs = set(mapping.values()) renamed = {} for j, b in enumerate(shared_blobs): renamed[b] = namescope + "__m{}_".format(j) # Final mapping for k, v in mapping.items(): mapping[k] = renamed[v] # Add the originators mapping.update(renamed) log.info("Remapping {} blobs, using {} shared".format( len(mapping), len(renamed), )) apply_assignments(netproto, mapping) log.info("Gradient memory optimization took {} secs".format( time.time() - start_time), ) return netproto def topological_sort_traversal(g): return nx.topological_sort(g) def compute_ranges(linearized_ops): blobs = collections.defaultdict(lambda: LiveRange(defined=None, used=None)) for i, op in enumerate(linearized_ops): for blob in op.input: used = blobs[blob].used if used is None: used = i else: used = max(used, i) blobs[blob] = blobs[blob]._replace(used=used) for blob in op.output: defined = blobs[blob].defined if defined is None: defined = i else: defined = min(defined, i) blobs[blob] = blobs[blob]._replace(defined=defined) return blobs def is_compatible(candidate_range, assignment, static_blobs): (name, range_) = assignment[-1] if name in static_blobs: return False if candidate_range.defined is None or range_.defined is None \ or range_.used is None: return False return candidate_range.defined > range_.used def compute_blob_assignments(assignments): blob_assignments = {} for assignment in assignments: if len(assignment) == 1: continue last_blob, _ = assignment[-1] for (blob, _) in assignment: blob_assignments[blob] = last_blob return blob_assignments def compute_assignments(ranges, static_blobs): # Sort the ranges based on when they are last used. # If LiveRange.used is None, then the blob is never used and could # be consumed externally. Sort these to the end of the list as opposed # to the beginning so that they can be shared as well. ranges = sorted( list(ranges.items()), key=lambda p: (p[1].used is None, p[1].used), ) assignments = [] for (name, range_) in ranges: assigned = False for assignment in assignments: if is_compatible(range_, assignment, static_blobs): assignment.append((name, range_)) assigned = True break if assigned: continue assignments.append([(name, range_)]) return assignments def compute_interference_graph(ops): g = nx.DiGraph() for i, op in enumerate(ops): g.add_node(i, op=op) for i, parent_op in enumerate(ops): for j, child_op in enumerate(ops): if i == j: continue if any(output in child_op.input for output in parent_op.output): deps = set(child_op.input).intersection(parent_op.output) g.add_edge(i, j, deps=deps) assert nx.is_directed_acyclic_graph(g), child_op return g Optimization = collections.namedtuple( 'Optimization', ['net', 'assignments', 'blob_assignments']) def apply_assignments(net, blob_assignments): def canonical_name(blob): if blob not in blob_assignments: return blob return blob_assignments[blob] for op in net.op: for i, input_ in enumerate(op.input): op.input[i] = canonical_name(input_) for i, output in enumerate(op.output): op.output[i] = canonical_name(output) def optimize_interference(net, static_blobs, ordering_function=topological_sort_traversal): """ 1) Use a BFS traversal of the execution graph to generate an ordering of the node executions. 2) Generate use-def ranges for each `blob` in the BFS traversal order. 3) Assign blobs to `canonical blobs` 4) Rename blobs to canonical blobs """ net = copy.deepcopy(net) g = compute_interference_graph(net.op) ordering = ordering_function(g) linearized_ops = [net.op[i] for i in ordering] # Reorder ops in net based on the computed linearlized order. # If the graph has multiple topological orderings and if the NetDef's # ordering differs from the order used to compute ranges, then the # runtime might end up overwriting blobs before they are used. del net.op[:] net.op.extend(linearized_ops) ranges = compute_ranges(linearized_ops) assignments = compute_assignments(ranges, static_blobs) blob_assignments = compute_blob_assignments(assignments) apply_assignments(net, blob_assignments) return Optimization( net=net, blob_assignments=blob_assignments, assignments=assignments) Statistics = collections.namedtuple( 'Statistics', ['baseline_nbytes', 'optimized_nbytes']) def compute_statistics(assignments): def blob_nbytes(blob): return workspace.FetchBlob(blob).nbytes blob_bytes = { blob: blob_nbytes(blob) for assignment in assignments for (blob, _) in assignment} baseline_nbytes = sum(v for _, v in blob_bytes.iteritems()) optimized_nbytes = sum( max(blob_bytes[blob] for (blob, _) in assignment) for assignment in assignments) return Statistics( baseline_nbytes=baseline_nbytes, optimized_nbytes=optimized_nbytes)
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/dataset_ops_test.py
416
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import core, workspace, dataset from caffe2.python.dataset import Const from caffe2.python.schema import ( List, Field, Struct, Scalar, Map, from_blob_list, FetchRecord, NewRecord, FeedRecord) from caffe2.python.test_util import TestCase def _assert_arrays_equal(actual, ref, err_msg): if ref.dtype.kind in ('S', 'O'): np.testing.assert_array_equal(actual, ref, err_msg=err_msg) else: np.testing.assert_allclose( actual, ref, atol=1e-4, rtol=1e-4, err_msg=err_msg) def _assert_records_equal(actual, ref): assert isinstance(actual, Field) assert isinstance(ref, Field) b1 = actual.field_blobs() b2 = ref.field_blobs() assert(len(b1) == len(b2)), 'Records have different lengths: %d vs. %d' % ( len(b1), len(b2)) for name, d1, d2 in zip(ref.field_names(), b1, b2): _assert_arrays_equal(d1, d2, err_msg='Mismatch in field %s.' % name) class TestDatasetOps(TestCase): def test_dataset_ops(self): """ 1. Defining the schema of our dataset. This example schema could represent, for example, a search query log. """ schema = Struct( # fixed size vector, which will be stored as a matrix when batched ('dense', Scalar((np.float32, 3))), # could represent a feature map from feature ID to float value ('floats', Map( Scalar(np.int32), Scalar(np.float32))), # could represent a multi-valued categorical feature map ('int_lists', Map( Scalar(np.int32), List(Scalar(np.int64)), )), # could represent a multi-valued, weighted categorical feature map ('id_score_pairs', Map( Scalar(np.int32), Map( Scalar(np.int64), Scalar(np.float32), keys_name='ids', values_name='scores'), )), # additional scalar information ('metadata', Struct( ('user_id', Scalar(np.int64)), ('user_embed', Scalar((np.float32, 2))), ('query', Scalar(str)), )), ) """ This is what the flattened fields for this schema look like, along with its type. Each one of these fields will be stored, read and writen as a tensor. """ expected_fields = [ ('dense', (np.float32, 3)), ('floats:lengths', np.int32), ('floats:values:keys', np.int32), ('floats:values:values', np.float32), ('int_lists:lengths', np.int32), ('int_lists:values:keys', np.int32), ('int_lists:values:values:lengths', np.int32), ('int_lists:values:values:values', np.int64), ('id_score_pairs:lengths', np.int32), ('id_score_pairs:values:keys', np.int32), ('id_score_pairs:values:values:lengths', np.int32), ('id_score_pairs:values:values:values:ids', np.int64), ('id_score_pairs:values:values:values:scores', np.float32), ('metadata:user_id', np.int64), ('metadata:user_embed', (np.float32, 2)), ('metadata:query', str), ] zipped = zip( expected_fields, schema.field_names(), schema.field_types()) for (ref_name, ref_type), name, dtype in zipped: self.assertEquals(ref_name, name) self.assertEquals(np.dtype(ref_type), dtype) """ 2. The contents of our dataset. Contents as defined below could represent, for example, a log of search queries along with dense, sparse features and metadata. The datset below has 3 top-level entries. """ contents_raw = [ # dense [[1.1, 1.2, 1.3], [2.1, 2.2, 2.3], [3.1, 3.2, 3.3]], # floats [1, 2, 3], # len [11, 21, 22, 31, 32, 33], # key [1.1, 2.1, 2.2, 3.1, 3.2, 3.3], # value # int lists [2, 0, 1], # len [11, 12, 31], # key [2, 4, 3], # value:len [111, 112, 121, 122, 123, 124, 311, 312, 313], # value:value # id score pairs [1, 2, 2], # len [11, 21, 22, 31, 32], # key [1, 1, 2, 2, 3], # value:len [111, 211, 221, 222, 311, 312, 321, 322, 323], # value:ids [11.1, 21.1, 22.1, 22.2, 31.1, 31.2, 32.1, 32.2, 32.3], # val:score # metadata [123, 234, 456], # user_id [[0.2, 0.8], [0.5, 0.5], [0.7, 0.3]], # user_embed ['dog posts', 'friends who like to', 'posts about ca'], # query ] # convert the above content to ndarrays, checking against the schema contents = from_blob_list(schema, contents_raw) """ 3. Creating and appending to the dataset. We first create an empty dataset with the given schema. Then, a Writer is used to append these entries to the dataset. """ ds = dataset.Dataset(schema) net = core.Net('init') ds.init_empty(net) content_blobs = NewRecord(net, contents) FeedRecord(content_blobs, contents) writer = ds.writer(init_net=net) writer.write_record(net, content_blobs) workspace.RunNetOnce(net) """ 4. Iterating through the dataset contents. If we were to iterate through the top level entries of our dataset, this is what we should expect to see: """ entries_raw = [ ( [[1.1, 1.2, 1.3]], # dense [1], [11], [1.1], # floats [2], [11, 12], [2, 4], [111, 112, 121, 122, 123, 124], # intlst [1], [11], [1], [111], [11.1], # id score pairs [123], [[0.2, 0.8]], ['dog posts'], # metadata ), ( [[2.1, 2.2, 2.3]], # dense [2], [21, 22], [2.1, 2.2], # floats [0], [], [], [], # int list [2], [21, 22], [1, 2], [211, 221, 222], [21.1, 22.1, 22.2], [234], [[0.5, 0.5]], ['friends who like to'], # metadata ), ( [[3.1, 3.2, 3.3]], # dense [3], [31, 32, 33], [3.1, 3.2, 3.3], # floats [1], [31], [3], [311, 312, 313], # int lst [2], [31, 32], [2, 3], [311, 312, 321, 322, 323], [31.1, 31.2, 32.1, 32.2, 32.3], # id score list [456], [[0.7, 0.3]], ['posts about ca'], # metadata ), # after the end of the dataset, we will keep getting empty vectors ([],) * 16, ([],) * 16, ] entries = [from_blob_list(schema, e) for e in entries_raw] """ Let's go ahead and create the reading nets. We will run `read` net multiple times and assert that we are reading the entries the way we stated above. """ read_init_net = core.Net('read_init') read_next_net = core.Net('read_next') reader = ds.reader(read_init_net) should_continue, batch = reader.read_record(read_next_net) workspace.RunNetOnce(read_init_net) workspace.CreateNet(read_next_net) for i, entry in enumerate(entries): workspace.RunNet(str(read_next_net)) actual = FetchRecord(batch) _assert_records_equal(actual, entry) """ 5. Reading/writing in a single plan If all of operations on the data are expressible as Caffe2 operators, we don't need to load the data to python, iterating through the dataset in a single Plan. Where we will process the dataset a little and store it in a second dataset. We can reuse the same Reader since it supports reset. """ reset_net = core.Net('reset_net') reader.reset(reset_net) read_step, batch = reader.execution_step() """ We will add the line number * 1000 to the feature ids. """ process_net = core.Net('process') line_no = Const(process_net, 0, dtype=np.int32) const_one = Const(process_net, 1000, dtype=np.int32) process_net.Add([line_no, const_one], [line_no]) field = batch.floats.keys.get() process_net.Print(field, []) process_net.Add([field, line_no], field, broadcast=1, axis=0) """ Lets create a second dataset and append to it. """ ds2 = dataset.Dataset(schema, name='dataset2') ds2.init_empty(reset_net) writer = ds2.writer(reset_net) writer.write_record(process_net, batch) # commit is not necessary for DatasetWriter but will add it for # generality of the example commit_net = core.Net('commit') writer.commit(commit_net) """ Time to create and run a plan which will do the processing """ plan = core.Plan('process') plan.AddStep(core.execution_step('reset', reset_net)) plan.AddStep(read_step.AddNet(process_net)) plan.AddStep(core.execution_step('commit', commit_net)) workspace.RunPlan(plan) """ Now we should have dataset2 populated. """ ds2_data = FetchRecord(ds2.content()) field = ds2_data.floats.keys field.set(blob=field.get() - [1000, 2000, 2000, 3000, 3000, 3000]) _assert_records_equal(contents, ds2_data) """ 6. Slicing a dataset You can create a new schema from pieces of another schema and reuse the same data. """ subschema = Struct(('top_level', schema.int_lists.values)) int_list_contents = contents.int_lists.values.field_names() self.assertEquals(len(subschema.field_names()), len(int_list_contents)) """ 7. Random Access a dataset """ read_init_net = core.Net('read_init') read_next_net = core.Net('read_next') idx = np.array([2, 1, 0]) indices_blob = Const(read_init_net, idx, name='indices') reader = ds.random_reader(read_init_net, indices_blob) reader.computeoffset(read_init_net) should_continue, batch = reader.read_record(read_next_net) workspace.CreateNet(read_init_net) workspace.RunNetOnce(read_init_net) workspace.CreateNet(read_next_net) read_next_net_name = str(read_next_net) for i in range(len(entries)): k = idx[i] if i in idx else i entry = entries[k] workspace.RunNet(str(read_next_net)) actual = FetchRecord(batch) _assert_records_equal(actual, entry) """ 8. Sort and shuffle a dataset This sort the dataset using the score of a certain column, and then shuffle within each chunk of size batch_size * shuffle_size before shuffling the chunks. """ read_init_net = core.Net('read_init') read_next_net = core.Net('read_next') reader = ds.random_reader(read_init_net) reader.sort_and_shuffle(read_init_net, 'int_lists:lengths', 1, 2) reader.computeoffset(read_init_net) should_continue, batch = reader.read_record(read_next_net) workspace.CreateNet(read_init_net) workspace.RunNetOnce(read_init_net) workspace.CreateNet(read_next_net) expected_idx = np.array([2, 1, 0]) for i in range(len(entries)): k = expected_idx[i] if i in expected_idx else i entry = entries[k] workspace.RunNet(str(read_next_net)) actual = FetchRecord(batch) _assert_records_equal(actual, entry) def test_last_n_window_ops(self): collect_net = core.Net('collect_net') collect_net.GivenTensorFill( [], 'input', shape=[3, 2], values=[1.0, 2.0, 3.0, 4.0, 5.0, 6.0], ) collect_net.LastNWindowCollector( ['input'], ['output'], num_to_collect=7, ) plan = core.Plan('collect_data') plan.AddStep(core.execution_step('collect_data', [collect_net], num_iter=1)) workspace.RunPlan(plan) reference_result = workspace.FetchBlob('output') self.assertSequenceEqual( [item for sublist in reference_result for item in sublist], [1, 2, 3, 4, 5, 6]) plan = core.Plan('collect_data') plan.AddStep(core.execution_step('collect_data', [collect_net], num_iter=2)) workspace.RunPlan(plan) reference_result = workspace.FetchBlob('output') self.assertSequenceEqual( [item for sublist in reference_result for item in sublist], [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]) plan = core.Plan('collect_data') plan.AddStep(core.execution_step('collect_data', [collect_net], num_iter=3)) workspace.RunPlan(plan) reference_result = workspace.FetchBlob('output') self.assertSequenceEqual( [item for sublist in reference_result for item in sublist], [3, 4, 5, 6, 5, 6, 1, 2, 3, 4, 5, 6, 1, 2]) def test_collect_tensor_ops(self): init_net = core.Net('init_net') blobs = ['blob_1', 'blob_2', 'blob_3'] bvec_map = {} ONE = init_net.ConstantFill([], 'ONE', shape=[1, 2], value=1) for b in blobs: init_net.ConstantFill([], [b], shape=[1, 2], value=0) bvec_map[b] = b + '_vec' init_net.CreateTensorVector([], [bvec_map[b]]) reader_net = core.Net('reader_net') for b in blobs: reader_net.Add([b, ONE], [b]) collect_net = core.Net('collect_net') num_to_collect = 1000 max_example_to_cover = 100000 bvec = [bvec_map[b] for b in blobs] collect_net.CollectTensor( bvec + blobs, bvec, num_to_collect=num_to_collect, ) print('Collect Net Proto: {}'.format(collect_net.Proto())) plan = core.Plan('collect_data') plan.AddStep(core.execution_step('collect_init', init_net)) plan.AddStep(core.execution_step('collect_data', [reader_net, collect_net], num_iter=max_example_to_cover)) workspace.RunPlan(plan) # concat the collected tensors concat_net = core.Net('concat_net') bconcated_map = {} for b in blobs: bconcated_map[b] = b + '_concated' concat_net.ConcatTensorVector([bvec_map[b]], [bconcated_map[b]]) workspace.RunNetOnce(concat_net) # check data reference_result = workspace.FetchBlob(bconcated_map[blobs[0]]) self.assertEqual(reference_result.shape, (min(num_to_collect, max_example_to_cover), 2)) hist, _ = np.histogram(reference_result[:, 0], bins=10, range=(1, max_example_to_cover)) print('Sample histogram: {}'.format(hist)) self.assertTrue(all(hist > 0.7 * (num_to_collect / 10))) for i in range(1, len(blobs)): result = workspace.FetchBlob(bconcated_map[blobs[i]]) self.assertEqual(reference_result.tolist(), result.tolist()) if __name__ == "__main__": import unittest unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/gradient_check_test.py
296
# TODO(jiayq): as more and more tests are moving to hypothesis test, we # can gradually remove this test script. DO NOT ADD MORE TESTS TO THIS # FILE. from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import numpy as np from caffe2.python import \ core, device_checker, gradient_checker, test_util, workspace import caffe2.python.hypothesis_test_util as hu from hypothesis import assume, given, settings import hypothesis.strategies as st from caffe2.proto import caffe2_pb2 import collections import unittest if workspace.has_gpu_support and workspace.NumCudaDevices() > 0: gpu_device_option = caffe2_pb2.DeviceOption() gpu_device_option.device_type = caffe2_pb2.CUDA cpu_device_option = caffe2_pb2.DeviceOption() gpu_device_checker = device_checker.DeviceChecker( 0.01, [gpu_device_option] ) device_checker = device_checker.DeviceChecker( 0.01, [gpu_device_option, cpu_device_option] ) gpu_gradient_checkers = [ gradient_checker.GradientChecker( 0.005, 0.05, gpu_device_option, "gpu_checker_ws" ), ] gradient_checkers = [ gradient_checker.GradientChecker( 0.005, 0.05, gpu_device_option, "gpu_checker_ws" ), gradient_checker.GradientChecker( 0.01, 0.05, cpu_device_option, "cpu_checker_ws" ), ] else: cpu_device_option = caffe2_pb2.DeviceOption() gpu_device_option = None gpu_device_checker = device_checker.DeviceChecker( 0.01, [] ) device_checker = device_checker.DeviceChecker(0.01, [cpu_device_option]) gradient_checkers = [ gradient_checker.GradientChecker( 0.01, 0.05, cpu_device_option, "cpu_checker_ws" ) ] gpu_gradient_checkers = [] class TestLRN(test_util.TestCase): def setUp(self): self.test_configs = [(6, 10), (3, 13), ] def testLRN(self): for input_size, depth in self.test_configs: op = core.CreateOperator("LRN", ["X"], ["Y", "Y_scale"], size=11, alpha=0.001, beta=0.5, bias=2.0, order="NHWC" ) X = np.random.rand(2, input_size, input_size, depth).astype(np.float32) res = device_checker.CheckSimple(op, [X], [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0]) self.assertTrue(res) class TestFlatten(test_util.TestCase): def testFlatten(self): op = core.CreateOperator("Flatten", ["X"], ["Y"]) X = np.random.rand(2, 3, 4, 5).astype(np.float32) res = device_checker.CheckSimple(op, [X], [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0]) self.assertTrue(res) class TestConcat(test_util.TestCase): def setUp(self): self.test_configs = [ # input_size, depth1, depth2, depth3, depth4 (3, 2, 3, 4, 5), (4, 5, 4, 3, 2), ] def testConcatNHWC(self): for input_size, d1, d2, d3, d4 in self.test_configs: op = core.CreateOperator("Concat", ["X1", "X2", "X3", "X4"], ["Y", "Y_dims"], order="NHWC" ) Xs = [ np.random.rand(2, input_size, input_size, d1).astype(np.float32), np.random.rand(2, input_size, input_size, d2).astype(np.float32), np.random.rand(2, input_size, input_size, d3).astype(np.float32), np.random.rand(2, input_size, input_size, d4).astype(np.float32) ] for i in range(4): res = device_checker.CheckSimple(op, Xs, [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, Xs, i, [0]) self.assertTrue(res) def testConcatNCHW(self): for input_size, d1, d2, d3, d4 in self.test_configs: op = core.CreateOperator("Concat", ["X1", "X2", "X3", "X4"], ["Y", "Y_dims"], order="NCHW" ) Xs = [ np.random.rand(2, d1, input_size, input_size).astype(np.float32), np.random.rand(2, d2, input_size, input_size).astype(np.float32), np.random.rand(2, d3, input_size, input_size).astype(np.float32), np.random.rand(2, d4, input_size, input_size).astype(np.float32) ] for i in range(4): res = device_checker.CheckSimple(op, Xs, [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, Xs, i, [0]) self.assertTrue(res) class TestRelu(test_util.TestCase): def setUp(self): self.test_configs = [ # input size # (0, 1), (1, 1), (2, 1), (1, 3, 3, 1), (2, 3, 3, 1), (1, 5, 5, 3), (2, 5, 5, 3), ] def testRelu(self): for input_size in self.test_configs: op = core.CreateOperator("Relu", ["X"], ["Y"]) X = np.random.rand(*input_size).astype(np.float32) # go away from the origin point to avoid kink problems X += 0.01 * np.sign(X) X[X == 0] = 0.01 res = device_checker.CheckSimple(op, [X], [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0]) self.assertTrue(res) class TestTanh(test_util.TestCase): def setUp(self): self.test_configs = [ # (0, 1), (1, 1), (2, 1), (1, 2, 3, 4), ] def testTanh(self): for input_size in self.test_configs: op = core.CreateOperator("Tanh", ["X"], ["Y"]) X = np.random.rand(*input_size).astype(np.float32) - 0.5 res = device_checker.CheckSimple(op, [X], [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0]) self.assertTrue(res) class TestExp(test_util.TestCase): def setUp(self): self.test_configs = [ # (0, 1), (1, 1), (2, 1), (1, 2, 3, 4), ] def testExp(self): for input_size in self.test_configs: op = core.CreateOperator("Exp", ["X"], ["Y"]) X = np.random.rand(*input_size).astype(np.float32) - 0.5 res = device_checker.CheckSimple(op, [X], [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0]) self.assertTrue(res) class TestSigmoid(test_util.TestCase): def setUp(self): self.test_configs = [ # (0, 1), (1, 1), (2, 1), (1, 2, 3, 4), ] def testSigmoid(self): for input_size in self.test_configs: op = core.CreateOperator("Sigmoid", ["X"], ["Y"]) X = np.random.rand(*input_size).astype(np.float32) - 0.5 res = device_checker.CheckSimple(op, [X], [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0]) self.assertTrue(res) class TestSum(test_util.TestCase): def setUp(self): self.test_configs = [ # ((0, 1), False), ((1, 2, 3, 4), True), ((1, 2, 3, 4), False)] def testSum(self): for (input_size, in_place) in self.test_configs: op = core.CreateOperator("Sum", ["X1", "X2"], ["Y" if not in_place else "X1"]) X1 = np.random.rand(*input_size).astype(np.float32) - 0.5 X2 = np.random.rand(*input_size).astype(np.float32) - 0.5 res = device_checker.CheckSimple(op, [X1, X2], [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple( op, [X1, X2], 0, [0]) self.assertTrue(res) class TestMakeTwoClass(test_util.TestCase): def setUp(self): self.test_configs = [ # input size # (0, 1), (1,), (7,), (1, 3), (2, 5), ] def testMakeTwoClass(self): for input_size in self.test_configs: op = core.CreateOperator("MakeTwoClass", ["X"], ["Y"]) X = np.random.rand(*input_size).astype(np.float32) # step a little to avoid gradient problems X[X < 0.01] += 0.01 X[X > 0.99] -= 0.01 res = device_checker.CheckSimple(op, [X], [0]) self.assertTrue(res) for checker in gradient_checkers: res, grad, grad_estimated = checker.CheckSimple(op, [X], 0, [0]) self.assertTrue(res) if __name__ == '__main__': workspace.GlobalInit(["python"]) unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/data_workers.py
298
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals ''' This module provides a python-land multithreaded data input mechanism for Caffe2 nets. Basic usage is as follows: coordinator = data_workers.init_data_input_workers( net, ["data", "label"], my_fetch_fun, batch_size=32, input_source_name="train" ) ... coordinator.start() First argument is the Caffe2 net (or model helper), and second argument is list of input blobs that are to be fed. Argument 'input_source_name' is used to distinguish different sources of data, such as train or test data. This is to ensure the data does not get mixed up, although two nets would share blobs. To do the actual data loading, one defines a "fetcher function" that has call signature my_fetch_fun(worker_id, batch_size) This function returns a list of numpy arrays corresponding to the different input blobs. In the example above, it would return two arrays, one for the data blob and another for the labels. These arrays can have arbitrary number of elements (i.e they do not need to match the batch size). The batch size is provided for the function as a hint only. For example, fetcher function could download images from a remote service or load random images from a directory on a file system. For a dummy example, see the data_workers_test unit test. Note that for data_parallel_models, init_data_input_workers will be called for each GPU. Note that the 'coordinator' returned by the function is same each time. ''' import Queue import logging import threading import atexit import numpy as np from caffe2.python import workspace, core, scope from caffe2.proto import caffe2_pb2 log = logging.getLogger("data_workers") def init_data_input_workers( net, input_blob_names, fetch_fun, batch_size, num_worker_threads=2, input_source_name="train", ): global global_coordinator device_option = scope.CurrentDeviceScope() if (device_option is None): device_option = caffe2_pb2.DeviceOption(device_type=caffe2_pb2.CPU) # Create coordinator object coordinator = DataInputCoordinator( net, input_blob_names, batch_size, device_option, scope.CurrentNameScope(), input_source_name, ) # Launch fetch worker threads workers = [ threading.Thread( target=fetcher, args=[coordinator, global_coordinator._fetcher_id_seq + i, fetch_fun, batch_size, input_blob_names], ) for i in range(num_worker_threads) ] global_coordinator._fetcher_id_seq += num_worker_threads workers.append(threading.Thread( target=enqueuer, args=[coordinator])) coordinator._workers = workers global_coordinator.add(coordinator) return global_coordinator class DataInputCoordinator(object): def __init__(self, net, input_blob_names, batch_size, device_option, namescope, input_source_name): self._net = net self._input_blob_names = input_blob_names self._batch_size = batch_size self._internal_queue = Queue.Queue(maxsize=500) self._queues = [] self._device_option = device_option self._namescope = namescope self._active = True self._started = False self._workers = [] self._input_source_name = input_source_name self._create_caffe2_queues_and_ops() def is_active(self): return self._active def _start(self): if self._started: return self._active = True self._started = True for w in self._workers: w.daemon = True w.start() def _stop(self, reason=None): self._active = False if reason is not None: log.error("Data input failed due to an error: {}".format(reason)) self._started = False def _wait_finish(self): log.info("Wait for workers to die") for w in self._workers: if w != threading.current_thread(): w.join(1.0) # don't wait forever, thread may be blocked in i/o log.info("...finished") def _get(self): while self.is_active(): try: return self._internal_queue.get(block=True, timeout=0.5) except Queue.Empty: continue return None def put(self, chunk): while self.is_active(): try: self._internal_queue.put(chunk, block=True, timeout=0.5) return except Queue.Full: log.debug("Queue full: stalling fetchers...") continue def _enqueue_batch(self): ''' This pulls data from the python-side queue and collects them into batch-sized pieces. ''' cur_batch = [np.array([]) for d in self._input_blob_names] # Collect data until we have a full batch size while cur_batch[0].shape[0] < self._batch_size and self.is_active(): chunk = self._get() if chunk is None: continue for j, chunk_elem in enumerate(chunk): if cur_batch[j].shape[0] == 0: cur_batch[j] = chunk_elem.copy() else: cur_batch[j] = np.append(cur_batch[j], chunk_elem, axis=0) # Return data over the batch size back to queue if cur_batch[0].shape[0] > self._batch_size: leftover = [c[self._batch_size:] for c in cur_batch] cur_batch = [c[:self._batch_size] for c in cur_batch] try: self._internal_queue.put(leftover, block=False) except Queue.Full: pass assert cur_batch[0].shape[0] == self._batch_size if self.is_active(): for b, q, c in zip(self._input_blob_names, self._queues, cur_batch): self._enqueue(b, q, c) def _enqueue(self, blob_name, queue, data_arr): ''' Enqueue the correctly sized batch arrays to Caffe2's queue. ''' scratch_name = self._namescope + blob_name + \ "_scratch_" + self._input_source_name blob = core.BlobReference(scratch_name) workspace.FeedBlob( blob, data_arr, device_option=self._device_option ) op = core.CreateOperator( "EnqueueBlobs", [queue, blob], [blob], device_option=self._device_option ) workspace.RunOperatorOnce(op) def _create_caffe2_queues_and_ops(self): ''' Creates queues on caffe2 side, and respective operators to pull (dequeue) blobs from the queues. ''' def create_queue(queue_name, num_blobs, capacity): workspace.RunOperatorOnce( core.CreateOperator( "CreateBlobsQueue", [], [queue_name], num_blobs=1, capacity=capacity)) return core.ScopedBlobReference(queue_name) for blob_name in self._input_blob_names: qname = blob_name + "_c2queue" + "_" + self._input_source_name q = create_queue(qname, num_blobs=1, capacity=4) self._queues.append(q) log.info("Created queue: {}".format(q)) # Add operator to the Caffe2 network to dequeue self._net.DequeueBlobs(q, blob_name) class GlobalCoordinator(object): def __init__(self): self._coordinators = [] self._fetcher_id_seq = 0 self.register_shutdown_handler() def add(self, coordinator): self._coordinators.append(coordinator) def start(self): for c in self._coordinators: c._start() def stop(self): for c in self._coordinators: c._stop() for c in self._coordinators: c._wait_finish() self._coordinators = [] def register_shutdown_handler(self): def cleanup(): self.stop() atexit.register(cleanup) global_coordinator = GlobalCoordinator() def fetcher(coordinator, worker_id, fetch_fun, batch_size, input_blob_names): while coordinator.is_active(): try: input_data = fetch_fun(worker_id, batch_size) if input_data is None: log.warn("Fetcher function returned None") continue assert len(input_data) == len(input_blob_names), \ "Expecting data blob for each input" for d in input_data: assert isinstance(d, np.ndarray), \ "Fetcher function must return a numpy array" for d in input_data[1:]: assert d.shape[0] == input_data[0].shape[0], \ "Each returned input must have equal number of samples" coordinator.put(input_data) except Exception as e: log.error(e) coordinator._stop("Exception in fetcher {}: {}".format( worker_id, e )) def enqueuer(coordinator): while coordinator.is_active(): coordinator._enqueue_batch()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/net_drawer.py
376
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import json from collections import defaultdict from caffe2.python import utils try: import pydot except ImportError: print( 'Cannot import pydot, which is required for drawing a network. This ' 'can usually be installed in python with "pip install pydot". Also, ' 'pydot requires graphviz to convert dot files to pdf: in ubuntu, this ' 'can usually be installed with "sudo apt-get install graphviz".' ) print( 'net_drawer will not run correctly. Please install the correct ' 'dependencies.' ) pydot = None from caffe2.proto import caffe2_pb2 OP_STYLE = { 'shape': 'box', 'color': '#0F9D58', 'style': 'filled', 'fontcolor': '#FFFFFF' } BLOB_STYLE = {'shape': 'octagon'} def _rectify_operator_and_name(operators_or_net, name): """Gets the operators and name for the pydot graph.""" if isinstance(operators_or_net, caffe2_pb2.NetDef): operators = operators_or_net.op if name is None: name = operators_or_net.name elif hasattr(operators_or_net, 'Proto'): net = operators_or_net.Proto() if not isinstance(net, caffe2_pb2.NetDef): raise RuntimeError( "Expecting NetDef, but got {}".format(type(net))) operators = net.op if name is None: name = net.name else: operators = operators_or_net if name is None: name = "unnamed" return operators, name def _escape_label(name): # json.dumps is poor man's escaping return json.dumps(name) def GetOpNodeProducer(append_output, **kwargs): def ReallyGetOpNode(op, op_id): if op.name: node_name = '%s/%s (op#%d)' % (op.name, op.type, op_id) else: node_name = '%s (op#%d)' % (op.type, op_id) if append_output: for output_name in op.output: node_name += '\n' + output_name return pydot.Node(node_name, **kwargs) return ReallyGetOpNode def GetPydotGraph( operators_or_net, name=None, rankdir='LR', node_producer=None ): if node_producer is None: node_producer = GetOpNodeProducer(False, **OP_STYLE) operators, name = _rectify_operator_and_name(operators_or_net, name) graph = pydot.Dot(name, rankdir=rankdir) pydot_nodes = {} pydot_node_counts = defaultdict(int) for op_id, op in enumerate(operators): op_node = node_producer(op, op_id) graph.add_node(op_node) # print 'Op: %s' % op.name # print 'inputs: %s' % str(op.input) # print 'outputs: %s' % str(op.output) for input_name in op.input: if input_name not in pydot_nodes: input_node = pydot.Node( _escape_label( input_name + str(pydot_node_counts[input_name])), label=_escape_label(input_name), **BLOB_STYLE ) pydot_nodes[input_name] = input_node else: input_node = pydot_nodes[input_name] graph.add_node(input_node) graph.add_edge(pydot.Edge(input_node, op_node)) for output_name in op.output: if output_name in pydot_nodes: # we are overwriting an existing blob. need to updat the count. pydot_node_counts[output_name] += 1 output_node = pydot.Node( _escape_label( output_name + str(pydot_node_counts[output_name])), label=_escape_label(output_name), **BLOB_STYLE ) pydot_nodes[output_name] = output_node graph.add_node(output_node) graph.add_edge(pydot.Edge(op_node, output_node)) return graph def GetPydotGraphMinimal( operators_or_net, name=None, rankdir='LR', minimal_dependency=False, node_producer=None, ): """Different from GetPydotGraph, hide all blob nodes and only show op nodes. If minimal_dependency is set as well, for each op, we will only draw the edges to the minimal necessary ancestors. For example, if op c depends on op a and b, and op b depends on a, then only the edge b->c will be drawn because a->c will be implied. """ if node_producer is None: node_producer = GetOpNodeProducer(False, **OP_STYLE) operators, name = _rectify_operator_and_name(operators_or_net, name) graph = pydot.Dot(name, rankdir=rankdir) # blob_parents maps each blob name to its generating op. blob_parents = {} # op_ancestry records the ancestors of each op. op_ancestry = defaultdict(set) for op_id, op in enumerate(operators): op_node = node_producer(op, op_id) graph.add_node(op_node) # Get parents, and set up op ancestry. parents = [ blob_parents[input_name] for input_name in op.input if input_name in blob_parents ] op_ancestry[op_node].update(parents) for node in parents: op_ancestry[op_node].update(op_ancestry[node]) if minimal_dependency: # only add nodes that do not have transitive ancestry for node in parents: if all( [node not in op_ancestry[other_node] for other_node in parents] ): graph.add_edge(pydot.Edge(node, op_node)) else: # Add all parents to the graph. for node in parents: graph.add_edge(pydot.Edge(node, op_node)) # Update blob_parents to reflect that this op created the blobs. for output_name in op.output: blob_parents[output_name] = op_node return graph def GetOperatorMapForPlan(plan_def): operator_map = {} for net_id, net in enumerate(plan_def.network): if net.HasField('name'): operator_map[plan_def.name + "_" + net.name] = net.op else: operator_map[plan_def.name + "_network_%d" % net_id] = net.op return operator_map def _draw_nets(nets, g): nodes = [] for i, net in enumerate(nets): nodes.append(pydot.Node(_escape_label(net))) g.add_node(nodes[-1]) if i > 0: g.add_edge(pydot.Edge(nodes[-2], nodes[-1])) return nodes def _draw_steps(steps, g, skip_step_edges=False): # noqa kMaxParallelSteps = 3 def get_label(): label = [step.name + '\n'] if step.report_net: label.append('Reporter: {}'.format(step.report_net)) if step.should_stop_blob: label.append('Stopper: {}'.format(step.should_stop_blob)) if step.concurrent_substeps: label.append('Concurrent') if step.only_once: label.append('Once') return '\n'.join(label) def substep_edge(start, end): return pydot.Edge(start, end, arrowhead='dot', style='dashed') nodes = [] for i, step in enumerate(steps): parallel = step.concurrent_substeps nodes.append(pydot.Node(_escape_label(get_label()), **OP_STYLE)) g.add_node(nodes[-1]) if i > 0 and not skip_step_edges: g.add_edge(pydot.Edge(nodes[-2], nodes[-1])) if step.network: sub_nodes = _draw_nets(step.network, g) elif step.substep: if parallel: sub_nodes = _draw_steps( step.substep[:kMaxParallelSteps], g, skip_step_edges=True) else: sub_nodes = _draw_steps(step.substep, g) else: raise ValueError('invalid step') if parallel: for sn in sub_nodes: g.add_edge(substep_edge(nodes[-1], sn)) if len(step.substep) > kMaxParallelSteps: ellipsis = pydot.Node('{} more steps'.format( len(step.substep) - kMaxParallelSteps), **OP_STYLE) g.add_node(ellipsis) g.add_edge(substep_edge(nodes[-1], ellipsis)) else: g.add_edge(substep_edge(nodes[-1], sub_nodes[0])) return nodes def GetPlanGraph(plan_def, name=None, rankdir='TB'): graph = pydot.Dot(name, rankdir=rankdir) _draw_steps(plan_def.execution_step, graph) return graph def GetGraphInJson(operators_or_net, output_filepath): operators, _ = _rectify_operator_and_name(operators_or_net, None) blob_strid_to_node_id = {} node_name_counts = defaultdict(int) nodes = [] edges = [] for op_id, op in enumerate(operators): op_label = op.name + '/' + op.type if op.name else op.type op_node_id = len(nodes) nodes.append({ 'id': op_node_id, 'label': op_label, 'op_id': op_id, 'type': 'op' }) for input_name in op.input: strid = _escape_label( input_name + str(node_name_counts[input_name])) if strid not in blob_strid_to_node_id: input_node = { 'id': len(nodes), 'label': input_name, 'type': 'blob' } blob_strid_to_node_id[strid] = len(nodes) nodes.append(input_node) else: input_node = nodes[blob_strid_to_node_id[strid]] edges.append({ 'source': blob_strid_to_node_id[strid], 'target': op_node_id }) for output_name in op.output: strid = _escape_label( output_name + str(node_name_counts[output_name])) if strid in blob_strid_to_node_id: # we are overwriting an existing blob. need to update the count. node_name_counts[output_name] += 1 strid = _escape_label( output_name + str(node_name_counts[output_name])) if strid not in blob_strid_to_node_id: output_node = { 'id': len(nodes), 'label': output_name, 'type': 'blob' } blob_strid_to_node_id[strid] = len(nodes) nodes.append(output_node) edges.append({ 'source': op_node_id, 'target': blob_strid_to_node_id[strid] }) with open(output_filepath, 'w') as f: json.dump({'nodes': nodes, 'edges': edges}, f) def main(): parser = argparse.ArgumentParser(description="Caffe2 net drawer.") parser.add_argument( "--input", type=str, help="The input protobuf file." ) parser.add_argument( "--output_prefix", type=str, default="", help="The prefix to be added to the output filename." ) parser.add_argument( "--minimal", action="store_true", help="If set, produce a minimal visualization." ) parser.add_argument( "--minimal_dependency", action="store_true", help="If set, only draw minimal dependency." ) parser.add_argument( "--append_output", action="store_true", help="If set, append the output blobs to the operator names.") parser.add_argument( "--rankdir", type=str, default="LR", help="The rank direction of the pydot graph." ) args = parser.parse_args() with open(args.input, 'r') as fid: content = fid.read() graphs = utils.GetContentFromProtoString( content, { caffe2_pb2.PlanDef: lambda x: GetOperatorMapForPlan(x), caffe2_pb2.NetDef: lambda x: {x.name: x.op}, } ) for key, operators in graphs.items(): if args.minimal: graph = GetPydotGraphMinimal( operators, name=key, rankdir=args.rankdir, node_producer=GetOpNodeProducer(args.append_output, **OP_STYLE), minimal_dependency=args.minimal_dependency) else: graph = GetPydotGraph( operators, name=key, rankdir=args.rankdir, node_producer=GetOpNodeProducer(args.append_output, **OP_STYLE)) filename = args.output_prefix + graph.get_name() + '.dot' graph.write(filename, format='raw') pdf_filename = filename[:-3] + 'pdf' try: graph.write_pdf(pdf_filename) except Exception: print( 'Error when writing out the pdf file. Pydot requires graphviz ' 'to convert dot files to pdf, and you may not have installed ' 'graphviz. On ubuntu this can usually be installed with "sudo ' 'apt-get install graphviz". We have generated the .dot file ' 'but will not be able to generate pdf file for now.' ) if __name__ == '__main__': main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/contrib/prof/htrace_to_chrome.py
199
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import argparse import json import re import sys display_levels = ["network", "worker", "operator", "kernel"] def stop_display(limit, curr): return display_levels.index(limit) <= display_levels.index(curr) def build_trace_dict(f, start_time, end_time): """Creates a python dictionary that has trace ids as keys and the corresponding trace objects as values. Input: python file object that points to a file with traces, written by htrace-c's local file span receiver. The exact format shouldn't concern you if you're using htrace-c correctly. https://github.com/apache/incubator-htrace/blob/master/htrace-c. Returns: a tuple (trace_dic, root_list), where trace_dic is a dictionary containing all traces parsed from the input file object, and root_list is a list of traces from trace_dic which have no parents. Each value in trace_dic is in the form of another dictionary with the folowing keys: "begin" : timestamp of trace start time, microseconds "end" : timestamp of trace end time, microseconds "desc" : description of trace "parent" : trace id of parent trace "children": dictionary of child traces, in the same format as trace_dic """ trace_dic = {} root_list = [] for line in f: h = json.loads(line) if h["e"] < start_time or h["b"] > end_time: continue entry = {"begin": h["b"], "end": h["e"], "desc": h["d"]} if "p" not in h or len(h["p"]) == 0: root_list.append(entry) else: entry["parent"] = h["p"][0] trace_dic[h["a"]] = entry for k, v in trace_dic.items(): if "parent" not in v: continue parent = trace_dic[v["parent"]] if "children" not in parent: parent["children"] = {} parent["children"][k] = v return trace_dic, root_list def generate_chrome_trace(root_list, display): """Takes trace objects created by build_trace_dict() and generates a list of python dictionaries that can be written to a file in json format, which in turn can be given to Chrome tracing (chrome://tracing). Input: refer to root_list in build_trace_dict()'s return value. Output: list of dictionaries that can be directly written to a json file by json.dumps(). The dictionary format follows the JSON array format of Chrome tracing. Complete events ("ph": "X") are used to express most traces; such events will appear as horizontal blocks with lengths equal to the trace duration. Instant events ("ph": "i") are used for traces with many occurrencs which may make the trace graph unreadable; such events are shown as thin lines. """ ct = [] for root_idx, root in enumerate(root_list): # network-level spans ct.append({ "name": root["desc"], "ph": "X", "ts": root["begin"], "dur": root["end"] - root["begin"], "pid": root_idx, "tid": root_idx, "args": { "Start timestamp": root["begin"], "End timestamp": root["end"] } }) for _, v in root["children"].items(): # run-scopes and worker-scopes c = { "name": v["desc"], "ph": "X", "ts": v["begin"], "dur": v["end"] - v["begin"], "pid": root_idx, "args": { "Start timestamp": v["begin"], "End timestamp": v["end"] } } if "run-scope" in v["desc"]: c["tid"] = root_idx ct.append(c) else: if stop_display(display, "network"): continue m = re.search("(?<=worker-scope-)\d+", v["desc"]) wid = m.group(0) c["tid"] = wid ct.append(c) if stop_display(display, "worker") or "children" not in v: continue for k_op, v_op in v["children"].items(): # operator scopes ct.append({ "name": v_op["desc"], "ph": "X", "ts": v_op["begin"], "dur": v_op["end"] - v_op["begin"], "pid": root_idx, "tid": wid, "args": { "Start timestamp": v_op["begin"], "End timestamp": v_op["end"] } }) if stop_display(display, "operator") or "children" not in v_op: continue for idx, (k_gpu_op, v_gpu_op) in \ enumerate(sorted(v_op["children"].items(), key=lambda e: e[1]["begin"])): # kernel scopes if idx == 0: ct.append({ "name": v_op["desc"] + "-GPU", "ph": "X", "ts": v_gpu_op["begin"], "dur": v_gpu_op["end"] - v_gpu_op["begin"], "pid": root_idx, "tid": wid, "args": { "desc": "NEW OPERATOR", "Start timestamp": v_gpu_op["begin"], "End timestamp": v_gpu_op["end"] } }) ct.append({ "name": v_op["desc"] + "-GPU", "ph": "i", "ts": v_gpu_op["begin"], "pid": root_idx, "tid": wid, "args": { "desc": v_gpu_op["desc"] } }) return ct def get_argument_parser(): parser = argparse.ArgumentParser( description="Format conversion from HTrace to Chrome tracing.") parser.add_argument("htrace_log", type=str, help="input htrace span log file") parser.add_argument("--display", type=str, choices=display_levels, default="operator", help="deepest level of spans to display (default: operator)") parser.add_argument("--start_time", type=int, default=-1, help="do not display spans occuring before this timestamp") parser.add_argument("--end_time", type=int, default=sys.maxsize, help="do not display spans occuring after this timestamp") return parser def main(): args = get_argument_parser().parse_args() with open(args.htrace_log, "r") as f: trace_dic, root_list = build_trace_dict(f, args.start_time, args.end_time) ct = generate_chrome_trace(root_list, args.display) print("Writing chrome json file to %s.json" % args.htrace_log) print("Now import %s.json in chrome://tracing" % args.htrace_log) with open(args.htrace_log + ".json", "w") as f: f.write(json.dumps(ct)) if __name__ == '__main__': main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/workspace.py
468
import contextlib from google.protobuf.message import Message from multiprocessing import Process import os import shutil import socket import tempfile import logging import numpy as np from caffe2.proto import caffe2_pb2 from caffe2.python import scope, utils import caffe2.python._import_c_extension as C logger = logging.getLogger(__name__) Blobs = C.blobs CreateBlob = C.create_blob CurrentWorkspace = C.current_workspace DeserializeBlob = C.deserialize_blob GlobalInit = C.global_init HasBlob = C.has_blob RegisteredOperators = C.registered_operators SerializeBlob = C.serialize_blob SwitchWorkspace = C.switch_workspace RootFolder = C.root_folder Workspaces = C.workspaces BenchmarkNet = C.benchmark_net is_asan = C.is_asan has_gpu_support = C.has_gpu_support if has_gpu_support: NumCudaDevices = C.num_cuda_devices SetDefaultGPUID = C.set_default_gpu_id GetDefaultGPUID = C.get_default_gpu_id def GetCudaPeerAccessPattern(): return np.asarray(C.get_cuda_peer_access_pattern()) else: def NumCudaDevices(): return 0 # Python 2 and 3 compatibility: test if basestring exists try: basestring # NOQA except NameError: # This is python3 so we define basestring. basestring = str def _GetFreeFlaskPort(): """Get a free flask port.""" # We will prefer to use 5000. If not, we will then pick a random port. sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM) result = sock.connect_ex(('127.0.0.1', 5000)) if result == 0: return 5000 else: s = socket.socket() s.bind(('', 0)) port = s.getsockname()[1] s.close() # Race condition: between the interval we close the socket and actually # start a mint process, another process might have occupied the port. We # don't do much here as this is mostly for convenience in research # rather than 24x7 service. return port def StartMint(root_folder=None, port=None): """Start a mint instance. TODO(Yangqing): this does not work well under ipython yet. According to https://github.com/ipython/ipython/issues/5862 writing up some fix is a todo item. """ from caffe2.python.mint import app if root_folder is None: # Get the root folder from the current workspace root_folder = C.root_folder() if port is None: port = _GetFreeFlaskPort() process = Process( target=app.main, args=( ['-p', str(port), '-r', root_folder], ) ) process.start() print('Mint running at http://{}:{}'.format(socket.getfqdn(), port)) return process def StringfyProto(obj): """Stringfy a protocol buffer object. Inputs: obj: a protocol buffer object, or a Pycaffe2 object that has a Proto() function. Outputs: string: the output protobuf string. Raises: AttributeError: if the passed in object does not have the right attribute. """ if type(obj) is str: return obj else: if isinstance(obj, Message): # First, see if this object is a protocol buffer, which we can # simply serialize with the SerializeToString() call. return obj.SerializeToString() elif hasattr(obj, 'Proto'): return obj.Proto().SerializeToString() else: raise ValueError("Unexpected argument to StringfyProto of type " + type(obj).__name__) def ResetWorkspace(root_folder=None): if root_folder is None: # Reset the workspace, but keep the current root folder setting. return C.reset_workspace(C.root_folder()) else: if not os.path.exists(root_folder): os.makedirs(root_folder) return C.reset_workspace(root_folder) def CreateNet(net, input_blobs=None): if input_blobs is None: input_blobs = [] for input_blob in input_blobs: C.create_blob(input_blob) return C.create_net(StringfyProto(net)) def RunOperatorOnce(operator): return C.run_operator_once(StringfyProto(operator)) def RunOperatorsOnce(operators): for op in operators: success = RunOperatorOnce(op) if not success: return False return True def RunNetOnce(net): return C.run_net_once(StringfyProto(net)) def RunNet(name): """Runs a given net. Inputs: name: the name of the net, or a reference to the net. Returns: True or an exception. """ return C.run_net(StringifyNetName(name)) def RunPlan(plan_or_step): # TODO(jiayq): refactor core.py/workspace.py to avoid circular deps import caffe2.python.core as core if isinstance(plan_or_step, core.ExecutionStep): plan_or_step = core.Plan(plan_or_step) return C.run_plan(StringfyProto(plan_or_step)) def _StringifyName(name, expected_type): if isinstance(name, basestring): return name assert type(name).__name__ == expected_type, \ "Expected a string or %s" % expected_type return str(name) def StringifyBlobName(name): return _StringifyName(name, "BlobReference") def StringifyNetName(name): return _StringifyName(name, "Net") def FeedBlob(name, arr, device_option=None): """Feeds a blob into the workspace. Inputs: name: the name of the blob. arr: either a TensorProto object or a numpy array object to be fed into the workspace. device_option (optional): the device option to feed the data with. Returns: True or False, stating whether the feed is successful. """ if type(arr) is caffe2_pb2.TensorProto: arr = utils.Caffe2TensorToNumpyArray(arr) if type(arr) is np.ndarray and arr.dtype.kind == 'S': # Plain NumPy strings are weird, let's use objects instead arr = arr.astype(np.object) if device_option is None: device_option = scope.CurrentDeviceScope() if device_option and device_option.device_type == caffe2_pb2.CUDA: if arr.dtype == np.dtype('float64'): logger.warning( "CUDA operators do not support 64-bit doubles, " + "please use arr.astype(np.float32) or np.int32 for ints." + " Blob: {}".format(name) + " type: {}".format(str(arr.dtype)) ) name = StringifyBlobName(name) if device_option is not None: return C.feed_blob(name, arr, StringfyProto(device_option)) else: return C.feed_blob(name, arr) def FetchBlobs(names): """Fetches a list of blobs from the workspace. Inputs: names: list of names of blobs - strings or BlobReferences Returns: list of fetched blobs """ return [FetchBlob(name) for name in names] def FetchBlob(name): """Fetches a blob from the workspace. Inputs: name: the name of the blob - a string or a BlobReference Returns: Fetched blob (numpy array or string) if successful """ return C.fetch_blob(StringifyBlobName(name)) def GetNameScope(): """Return the current namescope string. To be used to fetch blobs""" return scope.CurrentNameScope() class _BlobDict(object): """Provides python dict compatible way to do fetching and feeding""" def __getitem__(self, key): return FetchBlob(key) def __setitem__(self, key, value): return FeedBlob(key, value) def __len__(self): return len(C.blobs()) def __iter__(self): return C.blobs().__iter__() def __contains__(self, item): return C.has_blob(item) blobs = _BlobDict() class Model(object): def __init__(self, net, parameters, inputs, outputs, device_option=None): """Initializes a model. Inputs: net: a Caffe2 NetDef protocol buffer. parameters: a TensorProtos object containing the parameters to feed into the network. inputs: a list of strings specifying the input blob names. outputs: a list of strings specifying the output blob names. device_option (optional): the device option used to run the model. If not given, we will use the net's device option. """ self._name = net.name self._inputs = inputs self._outputs = outputs if device_option: self._device_option = device_option.SerializeToString() else: self._device_option = net.device_option.SerializeToString() # For a caffe2 net, before we create it, it needs to have all the # parameter blobs ready. The construction is in two steps: feed in all # the parameters first, and then create the network object. for param in parameters.protos: print('Feeding parameter {}'.format(param.name)) FeedBlob(param.name, param, net.device_option) if not CreateNet(net, inputs): raise RuntimeError("Error when creating the model.") def Run(self, input_arrs): """Runs the model with the given input. Inputs: input_arrs: an iterable of input arrays. Outputs: output_arrs: a list of output arrays. """ if len(input_arrs) != len(self._inputs): raise RuntimeError("Incorrect number of inputs.") for i, input_arr in enumerate(input_arrs): FeedBlob(self._inputs[i], input_arr, self._device_option) if not RunNet(self._name): raise RuntimeError("Error in running the network.") return [FetchBlob(s) for s in self._outputs] ################################################################################ # Utilities for immediate mode # # Caffe2's immediate mode implements the following behavior: between the two # function calls StartImmediate() and StopImmediate(), for any operator that is # called through CreateOperator(), we will also run that operator in a workspace # that is specific to the immediate mode. The user is explicitly expected to # make sure that these ops have proper inputs and outputs, i.e. one should not # run an op where an external input is not created or fed. # # Users can use FeedImmediate() and FetchImmediate() to interact with blobs # in the immediate workspace. # # Once StopImmediate() is called, all contents in the immediate workspace is # freed up so one can continue using normal runs. # # The immediate mode is solely for debugging purposes and support will be very # sparse. ################################################################################ _immediate_mode = False _immediate_workspace_name = "_CAFFE2_IMMEDIATE" _immediate_root_folder = '' def IsImmediate(): return _immediate_mode @contextlib.contextmanager def WorkspaceGuard(workspace_name): current = CurrentWorkspace() SwitchWorkspace(workspace_name, True) yield SwitchWorkspace(current) def StartImmediate(i_know=False): global _immediate_mode global _immediate_root_folder if IsImmediate(): # already in immediate mode. We will kill the previous one # and start from fresh. StopImmediate() _immediate_mode = True with WorkspaceGuard(_immediate_workspace_name): _immediate_root_folder = tempfile.mkdtemp() ResetWorkspace(_immediate_root_folder) if i_know: # if the user doesn't want to see the warning message, sure... return print(""" Enabling immediate mode in caffe2 python is an EXTREMELY EXPERIMENTAL feature and may very easily go wrong. This is because Caffe2 uses a declarative way of defining operators and models, which is essentially not meant to run things in an interactive way. Read the following carefully to make sure that you understand the caveats. (1) You need to make sure that the sequences of operators you create are actually runnable sequentially. For example, if you create an op that takes an input X, somewhere earlier you should have already created X. (2) Caffe2 immediate uses one single workspace, so if the set of operators you run are intended to be under different workspaces, they will not run. To create boundaries between such use cases, you can call FinishImmediate() and StartImmediate() manually to flush out everything no longer needed. (3) Underlying objects held by the immediate mode may interfere with your normal run. For example, if there is a leveldb that you opened in immediate mode and did not close, your main run will fail because leveldb does not support double opening. Immediate mode may also occupy a lot of memory esp. on GPUs. Call FinishImmediate() as soon as possible when you no longer need it. (4) Immediate is designed to be slow. Every immediate call implicitly creates a temp operator object, runs it, and destroys the operator. This slow-speed run is by design to discourage abuse. For most use cases other than debugging, do NOT turn on immediate mode. (5) If there is anything FATAL happening in the underlying C++ code, the immediate mode will immediately (pun intended) cause the runtime to crash. Thus you should use immediate mode with extra care. If you still would like to, have fun [https://xkcd.com/149/]. """) def StopImmediate(): """Stops an immediate mode run.""" # Phew, that was a dangerous ride. global _immediate_mode global _immediate_root_folder if not IsImmediate(): return with WorkspaceGuard(_immediate_workspace_name): ResetWorkspace() shutil.rmtree(_immediate_root_folder) _immediate_root_folder = '' _immediate_mode = False def ImmediateBlobs(): with WorkspaceGuard(_immediate_workspace_name): return Blobs() def RunOperatorImmediate(op): with WorkspaceGuard(_immediate_workspace_name): RunOperatorOnce(op) def FetchImmediate(*args, **kwargs): with WorkspaceGuard(_immediate_workspace_name): return FetchBlob(*args, **kwargs) def FeedImmediate(*args, **kwargs): with WorkspaceGuard(_immediate_workspace_name): return FeedBlob(*args, **kwargs) # CWorkspace utilities def _Workspace_create_net(ws, net): return ws._create_net(StringfyProto(net)) C.Workspace.create_net = _Workspace_create_net def _Workspace_run(ws, obj): if hasattr(obj, 'Proto'): obj = obj.Proto() if isinstance(obj, caffe2_pb2.PlanDef): return ws._run_plan(obj.SerializeToString()) if isinstance(obj, caffe2_pb2.NetDef): return ws._run_net(obj.SerializeToString()) if isinstance(obj, caffe2_pb2.OperatorDef): return ws._run_operator(obj.SerializeToString()) raise ValueError( "Don't know how to do Workspace.run() on {}".format(type(obj))) C.Workspace.run = _Workspace_run def _Blob_feed(blob, arg, device_option=None): if device_option is not None: device_option = StringfyProto(device_option) return blob._feed(arg, device_option) C.Blob.feed = _Blob_feed
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/sequence_ops_test.py
292
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np from functools import partial def _gen_test_add_padding(with_pad_data=True, is_remove=False): def gen_with_size(args): lengths, inner_shape = args data_dim = [sum(lengths)] + inner_shape lengths = np.array(lengths, dtype=np.int32) if with_pad_data: return st.tuples( st.just(lengths), hu.arrays(data_dim), hu.arrays(inner_shape), hu.arrays(inner_shape)) else: return st.tuples(st.just(lengths), hu.arrays(data_dim)) min_len = 4 if is_remove else 0 lengths = st.lists( st.integers(min_value=min_len, max_value=10), min_size=0, max_size=5) inner_shape = st.lists( st.integers(min_value=1, max_value=3), min_size=0, max_size=2) return st.tuples(lengths, inner_shape).flatmap(gen_with_size) def _add_padding_ref( start_pad_width, end_pad_width, data, lengths, start_padding=None, end_padding=None): if start_padding is None: start_padding = np.zeros(data.shape[1:], dtype=data.dtype) end_padding = ( end_padding if end_padding is not None else start_padding) out_size = data.shape[0] + ( start_pad_width + end_pad_width) * len(lengths) out = np.ndarray((out_size,) + data.shape[1:]) in_ptr = 0 out_ptr = 0 for length in lengths: out[out_ptr:(out_ptr + start_pad_width)] = start_padding out_ptr += start_pad_width out[out_ptr:(out_ptr + length)] = data[in_ptr:(in_ptr + length)] in_ptr += length out_ptr += length out[out_ptr:(out_ptr + end_pad_width)] = end_padding out_ptr += end_pad_width lengths_out = lengths + (start_pad_width + end_pad_width) return (out, lengths_out) def _remove_padding_ref(start_pad_width, end_pad_width, data, lengths): pad_width = start_pad_width + end_pad_width out_size = data.shape[0] - ( start_pad_width + end_pad_width) * len(lengths) out = np.ndarray((out_size,) + data.shape[1:]) in_ptr = 0 out_ptr = 0 for length in lengths: out_length = length - pad_width out[out_ptr:(out_ptr + out_length)] = data[ (in_ptr + start_pad_width):(in_ptr + length - end_pad_width)] in_ptr += length out_ptr += out_length lengths_out = lengths - (start_pad_width + end_pad_width) return (out, lengths_out) def _gather_padding_ref(start_pad_width, end_pad_width, data, lengths): start_padding = np.zeros(data.shape[1:], dtype=data.dtype) end_padding = np.zeros(data.shape[1:], dtype=data.dtype) pad_width = start_pad_width + end_pad_width ptr = 0 for length in lengths: for i in range(start_pad_width): start_padding += data[ptr] ptr += 1 ptr += length - pad_width for i in range(end_pad_width): end_padding += data[ptr] ptr += 1 return (start_padding, end_padding) class TestSequenceOps(hu.HypothesisTestCase): @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), args=_gen_test_add_padding(with_pad_data=True)) def test_add_padding(self, start_pad_width, end_pad_width, args): lengths, data, start_padding, end_padding = args start_padding = np.array(start_padding, dtype=np.float32) end_padding = np.array(end_padding, dtype=np.float32) op = core.CreateOperator( 'AddPadding', ['data', 'lengths', 'start_padding', 'end_padding'], ['output', 'lengths_out'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( hu.cpu_do, op, [data, lengths, start_padding, end_padding], partial(_add_padding_ref, start_pad_width, end_pad_width)) @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), args=_gen_test_add_padding(with_pad_data=False)) def test_add_zero_padding(self, start_pad_width, end_pad_width, args): lengths, data = args op = core.CreateOperator( 'AddPadding', ['data', 'lengths'], ['output', 'lengths_out'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( hu.cpu_do, op, [data, lengths], partial(_add_padding_ref, start_pad_width, end_pad_width)) @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), data=hu.tensor(min_dim=1, max_dim=3)) def test_add_padding_no_length(self, start_pad_width, end_pad_width, data): op = core.CreateOperator( 'AddPadding', ['data'], ['output', 'output_lens'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( hu.cpu_do, op, [data], partial( _add_padding_ref, start_pad_width, end_pad_width, lengths=np.array([data.shape[0]]))) @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), args=_gen_test_add_padding(with_pad_data=False, is_remove=True)) def test_remove_padding(self, start_pad_width, end_pad_width, args): lengths, data = args op = core.CreateOperator( 'RemovePadding', ['data', 'lengths'], ['output', 'lengths_out'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( hu.cpu_do, op, [data, lengths], partial(_remove_padding_ref, start_pad_width, end_pad_width)) @given(start_pad_width=st.integers(min_value=1, max_value=2), end_pad_width=st.integers(min_value=0, max_value=2), args=_gen_test_add_padding(with_pad_data=True)) def test_gather_padding(self, start_pad_width, end_pad_width, args): lengths, data, start_padding, end_padding = args padded_data, padded_lengths = _add_padding_ref( start_pad_width, end_pad_width, data, lengths, start_padding, end_padding) op = core.CreateOperator( 'GatherPadding', ['data', 'lengths'], ['start_padding', 'end_padding'], padding_width=start_pad_width, end_padding_width=end_pad_width) self.assertReferenceChecks( hu.cpu_do, op, [padded_data, padded_lengths], partial(_gather_padding_ref, start_pad_width, end_pad_width)) @given(data=hu.tensor(min_dim=3, max_dim=3, dtype=np.float32, elements=st.floats(min_value=-np.inf, max_value=np.inf), min_value=1, max_value=10), **hu.gcs_cpu_only) def test_reverse_packed_segs(self, data, gc, dc): max_length = data.shape[0] batch_size = data.shape[1] lengths = np.random.randint(max_length + 1, size=batch_size) op = core.CreateOperator( "ReversePackedSegs", ["data", "lengths"], ["reversed_data"]) def op_ref(data, lengths): rev_data = np.array(data, copy=True) for i in range(batch_size): seg_length = lengths[i] for j in range(seg_length): rev_data[j][i] = data[seg_length - 1 - j][i] return (rev_data,) def op_grad_ref(grad_out, outputs, inputs): return op_ref(grad_out, inputs[1]) + (None,) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data, lengths], reference=op_ref, output_to_grad='reversed_data', grad_reference=op_grad_ref) @given(data=hu.tensor(min_dim=1, max_dim=3, dtype=np.float32, elements=st.floats(min_value=-np.inf, max_value=np.inf), min_value=10, max_value=10), indices=st.lists(st.integers(min_value=0, max_value=9), min_size=0, max_size=10), **hu.gcs_cpu_only) def test_remove_data_blocks(self, data, indices, gc, dc): indices = np.array(indices) op = core.CreateOperator( "RemoveDataBlocks", ["data", "indices"], ["shrunk_data"]) def op_ref(data, indices): unique_indices = np.unique(indices) sorted_indices = np.sort(unique_indices) shrunk_data = np.delete(data, sorted_indices, axis=0) return (shrunk_data,) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data, indices], reference=op_ref) @given(elements=st.lists(st.integers(min_value=0, max_value=9), min_size=0, max_size=10), **hu.gcs_cpu_only) def test_find_duplicate_elements(self, elements, gc, dc): mapping = { 0: "a", 1: "b", 2: "c", 3: "d", 4: "e", 5: "f", 6: "g", 7: "h", 8: "i", 9: "j"} data = np.array([mapping[e] for e in elements], dtype='|S') op = core.CreateOperator( "FindDuplicateElements", ["data"], ["indices"]) def op_ref(data): unique_data = [] indices = [] for i, e in enumerate(data): if e in unique_data: indices.append(i) else: unique_data.append(e) return (np.array(indices, dtype=np.int64),) self.assertReferenceChecks( device_option=gc, op=op, inputs=[data], reference=op_ref) if __name__ == "__main__": import unittest unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/conv_transpose_test.py
236
from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from hypothesis import assume, given, settings import hypothesis.strategies as st from caffe2.python import core import caffe2.python.hypothesis_test_util as hu class TestConvolutionTranspose(hu.HypothesisTestCase): @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), adj=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), engine=st.sampled_from(["", "CUDNN", "BLOCK"]), shared_buffer=st.booleans(), **hu.gcs) def test_convolution_transpose_layout(self, stride, pad, kernel, adj, size, input_channels, output_channels, batch_size, engine, shared_buffer, gc, dc): assume(adj < stride) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 outputs = {} for order in ["NCHW", "NHWC"]: op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"], ["Y"], stride=stride, kernel=kernel, pad=pad, adj=adj, order=order, engine=engine, shared_buffer=int(shared_buffer), device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs[order] = self.ws.blobs["Y"].fetch() output_size = (size - 1) * stride + kernel + adj - 2 * pad self.assertEqual( outputs["NCHW"].shape, (batch_size, output_channels, output_size, output_size)) np.testing.assert_allclose( outputs["NCHW"], outputs["NHWC"].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) # CUDNN does not support separate stride and pad so we skip it. @given(stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(1, 5), adj_h=st.integers(0, 2), adj_w=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), engine=st.sampled_from(["", "BLOCK"]), **hu.gcs) def test_convolution_transpose_separate_stride_pad_adj_layout( self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, adj_h, adj_w, size, input_channels, output_channels, batch_size, engine, gc, dc): assume(adj_h < stride_h) assume(adj_w < stride_w) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 outputs = {} for order in ["NCHW", "NHWC"]: op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"], ["Y"], stride_h=stride_h, stride_w=stride_w, kernel=kernel, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, adj_h=adj_h, adj_w=adj_w, order=order, engine=engine, device_option=gc, ) if order == "NCHW": X_f = X.transpose((0, 3, 1, 2)) w_f = w.transpose((0, 3, 1, 2)) else: X_f = X w_f = w self.ws.create_blob("X").feed(X_f, device_option=gc) self.ws.create_blob("w").feed(w_f, device_option=gc) self.ws.create_blob("b").feed(b, device_option=gc) self.ws.run(op) outputs[order] = self.ws.blobs["Y"].fetch() output_h = (size - 1) * stride_h + kernel + adj_h - pad_t - pad_b output_w = (size - 1) * stride_w + kernel + adj_w - pad_l - pad_r self.assertEqual( outputs["NCHW"].shape, (batch_size, output_channels, output_h, output_w)) np.testing.assert_allclose( outputs["NCHW"], outputs["NHWC"].transpose((0, 3, 1, 2)), atol=1e-4, rtol=1e-4) @given(stride=st.integers(1, 3), pad=st.integers(0, 3), kernel=st.integers(1, 5), adj=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), engine=st.sampled_from(["", "CUDNN", "BLOCK"]), **hu.gcs) @settings(max_examples=2, timeout=100) def test_convolution_transpose_gradients(self, stride, pad, kernel, adj, size, input_channels, output_channels, batch_size, order, engine, gc, dc): assume(adj < stride) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"], ["Y"], stride=stride, kernel=kernel, pad=pad, adj=adj, order=order, engine=engine, ) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) self.assertDeviceChecks(dc, op, [X, w, b], [0]) for i in range(3): self.assertGradientChecks(gc, op, [X, w, b], i, [0]) # CUDNN does not support separate stride and pad so we skip it. @given(stride_h=st.integers(1, 3), stride_w=st.integers(1, 3), pad_t=st.integers(0, 3), pad_l=st.integers(0, 3), pad_b=st.integers(0, 3), pad_r=st.integers(0, 3), kernel=st.integers(1, 5), adj_h=st.integers(0, 2), adj_w=st.integers(0, 2), size=st.integers(7, 10), input_channels=st.integers(1, 8), output_channels=st.integers(1, 8), batch_size=st.integers(1, 3), order=st.sampled_from(["NCHW", "NHWC"]), engine=st.sampled_from(["", "BLOCK"]), **hu.gcs) @settings(max_examples=2, timeout=100) def test_convolution_transpose_separate_stride_pad_adj_gradient( self, stride_h, stride_w, pad_t, pad_l, pad_b, pad_r, kernel, adj_h, adj_w, size, input_channels, output_channels, batch_size, order, engine, gc, dc): assume(adj_h < stride_h) assume(adj_w < stride_w) X = np.random.rand( batch_size, size, size, input_channels).astype(np.float32) - 0.5 w = np.random.rand( input_channels, kernel, kernel, output_channels)\ .astype(np.float32) - 0.5 b = np.random.rand(output_channels).astype(np.float32) - 0.5 op = core.CreateOperator( "ConvTranspose", ["X", "w", "b"], ["Y"], stride_h=stride_h, stride_w=stride_w, kernel=kernel, pad_t=pad_t, pad_l=pad_l, pad_b=pad_b, pad_r=pad_r, adj_h=adj_h, adj_w=adj_w, order=order, engine=engine, ) if order == "NCHW": X = X.transpose((0, 3, 1, 2)) w = w.transpose((0, 3, 1, 2)) self.assertDeviceChecks(dc, op, [X, w, b], [0]) for i in range(3): self.assertGradientChecks(gc, op, [X, w, b], i, [0]) if __name__ == "__main__": import unittest unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/muji.py
202
"""muji.py does multi-gpu training for caffe2 with no need to change the c++ side code. Everything is defined on the computation graph level. Currently, here are the assumptions: we only support the following use cases: - 2 gpus, where peer access is enabled between them. - 4 gpus, where peer access are enabled between all of them. - 8 gpus, where peer access are enabled in two groups, between {1, 2, 3, 4} and {5, 6, 7, 8}. """ from caffe2.python import core from caffe2.proto import caffe2_pb2 def OnGPU(gpu_id): """A utility function that returns a device option protobuf of the specified gpu id. """ device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CUDA device_option.cuda_gpu_id = gpu_id return device_option def OnCPU(): device_option = caffe2_pb2.DeviceOption() device_option.device_type = caffe2_pb2.CPU return device_option def Allreduce(net, blobs, reduced_affix="_reduced", gpu_indices=None): """The general Allreduce interface that reroutes the function calls. """ if gpu_indices is None: gpu_indices = range(len(blobs)) if len(gpu_indices) != len(blobs): raise RuntimeError( "gpu_indices length and blobs length mismatch: %d vs %d" % (len(gpu_indices), len(blobs)) ) if len(blobs) == 2: return Allreduce2(net, blobs, reduced_affix, gpu_indices) elif len(blobs) == 4: return Allreduce4(net, blobs, reduced_affix, gpu_indices) elif len(blobs) == 8: return Allreduce8(net, blobs, reduced_affix, gpu_indices) else: return AllreduceFallback(net, blobs, reduced_affix, gpu_indices) def Allreduce2(net, blobs, reduced_affix, gpu_indices): """Allreduce for 2 gpus. Algorithm: 0r <- 0 + 1, 1r <- 0r, where r means "reduced" """ a, b = blobs gpu_a, gpu_b = gpu_indices a_reduced = net.Add([a, b], a + reduced_affix, device_option=OnGPU(gpu_a)) b_reduced = a_reduced.Copy( [], b + reduced_affix, device_option=OnGPU(gpu_b) ) return a_reduced, b_reduced def Allreduce4(net, blobs, reduced_affix, gpu_indices): """Allreduce for 4 gpus. Algorithm: 2 level reduction. 0r <- 0 + 1, 2r <- 2 + 3 0r <- 0r + 2r 2r <- 0r, 1r <- 0r, 3r <- 2r """ a, b, c, d = blobs gpu_a, gpu_b, gpu_c, gpu_d = gpu_indices # a_reduced <- a+b, c_reduced <- c + d a_reduced = net.Add( [a, b], str(a) + reduced_affix, device_option=OnGPU(gpu_a) ) c_reduced = net.Add( [c, d], str(c) + reduced_affix, device_option=OnGPU(gpu_c) ) # a_reduced <- a_reduced + c_reduced a_reduced = a_reduced.Add(c_reduced, a_reduced, device_option=OnGPU(gpu_a)) # broadcast a_reduced to c_reduced c_reduced = a_reduced.Copy([], c_reduced, device_option=OnGPU(gpu_c)) # broadcast to b and d b_reduced = a_reduced.Copy( [], str(b) + reduced_affix, device_option=OnGPU(gpu_b) ) d_reduced = c_reduced.Copy( [], str(d) + reduced_affix, device_option=OnGPU(gpu_d) ) return a_reduced, b_reduced, c_reduced, d_reduced def Allreduce8(net, blobs, reduced_affix, gpu_indices): """Allreduce for 8 gpus. Algorithm: 3 level reduction. 0r <- 0 + 1, 2r <- 2 + 3, 4r <- 4 + 5, 6r <- 6 + 7 0r <- 0r + 2r, 4r <- 4r + 6r 0r <- 0r + 4r 4r <- 0r 2r <- 0r, 6r <- 4r 1r <- 0r, 3r <- 2r, 5r <- 4r, 7r <- 6r """ reduced = [None] * 8 # Reduction level 1 for i in [0, 2, 4, 6]: reduced[i] = net.Add( [blobs[i], blobs[i + 1]], blobs[i] + reduced_affix, device_option=OnGPU(gpu_indices[i]) ) # Reduction level 2 for i in [0, 4]: reduced[i] = net.Add( [reduced[i], reduced[i + 2]], str(blobs[i]) + reduced_affix, device_option=OnGPU(gpu_indices[i]) ) # Reduction level 3: this involves a copy. reduced_4_copy = reduced[4].Copy( [], str(reduced[4]) + '_copy', device_option=OnGPU(gpu_indices[0]) ) reduced[0] = reduced[0].Add( reduced_4_copy, reduced[0], device_option=OnGPU(gpu_indices[0]) ) # Broadcast level 1 reduced[4] = reduced[0].Copy( [], reduced[4], device_option=OnGPU(gpu_indices[4]) ) # Broadcast level 2 for i in [2, 6]: reduced[i] = reduced[i - 2].Copy( [], reduced[i], device_option=OnGPU(gpu_indices[i]) ) # Broadcast level 3 for i in [1, 3, 5, 7]: reduced[i] = reduced[i - 1].Copy( [], blobs[i] + reduced_affix, device_option=OnGPU(gpu_indices[i]) ) return reduced def AllreduceFallback(net, blobs, reduced_affix, gpu_indices): """A fallback option for Allreduce with no assumption on p2p. Algorithm: a flat operation on gpu 0 0r <- 0 0r <- 0r + i for i in gpu_indices[1:] ir <- 0r for i in gpu_indices[1:] """ reduced = [None] * len(gpu_indices) # copy first reduced[0] = net.Copy( blobs[0], blobs[0] + reduced_affix, device_option=OnGPU(gpu_indices[0]) ) # do temp copy and add temp_name = reduced[0] + '_temp_copy' for i in range(1, len(gpu_indices)): temp = net.Copy( blobs[i], temp_name, device_option=OnGPU(gpu_indices[0]) ) reduced[0] = reduced[0].Add( temp, reduced[0], device_option=OnGPU(gpu_indices[0]) ) # Broadcast to everyone else for i in range(1, len(gpu_indices)): reduced[i] = net.Copy( reduced[0], blobs[i] + reduced_affix, device_option=OnGPU(gpu_indices[i]) ) return reduced
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/layer_model_helper.py
306
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, model_helper, schema from caffe2.python.layers import layers from functools import partial import logging import numpy as np logger = logging.getLogger(__name__) class LayerModelHelper(model_helper.ModelHelperBase): """ Model helper for building models on top of layers abstractions. Each layer is the abstraction that is higher level than Operator. Layer is responsible for ownership of it's own parameters and can easily be instantiated in multiple nets possible with different sets of ops. As an example: one can easily instantiate predict and train nets from the same set of layers, where predict net will have subset of the operators from train net. """ def __init__(self, name, input_feature_schema, trainer_extra_schema): super(LayerModelHelper, self).__init__(name=name) self._layer_names = set() self._layers = [] # optimizer bookkeeping self.param_to_optim = {} self._default_optimizer = None self._loss = None self._output_schema = None # Connect Schema to self.net. That particular instance of schmea will be # use for generation of the Layers accross the network and would be used # for connection with Readers. self._input_feature_schema = schema.NewRecord( self.net, input_feature_schema ) self._trainer_extra_schema = schema.NewRecord( self.net, trainer_extra_schema ) self._init_global_constants() self.param_init_net = self.create_init_net('param_init_net') def add_global_constant(self, name, array=None, dtype=None, initializer=None): # This is global namescope for constants. They will be created in all # init_nets and there should be very few of them. assert name not in self.global_constants self.global_constants[name] = core.BlobReference( self.net.NextName(name)) if array is not None: assert initializer is None,\ "Only one from array and initializer should be specified" if dtype is None: array = np.array(array) else: array = np.array(array, dtype=dtype) # TODO: make GivenTensor generic op_name = None if array.dtype == np.int32: op_name = 'GivenTensorIntFill' elif array.dtype == np.int64: op_name = 'GivenTensorInt64Fill' elif array.dtype == np.str: op_name = 'GivenTensorStringFill' else: op_name = 'GivenTensorFill' def initializer(blob_name): return core.CreateOperator(op_name, [], blob_name, shape=array.shape, values=array.flatten().tolist() ) else: assert initializer is not None self.global_constant_initializers.append( initializer(self.global_constants[name])) return self.global_constants[name] def _init_global_constants(self): self.global_constants = {} self.global_constant_initializers = [] self.add_global_constant('ONE', 1.0) self.add_global_constant('ZERO', 0.0) self.add_global_constant('ZERO_RANGE', [0, 0], dtype='int32') def _add_global_constants(self, init_net): for initializer_op in self.global_constant_initializers: init_net._net.op.extend([initializer_op]) def create_init_net(self, name): init_net = core.Net(name) self._add_global_constants(init_net) return init_net def next_layer_name(self, prefix): name = prefix + "_{}".format( len(filter(lambda x: x.startswith(prefix), self._layer_names))) self._layer_names.add(name) return name def add_layer(self, layer): self._layers.append(layer) for param in layer.get_parameters(): self.param_to_optim[str(param.parameter)] = param.optimizer # The primary value of adding everything to self.net - generation of the # operators right away, i.e. if error happens it'll be detected # immediately. Other then this - create_x_net should be called. layer.add_operators(self.net, self.param_init_net) return layer.get_output_schema() @property def default_optimizer(self): return self._default_optimizer @default_optimizer.setter def default_optimizer(self, optimizer): self._default_optimizer = optimizer @property def input_feature_schema(self): return self._input_feature_schema @property def trainer_extra_schema(self): return self._trainer_extra_schema @property def output_schema(self): assert self._output_schema is not None return self._output_schema @output_schema.setter def output_schema(self, schema): assert self._output_schema is None self._output_schema = schema @property def loss(self): assert self._loss is not None return self._loss @loss.setter def loss(self, loss): assert self._loss is None self._loss = loss def __getattr__(self, layer): if not layers.layer_exists(layer): raise ValueError( "Tring to create non-registered layer: {0}".format(layer)) def wrapper(*args, **kwargs): return self.add_layer( layers.create_layer(layer, self, *args, **kwargs)) return wrapper @property def layers(self): return self._layers # TODO(amalevich): Optimizer should not really in model. Move it out. # Copy over from another Helper def SgdOptim(self, base_lr=0.01, policy='fixed', **kwargs): return partial(self.Sgd, base_lr=base_lr, policy=policy, **kwargs) def AdagradOptim(self, alpha=0.01, epsilon=1e-4, **kwargs): return partial(self.Adagrad, alpha=alpha, epsilon=epsilon, **kwargs) def FtrlOptim(self, alpha=0.01, beta=1e-4, lambda1=0, lambda2=0, **kwargs): return partial(self.Ftrl, alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2, **kwargs) def _GetOne(self): return self.global_constants['ONE'] def Adagrad(self, net, param_init_net, param, grad, alpha, epsilon, sparse_dedup_aggregator=None, engine=''): if alpha <= 0: return param_square_sum = param_init_net.ConstantFill( [param], core.ScopedBlobReference(param + "_square_sum"), value=0.0 ) # Set learning rate to negative so that we can add the grad to param # directly later. lr = param_init_net.ConstantFill( [], core.ScopedBlobReference(param + "_lr"), value=-alpha) if isinstance(grad, core.GradientSlice): if sparse_dedup_aggregator: grad = net.DeduplicateGradientSlices( grad, aggregator=sparse_dedup_aggregator) net.SparseAdagrad( [param, param_square_sum, grad.indices, grad.values, lr], [param, param_square_sum], epsilon=epsilon, engine=engine ) else: net.Adagrad( [param, param_square_sum, grad, lr], [param, param_square_sum], epsilon=epsilon, engine=engine ) def Ftrl(self, net, param_init_net, param, grad, alpha, beta, lambda1, lambda2, sparse_dedup_aggregator=None, engine=''): if alpha <= 0: return nz = param_init_net.ConstantFill( [param], core.ScopedBlobReference(param + "_ftrl_nz"), extra_shape=[2], value=0.0 ) if isinstance(grad, core.GradientSlice): if sparse_dedup_aggregator: grad = net.DeduplicateGradientSlices( grad, aggregator=sparse_dedup_aggregator) net.SparseFtrl( [param, nz, grad.indices, grad.values], [param, nz], engine=engine, alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2 ) else: net.Ftrl( [param, nz, grad], [param, nz], engine=engine, alpha=alpha, beta=beta, lambda1=lambda1, lambda2=lambda2 ) def Sgd(self, net, param_init_net, param, grad, base_lr, policy, momentum=0.0, **kwargs): if (base_lr <= 0): return # Set learning rate to negative so that we can add the grad to param # directly later. # TODO(amalevich): Get rid of iter duplication if other parts are good # enough lr = net.LearningRate( [net.Iter([], 1)], core.ScopedBlobReference(param + "_lr"), base_lr=-base_lr, policy=policy, **kwargs ) if momentum > 0: momentum_data = param_init_net.ConstantFill( param, core.ScopedBlobReference(param + "_momentum"), value=0.) if isinstance(grad, core.GradientSlice): assert momentum == 0., "Doesn't support momentum for sparse" net.ScatterWeightedSum( [param, self._GetOne(), grad.indices, grad.values, lr], param ) else: if momentum > 0.: net.MomentumSGD( [grad, momentum_data, lr], [grad, momentum_data], momentum=momentum, nesterov=1) coeff = self._GetOne() else: coeff = lr net.WeightedSum( [param, self._GetOne(), grad, coeff], param )
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/operator_test/softmax_ops_test.py
369
from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals from caffe2.python import core, workspace from hypothesis import given import caffe2.python.hypothesis_test_util as hu import hypothesis.strategies as st import numpy as np import unittest class TestSoftmaxOps(hu.HypothesisTestCase): @given(n=st.integers(2, 10), D=st.integers(4, 16), **hu.gcs) def test_softmax(self, n, D, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Reference implementation of cross entropy with soft labels def label_softmax(X): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm return [probs] op = core.CreateOperator( "Softmax", ["X"], ["probs"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=label_softmax, ) self.assertGradientChecks( gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2) @given(axis=st.integers(min_value=1, max_value=4), **hu.gcs) def test_softmax_axis(self, axis, gc, dc): np.random.seed(1) X = np.random.randn(1, 2, 3, 2, 1).astype(np.float32) X = X + 1e-2 def prod(xs): p = 1 for x in xs: p *= x return p N = prod(list(X.shape)[:axis]) D = prod(list(X.shape)[axis:]) # Reference implementation of cross entropy with soft labels def label_softmax(X): X_ = X.reshape(N, D) probs = np.zeros((N, D)) rowmax = np.zeros(N) for i in range(N): rowmax[i] = max(X_[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X_[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm return [probs.reshape(*X.shape)] op = core.CreateOperator( "Softmax", ["X"], ["probs"], axis=axis, ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X], reference=label_softmax, ) self.assertGradientChecks( gc, op, [X], 0, [0], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(2, 10), D=st.integers(4, 16), **hu.gcs) def test_softmax_with_loss(self, n, D, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Initialize label label = (np.random.rand(n) * D).astype(np.int32) # Reference implementation of cross entropy with soft labels def label_softmax_crossent(X, label): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm label_xent = [-np.log(max(probs[i][label[i]], 1e-20)) for i in range(n)] avgloss = np.sum(label_xent) / float(n) return (probs, avgloss) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"], ["probs", "avgloss"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label], reference=label_softmax_crossent, ) self.assertGradientChecks( gc, op, [X, label], 0, [1], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(2, 10), D=st.integers(4, 16), **hu.gcs) def test_softmax_with_loss_weighted(self, n, D, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability X = np.random.rand(n, D).astype(np.float32) X = X + 1e-2 # Initialize label label = (np.random.rand(n) * D).astype(np.int32) # Init weights (weight by sample) weights = np.random.rand(n).astype(np.float32) # Reference implementation of cross entropy with soft labels def label_softmax_crossent_weighted(X, label, weights): probs = np.zeros((n, D)) rowmax = np.zeros(n) for i in range(n): rowmax[i] = max(X[i, ]) # We need to subtract the max to avoid numerical issues probs[i] = X[i] - rowmax[i] exps = np.exp(probs[i, ]) norm = sum(exps) probs[i, ] = exps / norm label_xent = [-weights[i] * np.log(max(probs[i][label[i]], 1e-20)) for i in range(n)] avgloss = np.sum(label_xent) / sum(weights) return (probs, avgloss) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label", "weights"], ["probs", "avgloss"] ) self.assertReferenceChecks( device_option=gc, op=op, inputs=[X, label, weights], reference=label_softmax_crossent_weighted, ) self.assertGradientChecks( gc, op, [X, label, weights], 0, [1], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(2, 5), D=st.integers(2, 4), weighted=st.booleans(), **hu.gcs) def test_spatial_softmax_with_loss(self, n, D, weighted, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability W = 18 H = 12 X = np.random.rand(n, D, H, W).astype(np.float32) X = X + 1e-2 weighted = True weights = None if weighted: weights = np.random.rand(n, H, W).astype(np.float32) # Initialize label. Some of the labels are (-1), i.e "DONT CARE" label = (np.random.rand(n, H, W) * (D + 1)).astype(np.int32) - 1 def label_softmax_crossent_spatial(X, label, weights=None): probs = np.zeros((n, D, H, W)) rowmax = np.zeros((n, H, W)) label_xent = np.zeros((n, H, W)) for i in range(n): for x in range(W): for y in range(H): rowmax[i, y, x] = max(X[i, :, y, x]) # We need to subtract the max to avoid numerical issues probs[i, :, y, x] = X[i, :, y, x] - rowmax[i, y, x] exps = np.exp(probs[i, :, y, x]) probs[i, :, y, x] = exps / sum(exps) label_xent[:, y, x] = \ [-np.log(max(probs[j, label[i, y, x], y, x], 1e-20)) for j in range(n)] total_xent = 0.0 total_weight = 0.0 for y in range(H): for x in range(W): for i in range(n): l = label[i, y, x] if (l != (-1)): w = 1.0 if weights is None else weights[i, y, x] total_xent += \ -np.log(max(probs[i, l, y, x], 1e-20)) * w total_weight += w print("Total weight {}".format(total_weight)) return (probs, total_xent / total_weight) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"] + ([] if weights is None else ["weights"]), ["probs", "avgloss"], spatial=1 ) inputs = [X, label] + ([] if weights is None else [weights]) self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=label_softmax_crossent_spatial, ) self.assertGradientChecks( gc, op, inputs, 0, [1], stepsize=1e-4, threshold=1e-2) @given(n=st.integers(4, 5), D=st.integers(3, 4), weighted=st.booleans(), **hu.gcs) def test_spatial_softmax_with_loss_allignore(self, n, D, weighted, gc, dc): # n = number of examples, D = |labels| # Initialize X and add 1e-2 for numerical stability W = 18 H = 12 X = np.random.rand(n, D, H, W).astype(np.float32) X = X + 1e-2 weighted = True weights = None if weighted: weights = np.random.rand(n, H, W).astype(np.float32) # Initialize label. All labels as "DONT CARE" label = np.zeros((n, H, W)).astype(np.int32) - 1 print(label) def label_softmax_crossent_spatial(X, label, weights=None): probs = np.zeros((n, D, H, W)) rowmax = np.zeros((n, H, W)) label_xent = np.zeros((n, H, W)) for i in range(n): for x in range(W): for y in range(H): rowmax[i, y, x] = max(X[i, :, y, x]) # We need to subtract the max to avoid numerical issues probs[i, :, y, x] = X[i, :, y, x] - rowmax[i, y, x] exps = np.exp(probs[i, :, y, x]) probs[i, :, y, x] = exps / sum(exps) label_xent[:, y, x] = \ [-np.log(max(probs[j, label[i, y, x], y, x], 1e-20)) for j in range(n)] return (probs, 0.0) op = core.CreateOperator( "SoftmaxWithLoss", ["X", "label"] + ([] if weights is None else ["weights"]), ["probs", "avgloss"], spatial=1 ) inputs = [X, label] + ([] if weights is None else [weights]) self.assertReferenceChecks( device_option=gc, op=op, inputs=inputs, reference=label_softmax_crossent_spatial, ) @unittest.skipIf(not workspace.has_gpu_support, "No gpu support") def test_compare_cpugpu(self): ''' Additional test that checks CPU and GPU returns same values with larger examples. This is mainly to test the more complex GPU implementation is correct. ''' from caffe2.proto import caffe2_pb2 for j in range(3): gpuop = core.CreateOperator( "SoftmaxWithLoss", ["X_gpu", "label_gpu"], ["probs_gpu", "avgloss_gpu"], spatial=1, device_option=core.DeviceOption(caffe2_pb2.CUDA, 0) ) cpuop = core.CreateOperator( "SoftmaxWithLoss", ["X_cpu", "label_cpu"], ["probs_cpu", "avgloss_cpu"], spatial=1, device_option=core.DeviceOption(caffe2_pb2.CPU) ) n = 8 D = 4 W = 64 + int(np.random.rand(1) * 1024) H = 64 + int(np.random.rand(1) * 1024) print("W: {} H: {}".format(W, H)) X = np.random.rand(n, D, H, W).astype(np.float32) X = X + 1e-2 # Initialize label. Some of the labels are (-1), i.e "DONT CARE" label = (np.random.rand(n, H, W) * (D + 1)).astype(np.int32) - 1 gpu0 = core.DeviceOption(caffe2_pb2.CUDA, 0) workspace.FeedBlob("X_cpu", X) workspace.FeedBlob("label_cpu", label) workspace.FeedBlob("X_gpu", X, device_option=gpu0) workspace.FeedBlob("label_gpu", label, device_option=gpu0) workspace.RunOperatorOnce(gpuop) workspace.RunOperatorOnce(cpuop) probs_gpu = workspace.FetchBlob("probs_gpu") probs_cpu = workspace.FetchBlob("probs_cpu") loss_gpu = workspace.FetchBlob("avgloss_gpu") loss_cpu = workspace.FetchBlob("avgloss_cpu") np.testing.assert_allclose(probs_gpu, probs_cpu, rtol=1e-4) np.testing.assert_allclose(loss_gpu, loss_cpu, rtol=1e-1) if __name__ == "__main__": import unittest unittest.main()
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
caffe2/python/models/resnet.py
296
from __future__ import absolute_import from __future__ import division from __future__ import print_function ''' Utility for creating ResNets See "Deep Residual Learning for Image Recognition" by He, Zhang et. al. 2015 ''' class ResNetBuilder(): ''' Helper class for constructing residual blocks. ''' def __init__(self, model, prev_blob, no_bias, is_test, spatial_bn_mom=0.9): self.model = model self.comp_count = 0 self.comp_idx = 0 self.prev_blob = prev_blob self.is_test = is_test self.spatial_bn_mom = spatial_bn_mom self.no_bias = 1 if no_bias else 0 def add_conv(self, in_filters, out_filters, kernel, stride=1, pad=0): self.comp_idx += 1 self.prev_blob = self.model.Conv( self.prev_blob, 'comp_%d_conv_%d' % (self.comp_count, self.comp_idx), in_filters, out_filters, weight_init=("MSRAFill", {}), kernel=kernel, stride=stride, pad=pad, no_bias=self.no_bias, ) return self.prev_blob def add_relu(self): self.prev_blob = self.model.Relu( self.prev_blob, self.prev_blob, # in-place ) return self.prev_blob def add_spatial_bn(self, num_filters): self.prev_blob = self.model.SpatialBN( self.prev_blob, 'comp_%d_spatbn_%d' % (self.comp_count, self.comp_idx), num_filters, epsilon=1e-3, momentum=self.spatial_bn_mom, is_test=self.is_test, ) return self.prev_blob ''' Add a "bottleneck" component as decribed in He et. al. Figure 3 (right) ''' def add_bottleneck( self, input_filters, # num of feature maps from preceding layer base_filters, # num of filters internally in the component output_filters, # num of feature maps to output down_sampling=False, spatial_batch_norm=True, ): self.comp_idx = 0 shortcut_blob = self.prev_blob # 1x1 self.add_conv( input_filters, base_filters, kernel=1, stride=1 ) if spatial_batch_norm: self.add_spatial_bn(base_filters) self.add_relu() # 3x3 (note the pad, required for keeping dimensions) self.add_conv( base_filters, base_filters, kernel=3, stride=(1 if down_sampling is False else 2), pad=1 ) if spatial_batch_norm: self.add_spatial_bn(base_filters) self.add_relu() # 1x1 last_conv = self.add_conv(base_filters, output_filters, kernel=1) if spatial_batch_norm: last_conv = self.add_spatial_bn(output_filters) # Summation with input signal (shortcut) # If we need to increase dimensions (feature maps), need to # do do a projection for the short cut if (output_filters > input_filters): shortcut_blob = self.model.Conv( shortcut_blob, 'shortcut_projection_%d' % self.comp_count, input_filters, output_filters, weight_init=("MSRAFill", {}), kernel=1, stride=(1 if down_sampling is False else 2), no_bias=self.no_bias, ) if spatial_batch_norm: shortcut_blob = self.model.SpatialBN( shortcut_blob, 'shortcut_projection_%d_spatbn' % self.comp_count, output_filters, epsilon=1e-3, momentum=self.spatial_bn_mom, is_test=self.is_test, ) self.prev_blob = self.model.Sum( [shortcut_blob, last_conv], 'comp_%d_sum_%d' % (self.comp_count, self.comp_idx) ) self.comp_idx += 1 self.add_relu() # Keep track of number of high level components if this ResNetBuilder self.comp_count += 1 def add_simple_block( self, input_filters, num_filters, down_sampling=False, spatial_batch_norm=True ): self.comp_idx = 0 shortcut_blob = self.prev_blob # 3x3 self.add_conv( input_filters, num_filters, kernel=3, stride=(1 if down_sampling is False else 2), pad=1 ) if spatial_batch_norm: self.add_spatial_bn(num_filters) self.add_relu() last_conv = self.add_conv(num_filters, num_filters, kernel=3, pad=1) if spatial_batch_norm: last_conv = self.add_spatial_bn(num_filters) # Increase of dimensions, need a projection for the shortcut if (num_filters != input_filters): shortcut_blob = self.model.Conv( shortcut_blob, 'shortcut_projection_%d' % self.comp_count, input_filters, num_filters, weight_init=("MSRAFill", {}), kernel=1, stride=(1 if down_sampling is False else 2), no_bias=self.no_bias, ) if spatial_batch_norm: shortcut_blob = self.model.SpatialBN( shortcut_blob, 'shortcut_projection_%d_spatbn' % self.comp_count, num_filters, epsilon=1e-3, is_test=self.is_test, ) self.prev_blob = self.model.Sum( [shortcut_blob, last_conv], 'comp_%d_sum_%d' % (self.comp_count, self.comp_idx) ) self.comp_idx += 1 self.add_relu() # Keep track of number of high level components if this ResNetBuilder self.comp_count += 1 def create_resnet50( model, data, num_input_channels, num_labels, label=None, is_test=False, no_loss=False, no_bias=0, ): # conv1 + maxpool model.Conv(data, 'conv1', num_input_channels, 64, weight_init=("MSRAFill", {}), kernel=7, stride=2, pad=3, no_bias=no_bias) model.SpatialBN('conv1', 'conv1_spatbn_relu', 64, epsilon=1e-3, momentum=0.1, is_test=is_test) model.Relu('conv1_spatbn_relu', 'conv1_spatbn_relu') model.MaxPool('conv1_spatbn_relu', 'pool1', kernel=3, stride=2) # Residual blocks... builder = ResNetBuilder(model, 'pool1', no_bias=no_bias, is_test=is_test, spatial_bn_mom=0.1) # conv2_x (ref Table 1 in He et al. (2015)) builder.add_bottleneck(64, 64, 256) builder.add_bottleneck(256, 64, 256) builder.add_bottleneck(256, 64, 256) # conv3_x builder.add_bottleneck(256, 128, 512, down_sampling=True) for i in range(1, 4): builder.add_bottleneck(512, 128, 512) # conv4_x builder.add_bottleneck(512, 256, 1024, down_sampling=True) for i in range(1, 6): builder.add_bottleneck(1024, 256, 1024) # conv5_x builder.add_bottleneck(1024, 512, 2048, down_sampling=True) builder.add_bottleneck(2048, 512, 2048) builder.add_bottleneck(2048, 512, 2048) # Final layers final_avg = model.AveragePool( builder.prev_blob, 'final_avg', kernel=7, stride=1, ) # Final dimension of the "image" is reduced to 7x7 last_out = model.FC(final_avg, 'last_out_L{}'.format(num_labels), 2048, num_labels) if no_loss: return last_out # If we create model for training, use softmax-with-loss if (label is not None): (softmax, loss) = model.SoftmaxWithLoss( [last_out, label], ["softmax", "loss"], ) return (softmax, loss) else: # For inference, we just return softmax return model.Softmax(last_out, "softmax") def create_resnet_32x32( model, data, num_input_channels, num_groups, num_labels, is_test=False ): ''' Create residual net for smaller images (sec 4.2 of He et. al (2015)) num_groups = 'n' in the paper ''' # conv1 + maxpool model.Conv(data, 'conv1', num_input_channels, 16, kernel=3, stride=1) model.SpatialBN('conv1', 'conv1_spatbn', 16, epsilon=1e-3, is_test=is_test) model.Relu('conv1_spatbn', 'relu1') # Number of blocks as described in sec 4.2 filters = [16, 32, 64] builder = ResNetBuilder(model, 'relu1', is_test=is_test) prev_filters = 16 for groupidx in range(0, 3): for blockidx in range(0, 2 * num_groups): builder.add_simple_block( prev_filters if blockidx == 0 else filters[groupidx], filters[groupidx], down_sampling=(True if blockidx == 0 and groupidx > 0 else False)) prev_filters = filters[groupidx] # Final layers model.AveragePool(builder.prev_blob, 'final_avg', kernel=8, stride=1) model.FC('final_avg', 'last_out', 64, num_labels) softmax = model.Softmax('last_out', 'softmax') return softmax
pytorch_pytorch
2017-01-28
14a5b3580555f7aabae4524556962db5e831e333
src/app/app.cpp
457
// Aseprite // Copyright (C) 2001-2016 David Capello // // This program is distributed under the terms of // the End-User License Agreement for Aseprite. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "app/app.h" #include "app/app_options.h" #include "app/check_update.h" #include "app/color_utils.h" #include "app/commands/cmd_save_file.h" #include "app/commands/cmd_sprite_size.h" #include "app/commands/commands.h" #include "app/commands/params.h" #include "app/console.h" #include "app/crash/data_recovery.h" #include "app/document_exporter.h" #include "app/document_undo.h" #include "app/file/file.h" #include "app/file/file_formats_manager.h" #include "app/file_system.h" #include "app/filename_formatter.h" #include "app/gui_xml.h" #include "app/ini_file.h" #include "app/log.h" #include "app/modules.h" #include "app/modules/gfx.h" #include "app/modules/gui.h" #include "app/modules/palettes.h" #include "app/pref/preferences.h" #include "app/recent_files.h" #include "app/resource_finder.h" #include "app/send_crash.h" #include "app/tools/active_tool.h" #include "app/tools/tool_box.h" #include "app/ui/backup_indicator.h" #include "app/ui/color_bar.h" #include "app/ui/document_view.h" #include "app/ui/editor/editor.h" #include "app/ui/editor/editor_view.h" #include "app/ui/input_chain.h" #include "app/ui/keyboard_shortcuts.h" #include "app/ui/main_window.h" #include "app/ui/status_bar.h" #include "app/ui/toolbar.h" #include "app/ui/workspace.h" #include "app/ui_context.h" #include "app/util/clipboard.h" #include "app/webserver.h" #include "base/convert_to.h" #include "base/exception.h" #include "base/fs.h" #include "base/scoped_lock.h" #include "base/split_string.h" #include "base/unique_ptr.h" #include "doc/document_observer.h" #include "doc/frame_tag.h" #include "doc/image.h" #include "doc/layer.h" #include "doc/layers_range.h" #include "doc/palette.h" #include "doc/site.h" #include "doc/sprite.h" #include "render/render.h" #include "she/display.h" #include "she/error.h" #include "she/system.h" #include "ui/intern.h" #include "ui/ui.h" #include <iostream> #ifdef ENABLE_SCRIPTING #include "app/script/app_scripting.h" #include "app/shell.h" #include "script/engine_delegate.h" #endif #ifdef ENABLE_STEAM #include "steam/steam.h" #endif namespace app { using namespace ui; class App::CoreModules { public: ConfigModule m_configModule; Preferences m_preferences; }; class App::Modules { public: LoggerModule m_loggerModule; FileSystemModule m_file_system_module; tools::ToolBox m_toolbox; tools::ActiveToolManager m_activeToolManager; CommandsModule m_commands_modules; UIContext m_ui_context; RecentFiles m_recent_files; InputChain m_inputChain; clipboard::ClipboardManager m_clipboardManager; // This is a raw pointer because we want to delete this explicitly. app::crash::DataRecovery* m_recovery; Modules(bool createLogInDesktop) : m_loggerModule(createLogInDesktop) , m_activeToolManager(&m_toolbox) , m_recovery(nullptr) { } app::crash::DataRecovery* recovery() { return m_recovery; } bool hasRecoverySessions() const { return m_recovery && !m_recovery->sessions().empty(); } void createDataRecovery() { #ifdef ENABLE_DATA_RECOVERY m_recovery = new app::crash::DataRecovery(&m_ui_context); #endif } void deleteDataRecovery() { #ifdef ENABLE_DATA_RECOVERY delete m_recovery; m_recovery = nullptr; #endif } }; #ifdef ENABLE_SCRIPTING class StdoutEngineDelegate : public script::EngineDelegate { public: void onConsolePrint(const char* text) override { printf("%s\n", text); } }; #endif App* App::m_instance = NULL; App::App() : m_coreModules(NULL) , m_modules(NULL) , m_legacy(NULL) , m_isGui(false) , m_isShell(false) , m_exporter(NULL) , m_backupIndicator(nullptr) { ASSERT(m_instance == NULL); m_instance = this; } void App::initialize(const AppOptions& options) { m_isGui = options.startUI(); m_isShell = options.startShell(); if (m_isGui) m_uiSystem.reset(new ui::UISystem); m_coreModules = new CoreModules; bool createLogInDesktop = false; switch (options.verboseLevel()) { case AppOptions::kNoVerbose: base::set_log_level(ERROR); break; case AppOptions::kVerbose: base::set_log_level(INFO); break; case AppOptions::kHighlyVerbose: base::set_log_level(VERBOSE); createLogInDesktop = true; break; } m_modules = new Modules(createLogInDesktop); m_legacy = new LegacyModules(isGui() ? REQUIRE_INTERFACE: 0); m_brushes.reset(new AppBrushes); if (options.hasExporterParams()) m_exporter.reset(new DocumentExporter); // Data recovery is enabled only in GUI mode if (isGui() && preferences().general.dataRecovery()) m_modules->createDataRecovery(); // Register well-known image file types. FileFormatsManager::instance()->registerAllFormats(); if (isPortable()) LOG("APP: Running in portable mode\n"); // Load or create the default palette, or migrate the default // palette from an old format palette to the new one, etc. load_default_palette(options.paletteFileName()); // Initialize GUI interface UIContext* ctx = UIContext::instance(); if (isGui()) { LOG("APP: GUI mode\n"); // Setup the GUI cursor and redraw screen ui::set_use_native_cursors(preferences().cursor.useNativeCursor()); ui::set_mouse_cursor_scale(preferences().cursor.cursorScale()); ui::set_mouse_cursor(kArrowCursor); ui::Manager::getDefault()->invalidate(); // Create the main window and show it. m_mainWindow.reset(new MainWindow); // Default status of the main window. app_rebuild_documents_tabs(); app_default_statusbar_message(); // Recover data if (m_modules->hasRecoverySessions()) m_mainWindow->showDataRecovery(m_modules->recovery()); m_mainWindow->openWindow(); // Redraw the whole screen. ui::Manager::getDefault()->invalidate(); } // Procress options LOG("APP: Processing options...\n"); bool ignoreEmpty = false; bool trim = false; Params cropParams; SpriteSheetType sheetType = SpriteSheetType::None; // Open file specified in the command line if (!options.values().empty()) { Console console; bool splitLayers = false; bool splitLayersSaveAs = false; bool allLayers = false; bool listLayers = false; bool listTags = false; std::string importLayer; std::string importLayerSaveAs; std::string filenameFormat; std::string frameTagName; std::string frameRange; for (const auto& value : options.values()) { const AppOptions::Option* opt = value.option(); // Special options/commands if (opt) { // --data <file.json> if (opt == &options.data()) { if (m_exporter) m_exporter->setDataFilename(value.value()); } // --format <format> else if (opt == &options.format()) { if (m_exporter) { DocumentExporter::DataFormat format = DocumentExporter::DefaultDataFormat; if (value.value() == "json-hash") format = DocumentExporter::JsonHashDataFormat; else if (value.value() == "json-array") format = DocumentExporter::JsonArrayDataFormat; m_exporter->setDataFormat(format); } } // --sheet <file.png> else if (opt == &options.sheet()) { if (m_exporter) m_exporter->setTextureFilename(value.value()); } // --sheet-width <width> else if (opt == &options.sheetWidth()) { if (m_exporter) m_exporter->setTextureWidth(strtol(value.value().c_str(), NULL, 0)); } // --sheet-height <height> else if (opt == &options.sheetHeight()) { if (m_exporter) m_exporter->setTextureHeight(strtol(value.value().c_str(), NULL, 0)); } // --sheet-pack else if (opt == &options.sheetType()) { if (value.value() == "horizontal") sheetType = SpriteSheetType::Horizontal; else if (value.value() == "vertical") sheetType = SpriteSheetType::Vertical; else if (value.value() == "rows") sheetType = SpriteSheetType::Rows; else if (value.value() == "columns") sheetType = SpriteSheetType::Columns; else if (value.value() == "packed") sheetType = SpriteSheetType::Packed; } // --sheet-pack else if (opt == &options.sheetPack()) { sheetType = SpriteSheetType::Packed; } // --split-layers else if (opt == &options.splitLayers()) { splitLayers = true; splitLayersSaveAs = true; } // --layer <layer-name> else if (opt == &options.layer()) { importLayer = value.value(); importLayerSaveAs = value.value(); } // --all-layers else if (opt == &options.allLayers()) { allLayers = true; } // --frame-tag <tag-name> else if (opt == &options.frameTag()) { frameTagName = value.value(); } // --frame-range from,to else if (opt == &options.frameRange()) { frameRange = value.value(); } // --ignore-empty else if (opt == &options.ignoreEmpty()) { ignoreEmpty = true; } // --border-padding else if (opt == &options.borderPadding()) { if (m_exporter) m_exporter->setBorderPadding(strtol(value.value().c_str(), NULL, 0)); } // --shape-padding else if (opt == &options.shapePadding()) { if (m_exporter) m_exporter->setShapePadding(strtol(value.value().c_str(), NULL, 0)); } // --inner-padding else if (opt == &options.innerPadding()) { if (m_exporter) m_exporter->setInnerPadding(strtol(value.value().c_str(), NULL, 0)); } // --trim else if (opt == &options.trim()) { trim = true; } // --crop x,y,width,height else if (opt == &options.crop()) { std::vector<std::string> parts; base::split_string(value.value(), parts, ","); if (parts.size() < 4) throw std::runtime_error("--crop needs four parameters separated by comma (,)\n" "Usage: --crop x,y,width,height\n" "E.g. --crop 0,0,32,32"); cropParams.set("x", parts[0].c_str()); cropParams.set("y", parts[1].c_str()); cropParams.set("width", parts[2].c_str()); cropParams.set("height", parts[3].c_str()); } // --filename-format else if (opt == &options.filenameFormat()) { filenameFormat = value.value(); } // --save-as <filename> else if (opt == &options.saveAs()) { Document* doc = NULL; if (!ctx->documents().empty()) doc = dynamic_cast<Document*>(ctx->documents().lastAdded()); if (!doc) { console.printf("A document is needed before --save-as argument\n"); } else { ctx->setActiveDocument(doc); std::string format = filenameFormat; Command* saveAsCommand = CommandsModule::instance()->getCommandByName(CommandId::SaveFileCopyAs); Command* trimCommand = CommandsModule::instance()->getCommandByName(CommandId::AutocropSprite); Command* cropCommand = CommandsModule::instance()->getCommandByName(CommandId::CropSprite); Command* undoCommand = CommandsModule::instance()->getCommandByName(CommandId::Undo); // --save-as with --split-layers if (splitLayersSaveAs) { std::string fn, fmt; if (format.empty()) { if (doc->sprite()->totalFrames() > frame_t(1)) format = "{path}/{title} ({layer}) {frame}.{extension}"; else format = "{path}/{title} ({layer}).{extension}"; } // Store in "visibility" the original "visible" state of every layer. std::vector<bool> visibility(doc->sprite()->countLayers()); int i = 0; for (Layer* layer : doc->sprite()->layers()) visibility[i++] = layer->isVisible(); // For each layer, hide other ones and save the sprite. i = 0; for (Layer* show : doc->sprite()->layers()) { // If the user doesn't want all layers and this one is hidden. if (!visibility[i++]) continue; // Just ignore this layer. // Make this layer ("show") the only one visible. for (Layer* hide : doc->sprite()->layers()) hide->setVisible(hide == show); FilenameInfo fnInfo; fnInfo .filename(value.value()) .layerName(show->name()); fn = filename_formatter(format, fnInfo); fmt = filename_formatter(format, fnInfo, false); if (!cropParams.empty()) ctx->executeCommand(cropCommand, cropParams); // TODO --trim command with --save-as doesn't make too // much sense as we lost the trim rectangle // information (e.g. we don't have sheet .json) Also, // we should trim each frame individually (a process // that can be done only in fop_operate()). if (trim) ctx->executeCommand(trimCommand); Params params; params.set("filename", fn.c_str()); params.set("filename-format", fmt.c_str()); ctx->executeCommand(saveAsCommand, params); if (trim) { // Undo trim command ctx->executeCommand(undoCommand); // Just in case allow non-linear history is enabled // we clear redo information doc->undoHistory()->clearRedo(); } } // Restore layer visibility i = 0; for (Layer* layer : doc->sprite()->layers()) layer->setVisible(visibility[i++]); } else { // Show only one layer if (!importLayerSaveAs.empty()) { for (Layer* layer : doc->sprite()->layers()) layer->setVisible(layer->name() == importLayerSaveAs); } if (!cropParams.empty()) ctx->executeCommand(cropCommand, cropParams); if (trim) ctx->executeCommand(trimCommand); Params params; params.set("filename", value.value().c_str()); params.set("filename-format", format.c_str()); ctx->executeCommand(saveAsCommand, params); if (trim) { // Undo trim command ctx->executeCommand(undoCommand); // Just in case allow non-linear history is enabled // we clear redo information doc->undoHistory()->clearRedo(); } } } } // --scale <factor> else if (opt == &options.scale()) { Command* command = CommandsModule::instance()->getCommandByName(CommandId::SpriteSize); double scale = strtod(value.value().c_str(), NULL); static_cast<SpriteSizeCommand*>(command)->setScale(scale, scale); // Scale all sprites for (auto doc : ctx->documents()) { ctx->setActiveDocument(static_cast<app::Document*>(doc)); ctx->executeCommand(command); } } // --shrink-to <width,height> else if (opt == &options.shrinkTo()) { std::vector<std::string> dimensions; base::split_string(value.value(), dimensions, ","); if (dimensions.size() < 2) throw std::runtime_error("--shrink-to needs two parameters separated by comma (,)\n" "Usage: --shrink-to width,height\n" "E.g. --shrink-to 128,64"); double maxWidth = base::convert_to<double>(dimensions[0]); double maxHeight = base::convert_to<double>(dimensions[1]); double scaleWidth, scaleHeight, scale; // Shrink all sprites if needed for (auto doc : ctx->documents()) { ctx->setActiveDocument(static_cast<app::Document*>(doc)); scaleWidth = (doc->width() > maxWidth ? maxWidth / doc->width() : 1.0); scaleHeight = (doc->height() > maxHeight ? maxHeight / doc->height() : 1.0); if (scaleWidth < 1.0 || scaleHeight < 1.0) { scale = MIN(scaleWidth, scaleHeight); Command* command = CommandsModule::instance()->getCommandByName(CommandId::SpriteSize); static_cast<SpriteSizeCommand*>(command)->setScale(scale, scale); ctx->executeCommand(command); } } } #ifdef ENABLE_SCRIPTING // --script <filename> else if (opt == &options.script()) { std::string script = value.value(); StdoutEngineDelegate delegate; AppScripting engine(&delegate); engine.evalFile(script); } #endif // --list-layers else if (opt == &options.listLayers()) { listLayers = true; if (m_exporter) m_exporter->setListLayers(true); } // --list-tags else if (opt == &options.listTags()) { listTags = true; if (m_exporter) m_exporter->setListFrameTags(true); } } // File names aren't associated to any option else { const std::string& filename = base::normalize_path(value.value()); app::Document* oldDoc = ctx->activeDocument(); Command* openCommand = CommandsModule::instance()->getCommandByName(CommandId::OpenFile); Params params; params.set("filename", filename.c_str()); ctx->executeCommand(openCommand, params); app::Document* doc = ctx->activeDocument(); // If the active document is equal to the previous one, it // means that we couldn't open this specific document. if (doc == oldDoc) doc = nullptr; // List layers and/or tags if (doc) { // Show all layers if (allLayers) { for (Layer* layer : doc->sprite()->layers()) layer->setVisible(true); } if (listLayers) { listLayers = false; for (Layer* layer : doc->sprite()->layers()) { if (layer->isVisible()) std::cout << layer->name() << "\n"; } } if (listTags) { listTags = false; for (FrameTag* tag : doc->sprite()->frameTags()) std::cout << tag->name() << "\n"; } if (m_exporter) { FrameTag* frameTag = nullptr; if (!frameTagName.empty()) { frameTag = doc->sprite()->frameTags().getByName(frameTagName); } else if (!frameRange.empty()) { std::vector<std::string> splitRange; base::split_string(frameRange, splitRange, ","); if (splitRange.size() < 2) throw std::runtime_error("--frame-range needs two parameters separated by comma (,)\n" "Usage: --frame-range from,to\n" "E.g. --frame-range 0,99"); frameTag = new FrameTag(base::convert_to<frame_t>(splitRange[0]), base::convert_to<frame_t>(splitRange[1])); } if (!importLayer.empty()) { Layer* foundLayer = NULL; for (Layer* layer : doc->sprite()->layers()) { if (layer->name() == importLayer) { foundLayer = layer; break; } } if (foundLayer) m_exporter->addDocument(doc, foundLayer, frameTag); } else if (splitLayers) { for (auto layer : doc->sprite()->layers()) { if (layer->isVisible()) m_exporter->addDocument(doc, layer, frameTag); } } else { m_exporter->addDocument(doc, nullptr, frameTag); } } } if (!importLayer.empty()) importLayer.clear(); if (splitLayers) splitLayers = false; if (listLayers) listLayers = false; if (listTags) listTags = false; } } if (m_exporter && !filenameFormat.empty()) m_exporter->setFilenameFormat(filenameFormat); } // Export if (m_exporter) { LOG("APP: Exporting sheet...\n"); if (sheetType != SpriteSheetType::None) m_exporter->setSpriteSheetType(sheetType); if (ignoreEmpty) m_exporter->setIgnoreEmptyCels(true); if (trim) m_exporter->setTrimCels(true); base::UniquePtr<Document> spriteSheet(m_exporter->exportSheet()); m_exporter.reset(NULL); LOG("APP: Export sprite sheet: Done\n"); } she::instance()->finishLaunching(); } void App::run() { // Run the GUI if (isGui()) { // Initialize Steam API #ifdef ENABLE_STEAM steam::SteamAPI steam; if (steam.initialized()) she::instance()->activateApp(); #endif #if _DEBUG // On OS X, when we compile Aseprite on Debug mode, we're using it // outside an app bundle, so we must active the app explicitly. she::instance()->activateApp(); #endif #ifdef ENABLE_UPDATER // Launch the thread to check for updates. app::CheckUpdateThreadLauncher checkUpdate( m_mainWindow->getCheckUpdateDelegate()); checkUpdate.launch(); #endif #ifdef ENABLE_WEBSERVER // Launch the webserver. app::WebServer webServer; webServer.start(); #endif app::SendCrash sendCrash; sendCrash.search(); // Run the GUI main message loop ui::Manager::getDefault()->run(); } #ifdef ENABLE_SCRIPTING // Start shell to execute scripts. if (m_isShell) { StdoutEngineDelegate delegate; AppScripting engine(&delegate); engine.printLastResult(); Shell shell; shell.run(engine); } #endif // Destroy all documents in the UIContext. const doc::Documents& docs = m_modules->m_ui_context.documents(); while (!docs.empty()) { doc::Document* doc = docs.back(); // First we close the document. In this way we receive recent // notifications related to the document as an app::Document. If // we delete the document directly, we destroy the app::Document // too early, and then doc::~Document() call // DocumentsObserver::onRemoveDocument(). In this way, observers // could think that they have a fully created app::Document when // in reality it's a doc::Document (in the middle of a // destruction process). // // TODO: This problem is because we're extending doc::Document, // in the future, we should remove app::Document. doc->close(); delete doc; } if (isGui()) { // Destroy the window. m_mainWindow.reset(NULL); } // Delete backups (this is a normal shutdown, we are not handling // exceptions, and we are not in a destructor). m_modules->deleteDataRecovery(); } // Finishes the Aseprite application. App::~App() { try { LOG("APP: Exit\n"); ASSERT(m_instance == this); // Delete file formats. FileFormatsManager::destroyInstance(); // Fire App Exit signal. App::instance()->Exit(); // Finalize modules, configuration and core. Editor::destroyEditorSharedInternals(); // Save brushes m_brushes.reset(nullptr); if (m_backupIndicator) { delete m_backupIndicator; m_backupIndicator = nullptr; } delete m_legacy; delete m_modules; delete m_coreModules; // Destroy the loaded gui.xml data. delete KeyboardShortcuts::instance(); delete GuiXml::instance(); m_instance = NULL; } catch (const std::exception& e) { LOG(ERROR) << "APP: Error: " << e.what() << "\n"; she::error_message(e.what()); // no re-throw } catch (...) { she::error_message("Error closing " PACKAGE ".\n(uncaught exception)"); // no re-throw } } bool App::isPortable() { static bool* is_portable = NULL; if (!is_portable) { is_portable = new bool( base::is_file(base::join_path( base::get_file_path(base::get_app_path()), "aseprite.ini"))); } return *is_portable; } tools::ToolBox* App::toolBox() const { ASSERT(m_modules != NULL); return &m_modules->m_toolbox; } tools::Tool* App::activeTool() const { return m_modules->m_activeToolManager.activeTool(); } tools::ActiveToolManager* App::activeToolManager() const { return &m_modules->m_activeToolManager; } RecentFiles* App::recentFiles() const { ASSERT(m_modules != NULL); return &m_modules->m_recent_files; } Workspace* App::workspace() const { if (m_mainWindow) return m_mainWindow->getWorkspace(); else return nullptr; } ContextBar* App::contextBar() const { if (m_mainWindow) return m_mainWindow->getContextBar(); else return nullptr; } Timeline* App::timeline() const { if (m_mainWindow) return m_mainWindow->getTimeline(); else return nullptr; } Preferences& App::preferences() const { return m_coreModules->m_preferences; } crash::DataRecovery* App::dataRecovery() const { return m_modules->recovery(); } void App::showNotification(INotificationDelegate* del) { m_mainWindow->showNotification(del); } void App::showBackupNotification(bool state) { base::scoped_lock lock(m_backupIndicatorMutex); if (state) { if (!m_backupIndicator) m_backupIndicator = new BackupIndicator; m_backupIndicator->start(); } else { if (m_backupIndicator) m_backupIndicator->stop(); } } void App::updateDisplayTitleBar() { std::string defaultTitle = PACKAGE " v" VERSION; std::string title; DocumentView* docView = UIContext::instance()->activeView(); if (docView) { // Prepend the document's filename. title += docView->document()->name(); title += " - "; } title += defaultTitle; she::instance()->defaultDisplay()->setTitleBar(title); } InputChain& App::inputChain() { return m_modules->m_inputChain; } // Updates palette and redraw the screen. void app_refresh_screen() { Context* context = UIContext::instance(); ASSERT(context != NULL); Site site = context->activeSite(); if (Palette* pal = site.palette()) set_current_palette(pal, false); else set_current_palette(NULL, false); // Invalidate the whole screen. ui::Manager::getDefault()->invalidate(); } // TODO remove app_rebuild_documents_tabs() and replace it by // observable events in the document (so a tab can observe if the // document is modified). void app_rebuild_documents_tabs() { if (App::instance()->isGui()) { App::instance()->workspace()->updateTabs(); App::instance()->updateDisplayTitleBar(); } } PixelFormat app_get_current_pixel_format() { Context* context = UIContext::instance(); ASSERT(context != NULL); Document* document = context->activeDocument(); if (document != NULL) return document->sprite()->pixelFormat(); else return IMAGE_RGB; } void app_default_statusbar_message() { StatusBar::instance() ->setStatusText(250, "%s %s | %s", PACKAGE, VERSION, COPYRIGHT); } int app_get_color_to_clear_layer(Layer* layer) { ASSERT(layer != NULL); app::Color color; // The `Background' is erased with the `Background Color' if (layer->isBackground()) { if (ColorBar::instance()) color = ColorBar::instance()->getBgColor(); else color = app::Color::fromRgb(0, 0, 0); // TODO get background color color from doc::Settings } else // All transparent layers are cleared with the mask color color = app::Color::fromMask(); return color_utils::color_for_layer(color, layer); } } // namespace app
aseprite_aseprite
2017-01-28
90624bbc22b486e5303ddd710855267feeadbd80
src/app/commands/cmd_goto_layer.cpp
82
// Aseprite // Copyright (C) 2001-2015 David Capello // // This program is distributed under the terms of // the End-User License Agreement for Aseprite. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "app/app.h" #include "app/commands/command.h" #include "app/context_access.h" #include "app/modules/editors.h" #include "app/modules/gui.h" #include "app/ui/editor/editor.h" #include "app/ui/status_bar.h" #include "doc/layer.h" #include "doc/sprite.h" namespace app { class GotoCommand : public Command { public: GotoCommand(const char* short_name, const char* friendly_name, CommandFlags flags) : Command(short_name, friendly_name, flags) { } protected: void updateStatusBar(Site& site) { if (site.layer() != NULL) StatusBar::instance() ->setStatusText(1000, "Layer `%s' selected", site.layer()->name().c_str()); } }; class GotoPreviousLayerCommand : public GotoCommand { public: GotoPreviousLayerCommand(); Command* clone() const override { return new GotoPreviousLayerCommand(*this); } protected: bool onEnabled(Context* context) override; void onExecute(Context* context) override; }; GotoPreviousLayerCommand::GotoPreviousLayerCommand() : GotoCommand("GotoPreviousLayer", "Go to Previous Layer", CmdUIOnlyFlag) { } bool GotoPreviousLayerCommand::onEnabled(Context* context) { return (current_editor != nullptr && current_editor->document()); } void GotoPreviousLayerCommand::onExecute(Context* context) { Site site = current_editor->getSite(); if (site.layerIndex() > 0) site.layerIndex(site.layerIndex().previous()); else site.layerIndex(LayerIndex(site.sprite()->countLayers()-1)); // Flash the current layer current_editor->setLayer(site.layer()); current_editor->flashCurrentLayer(); updateStatusBar(site); } class GotoNextLayerCommand : public GotoCommand { public: GotoNextLayerCommand(); Command* clone() const override { return new GotoNextLayerCommand(*this); } protected: bool onEnabled(Context* context) override; void onExecute(Context* context) override; }; GotoNextLayerCommand::GotoNextLayerCommand() : GotoCommand("GotoNextLayer", "Go to Next Layer", CmdUIOnlyFlag) { } bool GotoNextLayerCommand::onEnabled(Context* context) { return (current_editor != nullptr && current_editor->document()); } void GotoNextLayerCommand::onExecute(Context* context) { Site site = current_editor->getSite(); if (site.layerIndex() < site.sprite()->countLayers()-1) site.layerIndex(site.layerIndex().next()); else site.layerIndex(LayerIndex(0)); // Flash the current layer current_editor->setLayer(site.layer()); current_editor->flashCurrentLayer(); updateStatusBar(site); } Command* CommandFactory::createGotoPreviousLayerCommand() { return new GotoPreviousLayerCommand; } Command* CommandFactory::createGotoNextLayerCommand() { return new GotoNextLayerCommand; } } // namespace app
aseprite_aseprite
2017-01-28
90624bbc22b486e5303ddd710855267feeadbd80
src/app/document_range_ops.cpp
256
// Aseprite // Copyright (C) 2001-2016 David Capello // // This program is distributed under the terms of // the End-User License Agreement for Aseprite. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "app/document_range_ops.h" #include "app/app.h" // TODO remove this dependency #include "app/context_access.h" #include "app/document_api.h" #include "app/document_range.h" #include "app/transaction.h" #include "doc/layer.h" #include "doc/sprite.h" #include <stdexcept> namespace app { enum Op { Move, Copy }; static DocumentRange drop_range_op( Document* doc, Op op, const DocumentRange& from, DocumentRangePlace place, const DocumentRange& to) { if (place != kDocumentRangeBefore && place != kDocumentRangeAfter) { ASSERT(false); throw std::invalid_argument("Invalid 'place' argument"); } Sprite* sprite = doc->sprite(); // Check noop/trivial/do nothing cases, i.e., move a range to the same place. // Also check invalid cases, like moving a Background layer. switch (from.type()) { case DocumentRange::kCels: if (from == to) return from; break; case DocumentRange::kFrames: if (op == Move) { if ((to.frameBegin() >= from.frameBegin() && to.frameEnd() <= from.frameEnd()) || (place == kDocumentRangeBefore && to.frameBegin() == from.frameEnd()+1) || (place == kDocumentRangeAfter && to.frameEnd() == from.frameBegin()-1)) return from; } break; case DocumentRange::kLayers: if (op == Move) { if ((to.layerBegin() >= from.layerBegin() && to.layerEnd() <= from.layerEnd()) || (place == kDocumentRangeBefore && to.layerBegin() == from.layerEnd()+1) || (place == kDocumentRangeAfter && to.layerEnd() == from.layerBegin()-1)) return from; // We cannot move the background for (LayerIndex i = from.layerBegin(); i <= from.layerEnd(); ++i) if (sprite->indexToLayer(i)->isBackground()) throw std::runtime_error("The background layer cannot be moved"); } // Before background if (place == kDocumentRangeBefore) { Layer* background = sprite->indexToLayer(to.layerBegin()); if (background && background->isBackground()) throw std::runtime_error("You cannot move or copy something below the background layer"); } break; } const char* undoLabel = NULL; switch (op) { case Move: undoLabel = "Move Range"; break; case Copy: undoLabel = "Copy Range"; break; default: ASSERT(false); throw std::invalid_argument("Invalid 'op' argument"); } DocumentRange resultRange; { const app::Context* context = static_cast<app::Context*>(doc->context()); const ContextReader reader(context); ContextWriter writer(reader, 500); Transaction transaction(writer.context(), undoLabel, ModifyDocument); DocumentApi api = doc->getApi(transaction); // TODO Try to add the range with just one call to DocumentApi // methods, to avoid generating a lot of SetCelFrame undoers (see // DocumentApi::setCelFramePosition). switch (from.type()) { case DocumentRange::kCels: { std::vector<Layer*> layers; sprite->getLayersList(layers); int srcLayerBegin, srcLayerStep, srcLayerEnd; int dstLayerBegin, dstLayerStep; frame_t srcFrameBegin, srcFrameStep, srcFrameEnd; frame_t dstFrameBegin, dstFrameStep; if (to.layerBegin() <= from.layerBegin()) { srcLayerBegin = from.layerBegin(); srcLayerStep = 1; srcLayerEnd = from.layerEnd()+1; dstLayerBegin = to.layerBegin(); dstLayerStep = 1; } else { srcLayerBegin = from.layerEnd(); srcLayerStep = -1; srcLayerEnd = from.layerBegin()-1; dstLayerBegin = to.layerEnd(); dstLayerStep = -1; } if (to.frameBegin() <= from.frameBegin()) { srcFrameBegin = from.frameBegin(); srcFrameStep = frame_t(1); srcFrameEnd = from.frameEnd()+1; dstFrameBegin = to.frameBegin(); dstFrameStep = frame_t(1); } else { srcFrameBegin = from.frameEnd(); srcFrameStep = frame_t(-1); srcFrameEnd = from.frameBegin()-1; dstFrameBegin = to.frameEnd(); dstFrameStep = frame_t(-1); } for (int srcLayerIdx = srcLayerBegin, dstLayerIdx = dstLayerBegin; srcLayerIdx != srcLayerEnd; ) { for (frame_t srcFrame = srcFrameBegin, dstFrame = dstFrameBegin; srcFrame != srcFrameEnd; ) { if (dstLayerIdx < 0 || dstLayerIdx >= int(layers.size()) || srcLayerIdx < 0 || srcLayerIdx >= int(layers.size())) break; LayerImage* srcLayer = static_cast<LayerImage*>(layers[srcLayerIdx]); LayerImage* dstLayer = static_cast<LayerImage*>(layers[dstLayerIdx]); switch (op) { case Move: api.moveCel(srcLayer, srcFrame, dstLayer, dstFrame); break; case Copy: api.copyCel(srcLayer, srcFrame, dstLayer, dstFrame); break; } srcFrame += srcFrameStep; dstFrame += dstFrameStep; } srcLayerIdx += srcLayerStep; dstLayerIdx += dstLayerStep; } resultRange = to; } break; case DocumentRange::kFrames: { frame_t srcFrameBegin = 0, srcFrameStep, srcFrameEnd = 0; frame_t dstFrameBegin = 0, dstFrameStep; switch (op) { case Move: if (place == kDocumentRangeBefore) { if (to.frameBegin() <= from.frameBegin()) { srcFrameBegin = from.frameBegin(); srcFrameStep = frame_t(1); srcFrameEnd = from.frameEnd()+1; dstFrameBegin = to.frameBegin(); dstFrameStep = frame_t(1); } else { srcFrameBegin = from.frameEnd(); srcFrameStep = frame_t(-1); srcFrameEnd = from.frameBegin()-1; dstFrameBegin = to.frameBegin(); dstFrameStep = frame_t(-1); } } else if (place == kDocumentRangeAfter) { if (to.frameEnd() <= from.frameBegin()) { srcFrameBegin = from.frameBegin(); srcFrameStep = frame_t(1); srcFrameEnd = from.frameEnd()+1; dstFrameBegin = to.frameEnd()+1; dstFrameStep = frame_t(1); } else { srcFrameBegin = from.frameEnd(); srcFrameStep = frame_t(-1); srcFrameEnd = from.frameBegin()-1; dstFrameBegin = to.frameEnd()+1; dstFrameStep = frame_t(-1); } } break; case Copy: if (place == kDocumentRangeBefore) { if (to.frameBegin() <= from.frameBegin()) { srcFrameBegin = from.frameBegin(); srcFrameStep = frame_t(2); srcFrameEnd = from.frameBegin() + 2*from.frames(); dstFrameBegin = to.frameBegin(); dstFrameStep = frame_t(1); } else { srcFrameBegin = from.frameEnd(); srcFrameStep = frame_t(-1); srcFrameEnd = from.frameBegin()-1; dstFrameBegin = to.frameBegin(); dstFrameStep = frame_t(0); } } else if (place == kDocumentRangeAfter) { if (to.frameEnd() <= from.frameBegin()) { srcFrameBegin = from.frameBegin(); srcFrameStep = frame_t(2); srcFrameEnd = from.frameBegin() + 2*from.frames(); dstFrameBegin = to.frameEnd()+1; dstFrameStep = frame_t(1); } else { srcFrameBegin = from.frameEnd(); srcFrameStep = frame_t(-1); srcFrameEnd = from.frameBegin()-1; dstFrameBegin = to.frameEnd()+1; dstFrameStep = frame_t(0); } } break; } for (frame_t srcFrame = srcFrameBegin, dstFrame = dstFrameBegin; srcFrame != srcFrameEnd; ) { switch (op) { case Move: api.moveFrame(sprite, srcFrame, dstFrame); break; case Copy: api.copyFrame(sprite, srcFrame, dstFrame); break; } srcFrame += srcFrameStep; dstFrame += dstFrameStep; } if (place == kDocumentRangeBefore) { resultRange.startRange(LayerIndex::NoLayer, frame_t(to.frameBegin()), from.type()); resultRange.endRange(LayerIndex::NoLayer, frame_t(to.frameBegin()+from.frames()-1)); } else if (place == kDocumentRangeAfter) { resultRange.startRange(LayerIndex::NoLayer, frame_t(to.frameEnd()+1), from.type()); resultRange.endRange(LayerIndex::NoLayer, frame_t(to.frameEnd()+1+from.frames()-1)); } if (op == Move && from.frameBegin() < to.frameBegin()) resultRange.displace(0, -from.frames()); } break; case DocumentRange::kLayers: { std::vector<Layer*> layers; sprite->getLayersList(layers); if (layers.empty()) break; switch (op) { case Move: if (place == kDocumentRangeBefore) { for (LayerIndex i = from.layerBegin(); i <= from.layerEnd(); ++i) { api.restackLayerBefore( layers[i], layers[to.layerBegin()]); } } else if (place == kDocumentRangeAfter) { for (LayerIndex i = from.layerEnd(); i >= from.layerBegin(); --i) { api.restackLayerAfter( layers[i], layers[to.layerEnd()]); } } break; case Copy: if (place == kDocumentRangeBefore) { for (LayerIndex i = from.layerBegin(); i <= from.layerEnd(); ++i) { api.duplicateLayerBefore( layers[i], layers[to.layerBegin()]); } } else if (place == kDocumentRangeAfter) { for (LayerIndex i = from.layerEnd(); i >= from.layerBegin(); --i) { api.duplicateLayerAfter( layers[i], layers[to.layerEnd()]); } } break; } if (place == kDocumentRangeBefore) { resultRange.startRange(LayerIndex(to.layerBegin()), frame_t(-1), from.type()); resultRange.endRange(LayerIndex(to.layerBegin()+from.layers()-1), frame_t(-1)); } else if (place == kDocumentRangeAfter) { resultRange.startRange(LayerIndex(to.layerEnd()+1), frame_t(-1), from.type()); resultRange.endRange(LayerIndex(to.layerEnd()+1+from.layers()-1), frame_t(-1)); } if (op == Move && from.layerBegin() < to.layerBegin()) resultRange.displace(-from.layers(), 0); } break; } transaction.commit(); } return resultRange; } DocumentRange move_range(Document* doc, const DocumentRange& from, const DocumentRange& to, DocumentRangePlace place) { return drop_range_op(doc, Move, from, place, to); } DocumentRange copy_range(Document* doc, const DocumentRange& from, const DocumentRange& to, DocumentRangePlace place) { return drop_range_op(doc, Copy, from, place, to); } void reverse_frames(Document* doc, const DocumentRange& range) { const app::Context* context = static_cast<app::Context*>(doc->context()); const ContextReader reader(context); ContextWriter writer(reader, 500); Transaction transaction(writer.context(), "Reverse Frames"); DocumentApi api = doc->getApi(transaction); Sprite* sprite = doc->sprite(); frame_t frameBegin, frameEnd; int layerBegin, layerEnd; bool moveFrames = false; bool swapCels = false; switch (range.type()) { case DocumentRange::kCels: frameBegin = range.frameBegin(); frameEnd = range.frameEnd(); layerBegin = range.layerBegin(); layerEnd = range.layerEnd() + 1; swapCels = true; break; case DocumentRange::kFrames: frameBegin = range.frameBegin(); frameEnd = range.frameEnd(); moveFrames = true; break; case DocumentRange::kLayers: frameBegin = frame_t(0); frameEnd = sprite->totalFrames()-1; layerBegin = range.layerBegin(); layerEnd = range.layerEnd() + 1; swapCels = true; break; } if (moveFrames) { for (frame_t frameRev = frameEnd+1; frameRev > frameBegin; --frameRev) { api.moveFrame(sprite, frameBegin, frameRev); } } else if (swapCels) { std::vector<Layer*> layers; sprite->getLayersList(layers); for (int layerIdx = layerBegin; layerIdx != layerEnd; ++layerIdx) { for (frame_t frame = frameBegin, frameRev = frameEnd; frame != (frameBegin+frameEnd)/2+1; ++frame, --frameRev) { if (frame == frameRev) continue; LayerImage* layer = static_cast<LayerImage*>(layers[layerIdx]); api.swapCel(layer, frame, frameRev); } } } transaction.commit(); } } // namespace app
aseprite_aseprite
2017-01-28
90624bbc22b486e5303ddd710855267feeadbd80
src/app/commands/cmd_new_layer_set.cpp
86
// Aseprite // Copyright (C) 2001-2015 David Capello // // This program is distributed under the terms of // the End-User License Agreement for Aseprite. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "app/app.h" #include "app/commands/command.h" #include "app/context_access.h" #include "app/document_api.h" #include "app/document_api.h" #include "app/find_widget.h" #include "app/load_widget.h" #include "app/modules/gui.h" #include "app/ui/status_bar.h" #include "app/transaction.h" #include "doc/layer.h" #include "doc/sprite.h" #include "ui/ui.h" namespace app { using namespace ui; class NewLayerSetCommand : public Command { public: NewLayerSetCommand(); Command* clone() const override { return new NewLayerSetCommand(*this); } protected: bool onEnabled(Context* context) override; void onExecute(Context* context) override; }; NewLayerSetCommand::NewLayerSetCommand() : Command("NewLayerSet", "New Layer Set", CmdRecordableFlag) { } bool NewLayerSetCommand::onEnabled(Context* context) { return context->checkFlags(ContextFlags::ActiveDocumentIsWritable | ContextFlags::HasActiveSprite); } void NewLayerSetCommand::onExecute(Context* context) { ContextWriter writer(context); Document* document(writer.document()); Sprite* sprite(writer.sprite()); // load the window widget base::UniquePtr<Window> window(app::load_widget<Window>("new_layer.xml", "new_layer_set")); window->openWindowInForeground(); if (window->closer() != window->findChild("ok")) return; std::string name = window->findChild("name")->text(); Layer* layer; { Transaction transaction(writer.context(), "New Layer"); layer = document->getApi(transaction).newLayerFolder(sprite); transaction.commit(); } layer->setName(name); update_screen_for_document(document); StatusBar::instance()->invalidate(); StatusBar::instance()->showTip(1000, "Layer `%s' created", name.c_str()); } Command* CommandFactory::createNewLayerSetCommand() { return new NewLayerSetCommand; } } // namespace app
aseprite_aseprite
2017-01-28
90624bbc22b486e5303ddd710855267feeadbd80
src/doc/layers_range.cpp
56
// Aseprite Document Library // Copyright (c) 2001-2015 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "doc/layers_range.h" #include "doc/cel.h" #include "doc/layer.h" #include "doc/sprite.h" namespace doc { LayersRange::LayersRange(const Sprite* sprite, LayerIndex first, LayerIndex last) : m_begin(sprite, first, last) , m_end() { } LayersRange::iterator::iterator() : m_layer(nullptr) , m_cur(-1) , m_last(-1) { } LayersRange::iterator::iterator(const Sprite* sprite, LayerIndex first, LayerIndex last) : m_layer(nullptr) , m_cur(first) , m_last(last) { m_layer = sprite->layer(first); } LayersRange::iterator& LayersRange::iterator::operator++() { if (!m_layer) return *this; ++m_cur; if (m_cur > m_last) m_layer = nullptr; else m_layer = m_layer->getNext(); return *this; } } // namespace doc
aseprite_aseprite
2017-01-28
90624bbc22b486e5303ddd710855267feeadbd80
src/gfx/clip.cpp
64
// Aseprite Gfx Library // Copyright (c) 2001-2014 David Capello // // This file is released under the terms of the MIT license. // Read LICENSE.txt for more information. #ifdef HAVE_CONFIG_H #include "config.h" #endif #include "gfx/clip.h" namespace gfx { bool Clip::clip( int avail_dst_w, int avail_dst_h, int avail_src_w, int avail_src_h) { // Clip srcBounds if (src.x < 0) { size.w += src.x; dst.x -= src.x; src.x = 0; } if (src.y < 0) { size.h += src.y; dst.y -= src.y; src.y = 0; } if (src.x + size.w > avail_src_w) size.w -= src.x + size.w - avail_src_w; if (src.y + size.h > avail_src_h) size.h -= src.y + size.h - avail_src_h; // Clip dstBounds if (dst.x < 0) { size.w += dst.x; src.x -= dst.x; dst.x = 0; } if (dst.y < 0) { size.h += dst.y; src.y -= dst.y; dst.y = 0; } if (dst.x + size.w > avail_dst_w) size.w -= dst.x + size.w - avail_dst_w; if (dst.y + size.h > avail_dst_h) size.h -= dst.y + size.h - avail_dst_h; return (size.w > 0 && size.h > 0); } } // namespace gfx
aseprite_aseprite
2017-01-28
90624bbc22b486e5303ddd710855267feeadbd80
public/js/app.js
41
!function(t){function e(r){if(n[r])return n[r].exports;var i=n[r]={i:r,l:!1,exports:{}};return t[r].call(i.exports,i,i.exports,e),i.l=!0,i.exports}var n={};return e.m=t,e.c=n,e.i=function(t){return t},e.d=function(t,n,r){e.o(t,n)||Object.defineProperty(t,n,{configurable:!1,enumerable:!0,get:r})},e.n=function(t){var n=t&&t.__esModule?function(){return t.default}:function(){return t};return e.d(n,"a",n),n},e.o=function(t,e){return Object.prototype.hasOwnProperty.call(t,e)},e.p="./",e(e.s=38)}([function(t,e,n){"use strict";function r(t){return"[object Array]"===C.call(t)}function i(t){return"[object ArrayBuffer]"===C.call(t)}function o(t){return"undefined"!=typeof FormData&&t instanceof FormData}function a(t){var e;return e="undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(t):t&&t.buffer&&t.buffer instanceof ArrayBuffer}function s(t){return"string"==typeof t}function u(t){return"number"==typeof t}function c(t){return"undefined"==typeof t}function l(t){return null!==t&&"object"==typeof t}function f(t){return"[object Date]"===C.call(t)}function p(t){return"[object File]"===C.call(t)}function d(t){return"[object Blob]"===C.call(t)}function h(t){return"[object Function]"===C.call(t)}function v(t){return l(t)&&h(t.pipe)}function g(t){return"undefined"!=typeof URLSearchParams&&t instanceof URLSearchParams}function m(t){return t.replace(/^\s*/,"").replace(/\s*$/,"")}function y(){return"undefined"!=typeof window&&"undefined"!=typeof document&&"function"==typeof document.createElement}function b(t,e){if(null!==t&&"undefined"!=typeof t)if("object"==typeof t||r(t)||(t=[t]),r(t))for(var n=0,i=t.length;n<i;n++)e.call(null,t[n],n,t);else for(var o in t)Object.prototype.hasOwnProperty.call(t,o)&&e.call(null,t[o],o,t)}function _(){function t(t,n){"object"==typeof e[n]&&"object"==typeof t?e[n]=_(e[n],t):e[n]=t}for(var e={},n=0,r=arguments.length;n<r;n++)b(arguments[n],t);return e}function w(t,e,n){return b(e,function(e,r){n&&"function"==typeof e?t[r]=x(e,n):t[r]=e}),t}var x=n(6),C=Object.prototype.toString;t.exports={isArray:r,isArrayBuffer:i,isFormData:o,isArrayBufferView:a,isString:s,isNumber:u,isObject:l,isUndefined:c,isDate:f,isFile:p,isBlob:d,isFunction:h,isStream:v,isURLSearchParams:g,isStandardBrowserEnv:y,forEach:b,merge:_,extend:w,trim:m}},function(t,e,n){"use strict";(function(e){function r(t,e){!o.isUndefined(t)&&o.isUndefined(t["Content-Type"])&&(t["Content-Type"]=e)}function i(){var t;return"undefined"!=typeof XMLHttpRequest?t=n(2):"undefined"!=typeof e&&(t=n(2)),t}var o=n(0),a=n(26),s=/^\)\]\}',?\n/,u={"Content-Type":"application/x-www-form-urlencoded"},c={adapter:i(),transformRequest:[function(t,e){return a(e,"Content-Type"),o.isFormData(t)||o.isArrayBuffer(t)||o.isStream(t)||o.isFile(t)||o.isBlob(t)?t:o.isArrayBufferView(t)?t.buffer:o.isURLSearchParams(t)?(r(e,"application/x-www-form-urlencoded;charset=utf-8"),t.toString()):o.isObject(t)?(r(e,"application/json;charset=utf-8"),JSON.stringify(t)):t}],transformResponse:[function(t){if("string"==typeof t){t=t.replace(s,"");try{t=JSON.parse(t)}catch(t){}}return t}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,validateStatus:function(t){return t>=200&&t<300}};c.headers={common:{Accept:"application/json, text/plain, */*"}},o.forEach(["delete","get","head"],function(t){c.headers[t]={}}),o.forEach(["post","put","patch"],function(t){c.headers[t]=o.merge(u)}),t.exports=c}).call(e,n(33))},function(t,e,n){"use strict";var r=n(0),i=n(18),o=n(21),a=n(27),s=n(25),u=n(5),c="undefined"!=typeof window&&window.btoa&&window.btoa.bind(window)||n(20);t.exports=function(t){return new Promise(function(e,l){var f=t.data,p=t.headers;r.isFormData(f)&&delete p["Content-Type"];var d=new XMLHttpRequest,h="onreadystatechange",v=!1;if("undefined"==typeof window||!window.XDomainRequest||"withCredentials"in d||s(t.url)||(d=new window.XDomainRequest,h="onload",v=!0,d.onprogress=function(){},d.ontimeout=function(){}),t.auth){var g=t.auth.username||"",m=t.auth.password||"";p.Authorization="Basic "+c(g+":"+m)}if(d.open(t.method.toUpperCase(),o(t.url,t.params,t.paramsSerializer),!0),d.timeout=t.timeout,d[h]=function(){if(d&&(4===d.readyState||v)&&(0!==d.status||d.responseURL&&0===d.responseURL.indexOf("file:"))){var n="getAllResponseHeaders"in d?a(d.getAllResponseHeaders()):null,r=t.responseType&&"text"!==t.responseType?d.response:d.responseText,o={data:r,status:1223===d.status?204:d.status,statusText:1223===d.status?"No Content":d.statusText,headers:n,config:t,request:d};i(e,l,o),d=null}},d.onerror=function(){l(u("Network Error",t)),d=null},d.ontimeout=function(){l(u("timeout of "+t.timeout+"ms exceeded",t,"ECONNABORTED")),d=null},r.isStandardBrowserEnv()){var y=n(23),b=(t.withCredentials||s(t.url))&&t.xsrfCookieName?y.read(t.xsrfCookieName):void 0;b&&(p[t.xsrfHeaderName]=b)}if("setRequestHeader"in d&&r.forEach(p,function(t,e){"undefined"==typeof f&&"content-type"===e.toLowerCase()?delete p[e]:d.setRequestHeader(e,t)}),t.withCredentials&&(d.withCredentials=!0),t.responseType)try{d.responseType=t.responseType}catch(t){if("json"!==d.responseType)throw t}"function"==typeof t.onDownloadProgress&&d.addEventListener("progress",t.onDownloadProgress),"function"==typeof t.onUploadProgress&&d.upload&&d.upload.addEventListener("progress",t.onUploadProgress),t.cancelToken&&t.cancelToken.promise.then(function(t){d&&(d.abort(),l(t),d=null)}),void 0===f&&(f=null),d.send(f)})}},function(t,e,n){"use strict";function r(t){this.message=t}r.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},r.prototype.__CANCEL__=!0,t.exports=r},function(t,e,n){"use strict";t.exports=function(t){return!(!t||!t.__CANCEL__)}},function(t,e,n){"use strict";var r=n(17);t.exports=function(t,e,n,i){var o=new Error(t);return r(o,e,n,i)}},function(t,e,n){"use strict";t.exports=function(t,e){return function(){for(var n=new Array(arguments.length),r=0;r<n.length;r++)n[r]=arguments[r];return t.apply(e,n)}}},function(t,e,n){var r,i;/*! * jQuery JavaScript Library v3.1.1 * https://jquery.com/ * * Includes Sizzle.js * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * https://jquery.org/license * * Date: 2016-09-22T22:30Z */ !function(e,n){"use strict";"object"==typeof t&&"object"==typeof t.exports?t.exports=e.document?n(e,!0):function(t){if(!t.document)throw new Error("jQuery requires a window with a document");return n(t)}:n(e)}("undefined"!=typeof window?window:this,function(n,o){"use strict";function a(t,e){e=e||ot;var n=e.createElement("script");n.text=t,e.head.appendChild(n).parentNode.removeChild(n)}function s(t){var e=!!t&&"length"in t&&t.length,n=yt.type(t);return"function"!==n&&!yt.isWindow(t)&&("array"===n||0===e||"number"==typeof e&&e>0&&e-1 in t)}function u(t,e,n){return yt.isFunction(e)?yt.grep(t,function(t,r){return!!e.call(t,r,t)!==n}):e.nodeType?yt.grep(t,function(t){return t===e!==n}):"string"!=typeof e?yt.grep(t,function(t){return lt.call(e,t)>-1!==n}):Et.test(e)?yt.filter(e,t,n):(e=yt.filter(e,t),yt.grep(t,function(t){return lt.call(e,t)>-1!==n&&1===t.nodeType}))}function c(t,e){for(;(t=t[e])&&1!==t.nodeType;);return t}function l(t){var e={};return yt.each(t.match(It)||[],function(t,n){e[n]=!0}),e}function f(t){return t}function p(t){throw t}function d(t,e,n){var r;try{t&&yt.isFunction(r=t.promise)?r.call(t).done(e).fail(n):t&&yt.isFunction(r=t.then)?r.call(t,e,n):e.call(void 0,t)}catch(t){n.call(void 0,t)}}function h(){ot.removeEventListener("DOMContentLoaded",h),n.removeEventListener("load",h),yt.ready()}function v(){this.expando=yt.expando+v.uid++}function g(t){return"true"===t||"false"!==t&&("null"===t?null:t===+t+""?+t:Ht.test(t)?JSON.parse(t):t)}function m(t,e,n){var r;if(void 0===n&&1===t.nodeType)if(r="data-"+e.replace(Bt,"-$&").toLowerCase(),n=t.getAttribute(r),"string"==typeof n){try{n=g(n)}catch(t){}Mt.set(t,e,n)}else n=void 0;return n}function y(t,e,n,r){var i,o=1,a=20,s=r?function(){return r.cur()}:function(){return yt.css(t,e,"")},u=s(),c=n&&n[3]||(yt.cssNumber[e]?"":"px"),l=(yt.cssNumber[e]||"px"!==c&&+u)&&Wt.exec(yt.css(t,e));if(l&&l[3]!==c){c=c||l[3],n=n||[],l=+u||1;do o=o||".5",l/=o,yt.style(t,e,l+c);while(o!==(o=s()/u)&&1!==o&&--a)}return n&&(l=+l||+u||0,i=n[1]?l+(n[1]+1)*n[2]:+n[2],r&&(r.unit=c,r.start=l,r.end=i)),i}function b(t){var e,n=t.ownerDocument,r=t.nodeName,i=Kt[r];return i?i:(e=n.body.appendChild(n.createElement(r)),i=yt.css(e,"display"),e.parentNode.removeChild(e),"none"===i&&(i="block"),Kt[r]=i,i)}function _(t,e){for(var n,r,i=[],o=0,a=t.length;o<a;o++)r=t[o],r.style&&(n=r.style.display,e?("none"===n&&(i[o]=qt.get(r,"display")||null,i[o]||(r.style.display="")),""===r.style.display&&Vt(r)&&(i[o]=b(r))):"none"!==n&&(i[o]="none",qt.set(r,"display",n)));for(o=0;o<a;o++)null!=i[o]&&(t[o].style.display=i[o]);return t}function w(t,e){var n;return n="undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e||"*"):"undefined"!=typeof t.querySelectorAll?t.querySelectorAll(e||"*"):[],void 0===e||e&&yt.nodeName(t,e)?yt.merge([t],n):n}function x(t,e){for(var n=0,r=t.length;n<r;n++)qt.set(t[n],"globalEval",!e||qt.get(e[n],"globalEval"))}function C(t,e,n,r,i){for(var o,a,s,u,c,l,f=e.createDocumentFragment(),p=[],d=0,h=t.length;d<h;d++)if(o=t[d],o||0===o)if("object"===yt.type(o))yt.merge(p,o.nodeType?[o]:o);else if(Qt.test(o)){for(a=a||f.appendChild(e.createElement("div")),s=(Gt.exec(o)||["",""])[1].toLowerCase(),u=Yt[s]||Yt._default,a.innerHTML=u[1]+yt.htmlPrefilter(o)+u[2],l=u[0];l--;)a=a.lastChild;yt.merge(p,a.childNodes),a=f.firstChild,a.textContent=""}else p.push(e.createTextNode(o));for(f.textContent="",d=0;o=p[d++];)if(r&&yt.inArray(o,r)>-1)i&&i.push(o);else if(c=yt.contains(o.ownerDocument,o),a=w(f.appendChild(o),"script"),c&&x(a),n)for(l=0;o=a[l++];)Zt.test(o.type||"")&&n.push(o);return f}function T(){return!0}function $(){return!1}function k(){try{return ot.activeElement}catch(t){}}function A(t,e,n,r,i,o){var a,s;if("object"==typeof e){"string"!=typeof n&&(r=r||n,n=void 0);for(s in e)A(t,s,n,r,e[s],o);return t}if(null==r&&null==i?(i=n,r=n=void 0):null==i&&("string"==typeof n?(i=r,r=void 0):(i=r,r=n,n=void 0)),i===!1)i=$;else if(!i)return t;return 1===o&&(a=i,i=function(t){return yt().off(t),a.apply(this,arguments)},i.guid=a.guid||(a.guid=yt.guid++)),t.each(function(){yt.event.add(this,e,i,r,n)})}function E(t,e){return yt.nodeName(t,"table")&&yt.nodeName(11!==e.nodeType?e:e.firstChild,"tr")?t.getElementsByTagName("tbody")[0]||t:t}function S(t){return t.type=(null!==t.getAttribute("type"))+"/"+t.type,t}function O(t){var e=se.exec(t.type);return e?t.type=e[1]:t.removeAttribute("type"),t}function j(t,e){var n,r,i,o,a,s,u,c;if(1===e.nodeType){if(qt.hasData(t)&&(o=qt.access(t),a=qt.set(e,o),c=o.events)){delete a.handle,a.events={};for(i in c)for(n=0,r=c[i].length;n<r;n++)yt.event.add(e,i,c[i][n])}Mt.hasData(t)&&(s=Mt.access(t),u=yt.extend({},s),Mt.set(e,u))}}function N(t,e){var n=e.nodeName.toLowerCase();"input"===n&&Jt.test(t.type)?e.checked=t.checked:"input"!==n&&"textarea"!==n||(e.defaultValue=t.defaultValue)}function D(t,e,n,r){e=ut.apply([],e);var i,o,s,u,c,l,f=0,p=t.length,d=p-1,h=e[0],v=yt.isFunction(h);if(v||p>1&&"string"==typeof h&&!gt.checkClone&&ae.test(h))return t.each(function(i){var o=t.eq(i);v&&(e[0]=h.call(this,i,o.html())),D(o,e,n,r)});if(p&&(i=C(e,t[0].ownerDocument,!1,t,r),o=i.firstChild,1===i.childNodes.length&&(i=o),o||r)){for(s=yt.map(w(i,"script"),S),u=s.length;f<p;f++)c=i,f!==d&&(c=yt.clone(c,!0,!0),u&&yt.merge(s,w(c,"script"))),n.call(t[f],c,f);if(u)for(l=s[s.length-1].ownerDocument,yt.map(s,O),f=0;f<u;f++)c=s[f],Zt.test(c.type||"")&&!qt.access(c,"globalEval")&&yt.contains(l,c)&&(c.src?yt._evalUrl&&yt._evalUrl(c.src):a(c.textContent.replace(ue,""),l))}return t}function I(t,e,n){for(var r,i=e?yt.filter(e,t):t,o=0;null!=(r=i[o]);o++)n||1!==r.nodeType||yt.cleanData(w(r)),r.parentNode&&(n&&yt.contains(r.ownerDocument,r)&&x(w(r,"script")),r.parentNode.removeChild(r));return t}function R(t,e,n){var r,i,o,a,s=t.style;return n=n||fe(t),n&&(a=n.getPropertyValue(e)||n[e],""!==a||yt.contains(t.ownerDocument,t)||(a=yt.style(t,e)),!gt.pixelMarginRight()&&le.test(a)&&ce.test(e)&&(r=s.width,i=s.minWidth,o=s.maxWidth,s.minWidth=s.maxWidth=s.width=a,a=n.width,s.width=r,s.minWidth=i,s.maxWidth=o)),void 0!==a?a+"":a}function L(t,e){return{get:function(){return t()?void delete this.get:(this.get=e).apply(this,arguments)}}}function P(t){if(t in ge)return t;for(var e=t[0].toUpperCase()+t.slice(1),n=ve.length;n--;)if(t=ve[n]+e,t in ge)return t}function F(t,e,n){var r=Wt.exec(e);return r?Math.max(0,r[2]-(n||0))+(r[3]||"px"):e}function q(t,e,n,r,i){var o,a=0;for(o=n===(r?"border":"content")?4:"width"===e?1:0;o<4;o+=2)"margin"===n&&(a+=yt.css(t,n+zt[o],!0,i)),r?("content"===n&&(a-=yt.css(t,"padding"+zt[o],!0,i)),"margin"!==n&&(a-=yt.css(t,"border"+zt[o]+"Width",!0,i))):(a+=yt.css(t,"padding"+zt[o],!0,i),"padding"!==n&&(a+=yt.css(t,"border"+zt[o]+"Width",!0,i)));return a}function M(t,e,n){var r,i=!0,o=fe(t),a="border-box"===yt.css(t,"boxSizing",!1,o);if(t.getClientRects().length&&(r=t.getBoundingClientRect()[e]),r<=0||null==r){if(r=R(t,e,o),(r<0||null==r)&&(r=t.style[e]),le.test(r))return r;i=a&&(gt.boxSizingReliable()||r===t.style[e]),r=parseFloat(r)||0}return r+q(t,e,n||(a?"border":"content"),i,o)+"px"}function H(t,e,n,r,i){return new H.prototype.init(t,e,n,r,i)}function B(){ye&&(n.requestAnimationFrame(B),yt.fx.tick())}function U(){return n.setTimeout(function(){me=void 0}),me=yt.now()}function W(t,e){var n,r=0,i={height:t};for(e=e?1:0;r<4;r+=2-e)n=zt[r],i["margin"+n]=i["padding"+n]=t;return e&&(i.opacity=i.width=t),i}function z(t,e,n){for(var r,i=(K.tweeners[e]||[]).concat(K.tweeners["*"]),o=0,a=i.length;o<a;o++)if(r=i[o].call(n,e,t))return r}function V(t,e,n){var r,i,o,a,s,u,c,l,f="width"in e||"height"in e,p=this,d={},h=t.style,v=t.nodeType&&Vt(t),g=qt.get(t,"fxshow");n.queue||(a=yt._queueHooks(t,"fx"),null==a.unqueued&&(a.unqueued=0,s=a.empty.fire,a.empty.fire=function(){a.unqueued||s()}),a.unqueued++,p.always(function(){p.always(function(){a.unqueued--,yt.queue(t,"fx").length||a.empty.fire()})}));for(r in e)if(i=e[r],be.test(i)){if(delete e[r],o=o||"toggle"===i,i===(v?"hide":"show")){if("show"!==i||!g||void 0===g[r])continue;v=!0}d[r]=g&&g[r]||yt.style(t,r)}if(u=!yt.isEmptyObject(e),u||!yt.isEmptyObject(d)){f&&1===t.nodeType&&(n.overflow=[h.overflow,h.overflowX,h.overflowY],c=g&&g.display,null==c&&(c=qt.get(t,"display")),l=yt.css(t,"display"),"none"===l&&(c?l=c:(_([t],!0),c=t.style.display||c,l=yt.css(t,"display"),_([t]))),("inline"===l||"inline-block"===l&&null!=c)&&"none"===yt.css(t,"float")&&(u||(p.done(function(){h.display=c}),null==c&&(l=h.display,c="none"===l?"":l)),h.display="inline-block")),n.overflow&&(h.overflow="hidden",p.always(function(){h.overflow=n.overflow[0],h.overflowX=n.overflow[1],h.overflowY=n.overflow[2]})),u=!1;for(r in d)u||(g?"hidden"in g&&(v=g.hidden):g=qt.access(t,"fxshow",{display:c}),o&&(g.hidden=!v),v&&_([t],!0),p.done(function(){v||_([t]),qt.remove(t,"fxshow");for(r in d)yt.style(t,r,d[r])})),u=z(v?g[r]:0,r,p),r in g||(g[r]=u.start,v&&(u.end=u.start,u.start=0))}}function X(t,e){var n,r,i,o,a;for(n in t)if(r=yt.camelCase(n),i=e[r],o=t[n],yt.isArray(o)&&(i=o[1],o=t[n]=o[0]),n!==r&&(t[r]=o,delete t[n]),a=yt.cssHooks[r],a&&"expand"in a){o=a.expand(o),delete t[r];for(n in o)n in t||(t[n]=o[n],e[n]=i)}else e[r]=i}function K(t,e,n){var r,i,o=0,a=K.prefilters.length,s=yt.Deferred().always(function(){delete u.elem}),u=function(){if(i)return!1;for(var e=me||U(),n=Math.max(0,c.startTime+c.duration-e),r=n/c.duration||0,o=1-r,a=0,u=c.tweens.length;a<u;a++)c.tweens[a].run(o);return s.notifyWith(t,[c,o,n]),o<1&&u?n:(s.resolveWith(t,[c]),!1)},c=s.promise({elem:t,props:yt.extend({},e),opts:yt.extend(!0,{specialEasing:{},easing:yt.easing._default},n),originalProperties:e,originalOptions:n,startTime:me||U(),duration:n.duration,tweens:[],createTween:function(e,n){var r=yt.Tween(t,c.opts,e,n,c.opts.specialEasing[e]||c.opts.easing);return c.tweens.push(r),r},stop:function(e){var n=0,r=e?c.tweens.length:0;if(i)return this;for(i=!0;n<r;n++)c.tweens[n].run(1);return e?(s.notifyWith(t,[c,1,0]),s.resolveWith(t,[c,e])):s.rejectWith(t,[c,e]),this}}),l=c.props;for(X(l,c.opts.specialEasing);o<a;o++)if(r=K.prefilters[o].call(c,t,l,c.opts))return yt.isFunction(r.stop)&&(yt._queueHooks(c.elem,c.opts.queue).stop=yt.proxy(r.stop,r)),r;return yt.map(l,z,c),yt.isFunction(c.opts.start)&&c.opts.start.call(t,c),yt.fx.timer(yt.extend(u,{elem:t,anim:c,queue:c.opts.queue})),c.progress(c.opts.progress).done(c.opts.done,c.opts.complete).fail(c.opts.fail).always(c.opts.always)}function J(t){var e=t.match(It)||[];return e.join(" ")}function G(t){return t.getAttribute&&t.getAttribute("class")||""}function Z(t,e,n,r){var i;if(yt.isArray(e))yt.each(e,function(e,i){n||Oe.test(t)?r(t,i):Z(t+"["+("object"==typeof i&&null!=i?e:"")+"]",i,n,r)});else if(n||"object"!==yt.type(e))r(t,e);else for(i in e)Z(t+"["+i+"]",e[i],n,r)}function Y(t){return function(e,n){"string"!=typeof e&&(n=e,e="*");var r,i=0,o=e.toLowerCase().match(It)||[];if(yt.isFunction(n))for(;r=o[i++];)"+"===r[0]?(r=r.slice(1)||"*",(t[r]=t[r]||[]).unshift(n)):(t[r]=t[r]||[]).push(n)}}function Q(t,e,n,r){function i(s){var u;return o[s]=!0,yt.each(t[s]||[],function(t,s){var c=s(e,n,r);return"string"!=typeof c||a||o[c]?a?!(u=c):void 0:(e.dataTypes.unshift(c),i(c),!1)}),u}var o={},a=t===Be;return i(e.dataTypes[0])||!o["*"]&&i("*")}function tt(t,e){var n,r,i=yt.ajaxSettings.flatOptions||{};for(n in e)void 0!==e[n]&&((i[n]?t:r||(r={}))[n]=e[n]);return r&&yt.extend(!0,t,r),t}function et(t,e,n){for(var r,i,o,a,s=t.contents,u=t.dataTypes;"*"===u[0];)u.shift(),void 0===r&&(r=t.mimeType||e.getResponseHeader("Content-Type"));if(r)for(i in s)if(s[i]&&s[i].test(r)){u.unshift(i);break}if(u[0]in n)o=u[0];else{for(i in n){if(!u[0]||t.converters[i+" "+u[0]]){o=i;break}a||(a=i)}o=o||a}if(o)return o!==u[0]&&u.unshift(o),n[o]}function nt(t,e,n,r){var i,o,a,s,u,c={},l=t.dataTypes.slice();if(l[1])for(a in t.converters)c[a.toLowerCase()]=t.converters[a];for(o=l.shift();o;)if(t.responseFields[o]&&(n[t.responseFields[o]]=e),!u&&r&&t.dataFilter&&(e=t.dataFilter(e,t.dataType)),u=o,o=l.shift())if("*"===o)o=u;else if("*"!==u&&u!==o){if(a=c[u+" "+o]||c["* "+o],!a)for(i in c)if(s=i.split(" "),s[1]===o&&(a=c[u+" "+s[0]]||c["* "+s[0]])){a===!0?a=c[i]:c[i]!==!0&&(o=s[0],l.unshift(s[1]));break}if(a!==!0)if(a&&t.throws)e=a(e);else try{e=a(e)}catch(t){return{state:"parsererror",error:a?t:"No conversion from "+u+" to "+o}}}return{state:"success",data:e}}function rt(t){return yt.isWindow(t)?t:9===t.nodeType&&t.defaultView}var it=[],ot=n.document,at=Object.getPrototypeOf,st=it.slice,ut=it.concat,ct=it.push,lt=it.indexOf,ft={},pt=ft.toString,dt=ft.hasOwnProperty,ht=dt.toString,vt=ht.call(Object),gt={},mt="3.1.1",yt=function(t,e){return new yt.fn.init(t,e)},bt=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,_t=/^-ms-/,wt=/-([a-z])/g,xt=function(t,e){return e.toUpperCase()};yt.fn=yt.prototype={jquery:mt,constructor:yt,length:0,toArray:function(){return st.call(this)},get:function(t){return null==t?st.call(this):t<0?this[t+this.length]:this[t]},pushStack:function(t){var e=yt.merge(this.constructor(),t);return e.prevObject=this,e},each:function(t){return yt.each(this,t)},map:function(t){return this.pushStack(yt.map(this,function(e,n){return t.call(e,n,e)}))},slice:function(){return this.pushStack(st.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(t){var e=this.length,n=+t+(t<0?e:0);return this.pushStack(n>=0&&n<e?[this[n]]:[])},end:function(){return this.prevObject||this.constructor()},push:ct,sort:it.sort,splice:it.splice},yt.extend=yt.fn.extend=function(){var t,e,n,r,i,o,a=arguments[0]||{},s=1,u=arguments.length,c=!1;for("boolean"==typeof a&&(c=a,a=arguments[s]||{},s++),"object"==typeof a||yt.isFunction(a)||(a={}),s===u&&(a=this,s--);s<u;s++)if(null!=(t=arguments[s]))for(e in t)n=a[e],r=t[e],a!==r&&(c&&r&&(yt.isPlainObject(r)||(i=yt.isArray(r)))?(i?(i=!1,o=n&&yt.isArray(n)?n:[]):o=n&&yt.isPlainObject(n)?n:{},a[e]=yt.extend(c,o,r)):void 0!==r&&(a[e]=r));return a},yt.extend({expando:"jQuery"+(mt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(t){throw new Error(t)},noop:function(){},isFunction:function(t){return"function"===yt.type(t)},isArray:Array.isArray,isWindow:function(t){return null!=t&&t===t.window},isNumeric:function(t){var e=yt.type(t);return("number"===e||"string"===e)&&!isNaN(t-parseFloat(t))},isPlainObject:function(t){var e,n;return!(!t||"[object Object]"!==pt.call(t))&&(!(e=at(t))||(n=dt.call(e,"constructor")&&e.constructor,"function"==typeof n&&ht.call(n)===vt))},isEmptyObject:function(t){var e;for(e in t)return!1;return!0},type:function(t){return null==t?t+"":"object"==typeof t||"function"==typeof t?ft[pt.call(t)]||"object":typeof t},globalEval:function(t){a(t)},camelCase:function(t){return t.replace(_t,"ms-").replace(wt,xt)},nodeName:function(t,e){return t.nodeName&&t.nodeName.toLowerCase()===e.toLowerCase()},each:function(t,e){var n,r=0;if(s(t))for(n=t.length;r<n&&e.call(t[r],r,t[r])!==!1;r++);else for(r in t)if(e.call(t[r],r,t[r])===!1)break;return t},trim:function(t){return null==t?"":(t+"").replace(bt,"")},makeArray:function(t,e){var n=e||[];return null!=t&&(s(Object(t))?yt.merge(n,"string"==typeof t?[t]:t):ct.call(n,t)),n},inArray:function(t,e,n){return null==e?-1:lt.call(e,t,n)},merge:function(t,e){for(var n=+e.length,r=0,i=t.length;r<n;r++)t[i++]=e[r];return t.length=i,t},grep:function(t,e,n){for(var r,i=[],o=0,a=t.length,s=!n;o<a;o++)r=!e(t[o],o),r!==s&&i.push(t[o]);return i},map:function(t,e,n){var r,i,o=0,a=[];if(s(t))for(r=t.length;o<r;o++)i=e(t[o],o,n),null!=i&&a.push(i);else for(o in t)i=e(t[o],o,n),null!=i&&a.push(i);return ut.apply([],a)},guid:1,proxy:function(t,e){var n,r,i;if("string"==typeof e&&(n=t[e],e=t,t=n),yt.isFunction(t))return r=st.call(arguments,2),i=function(){return t.apply(e||this,r.concat(st.call(arguments)))},i.guid=t.guid=t.guid||yt.guid++,i},now:Date.now,support:gt}),"function"==typeof Symbol&&(yt.fn[Symbol.iterator]=it[Symbol.iterator]),yt.each("Boolean Number String Function Array Date RegExp Object Error Symbol".split(" "),function(t,e){ft["[object "+e+"]"]=e.toLowerCase()});var Ct=/*! * Sizzle CSS Selector Engine v2.3.3 * https://sizzlejs.com/ * * Copyright jQuery Foundation and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2016-08-08 */ function(t){function e(t,e,n,r){var i,o,a,s,u,c,l,p=e&&e.ownerDocument,h=e?e.nodeType:9;if(n=n||[],"string"!=typeof t||!t||1!==h&&9!==h&&11!==h)return n;if(!r&&((e?e.ownerDocument||e:H)!==D&&N(e),e=e||D,R)){if(11!==h&&(u=mt.exec(t)))if(i=u[1]){if(9===h){if(!(a=e.getElementById(i)))return n;if(a.id===i)return n.push(a),n}else if(p&&(a=p.getElementById(i))&&q(e,a)&&a.id===i)return n.push(a),n}else{if(u[2])return Y.apply(n,e.getElementsByTagName(t)),n;if((i=u[3])&&x.getElementsByClassName&&e.getElementsByClassName)return Y.apply(n,e.getElementsByClassName(i)),n}if(x.qsa&&!V[t+" "]&&(!L||!L.test(t))){if(1!==h)p=e,l=t;else if("object"!==e.nodeName.toLowerCase()){for((s=e.getAttribute("id"))?s=s.replace(wt,xt):e.setAttribute("id",s=M),c=k(t),o=c.length;o--;)c[o]="#"+s+" "+d(c[o]);l=c.join(","),p=yt.test(t)&&f(e.parentNode)||e}if(l)try{return Y.apply(n,p.querySelectorAll(l)),n}catch(t){}finally{s===M&&e.removeAttribute("id")}}}return E(t.replace(st,"$1"),e,n,r)}function n(){function t(n,r){return e.push(n+" ")>C.cacheLength&&delete t[e.shift()],t[n+" "]=r}var e=[];return t}function r(t){return t[M]=!0,t}function i(t){var e=D.createElement("fieldset");try{return!!t(e)}catch(t){return!1}finally{e.parentNode&&e.parentNode.removeChild(e),e=null}}function o(t,e){for(var n=t.split("|"),r=n.length;r--;)C.attrHandle[n[r]]=e}function a(t,e){var n=e&&t,r=n&&1===t.nodeType&&1===e.nodeType&&t.sourceIndex-e.sourceIndex;if(r)return r;if(n)for(;n=n.nextSibling;)if(n===e)return-1;return t?1:-1}function s(t){return function(e){var n=e.nodeName.toLowerCase();return"input"===n&&e.type===t}}function u(t){return function(e){var n=e.nodeName.toLowerCase();return("input"===n||"button"===n)&&e.type===t}}function c(t){return function(e){return"form"in e?e.parentNode&&e.disabled===!1?"label"in e?"label"in e.parentNode?e.parentNode.disabled===t:e.disabled===t:e.isDisabled===t||e.isDisabled!==!t&&Tt(e)===t:e.disabled===t:"label"in e&&e.disabled===t}}function l(t){return r(function(e){return e=+e,r(function(n,r){for(var i,o=t([],n.length,e),a=o.length;a--;)n[i=o[a]]&&(n[i]=!(r[i]=n[i]))})})}function f(t){return t&&"undefined"!=typeof t.getElementsByTagName&&t}function p(){}function d(t){for(var e=0,n=t.length,r="";e<n;e++)r+=t[e].value;return r}function h(t,e,n){var r=e.dir,i=e.next,o=i||r,a=n&&"parentNode"===o,s=U++;return e.first?function(e,n,i){for(;e=e[r];)if(1===e.nodeType||a)return t(e,n,i);return!1}:function(e,n,u){var c,l,f,p=[B,s];if(u){for(;e=e[r];)if((1===e.nodeType||a)&&t(e,n,u))return!0}else for(;e=e[r];)if(1===e.nodeType||a)if(f=e[M]||(e[M]={}),l=f[e.uniqueID]||(f[e.uniqueID]={}),i&&i===e.nodeName.toLowerCase())e=e[r]||e;else{if((c=l[o])&&c[0]===B&&c[1]===s)return p[2]=c[2];if(l[o]=p,p[2]=t(e,n,u))return!0}return!1}}function v(t){return t.length>1?function(e,n,r){for(var i=t.length;i--;)if(!t[i](e,n,r))return!1;return!0}:t[0]}function g(t,n,r){for(var i=0,o=n.length;i<o;i++)e(t,n[i],r);return r}function m(t,e,n,r,i){for(var o,a=[],s=0,u=t.length,c=null!=e;s<u;s++)(o=t[s])&&(n&&!n(o,r,i)||(a.push(o),c&&e.push(s)));return a}function y(t,e,n,i,o,a){return i&&!i[M]&&(i=y(i)),o&&!o[M]&&(o=y(o,a)),r(function(r,a,s,u){var c,l,f,p=[],d=[],h=a.length,v=r||g(e||"*",s.nodeType?[s]:s,[]),y=!t||!r&&e?v:m(v,p,t,s,u),b=n?o||(r?t:h||i)?[]:a:y;if(n&&n(y,b,s,u),i)for(c=m(b,d),i(c,[],s,u),l=c.length;l--;)(f=c[l])&&(b[d[l]]=!(y[d[l]]=f));if(r){if(o||t){if(o){for(c=[],l=b.length;l--;)(f=b[l])&&c.push(y[l]=f);o(null,b=[],c,u)}for(l=b.length;l--;)(f=b[l])&&(c=o?tt(r,f):p[l])>-1&&(r[c]=!(a[c]=f))}}else b=m(b===a?b.splice(h,b.length):b),o?o(null,a,b,u):Y.apply(a,b)})}function b(t){for(var e,n,r,i=t.length,o=C.relative[t[0].type],a=o||C.relative[" "],s=o?1:0,u=h(function(t){return t===e},a,!0),c=h(function(t){return tt(e,t)>-1},a,!0),l=[function(t,n,r){var i=!o&&(r||n!==S)||((e=n).nodeType?u(t,n,r):c(t,n,r));return e=null,i}];s<i;s++)if(n=C.relative[t[s].type])l=[h(v(l),n)];else{if(n=C.filter[t[s].type].apply(null,t[s].matches),n[M]){for(r=++s;r<i&&!C.relative[t[r].type];r++);return y(s>1&&v(l),s>1&&d(t.slice(0,s-1).concat({value:" "===t[s-2].type?"*":""})).replace(st,"$1"),n,s<r&&b(t.slice(s,r)),r<i&&b(t=t.slice(r)),r<i&&d(t))}l.push(n)}return v(l)}function _(t,n){var i=n.length>0,o=t.length>0,a=function(r,a,s,u,c){var l,f,p,d=0,h="0",v=r&&[],g=[],y=S,b=r||o&&C.find.TAG("*",c),_=B+=null==y?1:Math.random()||.1,w=b.length;for(c&&(S=a===D||a||c);h!==w&&null!=(l=b[h]);h++){if(o&&l){for(f=0,a||l.ownerDocument===D||(N(l),s=!R);p=t[f++];)if(p(l,a||D,s)){u.push(l);break}c&&(B=_)}i&&((l=!p&&l)&&d--,r&&v.push(l))}if(d+=h,i&&h!==d){for(f=0;p=n[f++];)p(v,g,a,s);if(r){if(d>0)for(;h--;)v[h]||g[h]||(g[h]=G.call(u));g=m(g)}Y.apply(u,g),c&&!r&&g.length>0&&d+n.length>1&&e.uniqueSort(u)}return c&&(B=_,S=y),v};return i?r(a):a}var w,x,C,T,$,k,A,E,S,O,j,N,D,I,R,L,P,F,q,M="sizzle"+1*new Date,H=t.document,B=0,U=0,W=n(),z=n(),V=n(),X=function(t,e){return t===e&&(j=!0),0},K={}.hasOwnProperty,J=[],G=J.pop,Z=J.push,Y=J.push,Q=J.slice,tt=function(t,e){for(var n=0,r=t.length;n<r;n++)if(t[n]===e)return n;return-1},et="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",nt="[\\x20\\t\\r\\n\\f]",rt="(?:\\\\.|[\\w-]|[^\0-\\xa0])+",it="\\["+nt+"*("+rt+")(?:"+nt+"*([*^$|!~]?=)"+nt+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+rt+"))|)"+nt+"*\\]",ot=":("+rt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+it+")*)|.*)\\)|)",at=new RegExp(nt+"+","g"),st=new RegExp("^"+nt+"+|((?:^|[^\\\\])(?:\\\\.)*)"+nt+"+$","g"),ut=new RegExp("^"+nt+"*,"+nt+"*"),ct=new RegExp("^"+nt+"*([>+~]|"+nt+")"+nt+"*"),lt=new RegExp("="+nt+"*([^\\]'\"]*?)"+nt+"*\\]","g"),ft=new RegExp(ot),pt=new RegExp("^"+rt+"$"),dt={ID:new RegExp("^#("+rt+")"),CLASS:new RegExp("^\\.("+rt+")"),TAG:new RegExp("^("+rt+"|[*])"),ATTR:new RegExp("^"+it),PSEUDO:new RegExp("^"+ot),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+nt+"*(even|odd|(([+-]|)(\\d*)n|)"+nt+"*(?:([+-]|)"+nt+"*(\\d+)|))"+nt+"*\\)|)","i"),bool:new RegExp("^(?:"+et+")$","i"),needsContext:new RegExp("^"+nt+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+nt+"*((?:-\\d)?\\d*)"+nt+"*\\)|)(?=[^-]|$)","i")},ht=/^(?:input|select|textarea|button)$/i,vt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,mt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,yt=/[+~]/,bt=new RegExp("\\\\([\\da-f]{1,6}"+nt+"?|("+nt+")|.)","ig"),_t=function(t,e,n){var r="0x"+e-65536;return r!==r||n?e:r<0?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},wt=/([\0-\x1f\x7f]|^-?\d)|^-$|[^\0-\x1f\x7f-\uFFFF\w-]/g,xt=function(t,e){return e?"\0"===t?"�":t.slice(0,-1)+"\\"+t.charCodeAt(t.length-1).toString(16)+" ":"\\"+t},Ct=function(){N()},Tt=h(function(t){return t.disabled===!0&&("form"in t||"label"in t)},{dir:"parentNode",next:"legend"});try{Y.apply(J=Q.call(H.childNodes),H.childNodes),J[H.childNodes.length].nodeType}catch(t){Y={apply:J.length?function(t,e){Z.apply(t,Q.call(e))}:function(t,e){for(var n=t.length,r=0;t[n++]=e[r++];);t.length=n-1}}}x=e.support={},$=e.isXML=function(t){var e=t&&(t.ownerDocument||t).documentElement;return!!e&&"HTML"!==e.nodeName},N=e.setDocument=function(t){var e,n,r=t?t.ownerDocument||t:H;return r!==D&&9===r.nodeType&&r.documentElement?(D=r,I=D.documentElement,R=!$(D),H!==D&&(n=D.defaultView)&&n.top!==n&&(n.addEventListener?n.addEventListener("unload",Ct,!1):n.attachEvent&&n.attachEvent("onunload",Ct)),x.attributes=i(function(t){return t.className="i",!t.getAttribute("className")}),x.getElementsByTagName=i(function(t){return t.appendChild(D.createComment("")),!t.getElementsByTagName("*").length}),x.getElementsByClassName=gt.test(D.getElementsByClassName),x.getById=i(function(t){return I.appendChild(t).id=M,!D.getElementsByName||!D.getElementsByName(M).length}),x.getById?(C.filter.ID=function(t){var e=t.replace(bt,_t);return function(t){return t.getAttribute("id")===e}},C.find.ID=function(t,e){if("undefined"!=typeof e.getElementById&&R){var n=e.getElementById(t);return n?[n]:[]}}):(C.filter.ID=function(t){var e=t.replace(bt,_t);return function(t){var n="undefined"!=typeof t.getAttributeNode&&t.getAttributeNode("id");return n&&n.value===e}},C.find.ID=function(t,e){if("undefined"!=typeof e.getElementById&&R){var n,r,i,o=e.getElementById(t);if(o){if(n=o.getAttributeNode("id"),n&&n.value===t)return[o];for(i=e.getElementsByName(t),r=0;o=i[r++];)if(n=o.getAttributeNode("id"),n&&n.value===t)return[o]}return[]}}),C.find.TAG=x.getElementsByTagName?function(t,e){return"undefined"!=typeof e.getElementsByTagName?e.getElementsByTagName(t):x.qsa?e.querySelectorAll(t):void 0}:function(t,e){var n,r=[],i=0,o=e.getElementsByTagName(t);if("*"===t){for(;n=o[i++];)1===n.nodeType&&r.push(n);return r}return o},C.find.CLASS=x.getElementsByClassName&&function(t,e){if("undefined"!=typeof e.getElementsByClassName&&R)return e.getElementsByClassName(t)},P=[],L=[],(x.qsa=gt.test(D.querySelectorAll))&&(i(function(t){I.appendChild(t).innerHTML="<a id='"+M+"'></a><select id='"+M+"-\r\\' msallowcapture=''><option selected=''></option></select>",t.querySelectorAll("[msallowcapture^='']").length&&L.push("[*^$]="+nt+"*(?:''|\"\")"),t.querySelectorAll("[selected]").length||L.push("\\["+nt+"*(?:value|"+et+")"),t.querySelectorAll("[id~="+M+"-]").length||L.push("~="),t.querySelectorAll(":checked").length||L.push(":checked"),t.querySelectorAll("a#"+M+"+*").length||L.push(".#.+[+~]")}),i(function(t){t.innerHTML="<a href='' disabled='disabled'></a><select disabled='disabled'><option/></select>";var e=D.createElement("input");e.setAttribute("type","hidden"),t.appendChild(e).setAttribute("name","D"),t.querySelectorAll("[name=d]").length&&L.push("name"+nt+"*[*^$|!~]?="),2!==t.querySelectorAll(":enabled").length&&L.push(":enabled",":disabled"),I.appendChild(t).disabled=!0,2!==t.querySelectorAll(":disabled").length&&L.push(":enabled",":disabled"),t.querySelectorAll("*,:x"),L.push(",.*:")})),(x.matchesSelector=gt.test(F=I.matches||I.webkitMatchesSelector||I.mozMatchesSelector||I.oMatchesSelector||I.msMatchesSelector))&&i(function(t){x.disconnectedMatch=F.call(t,"*"),F.call(t,"[s!='']:x"),P.push("!=",ot)}),L=L.length&&new RegExp(L.join("|")),P=P.length&&new RegExp(P.join("|")),e=gt.test(I.compareDocumentPosition),q=e||gt.test(I.contains)?function(t,e){var n=9===t.nodeType?t.documentElement:t,r=e&&e.parentNode;return t===r||!(!r||1!==r.nodeType||!(n.contains?n.contains(r):t.compareDocumentPosition&&16&t.compareDocumentPosition(r)))}:function(t,e){if(e)for(;e=e.parentNode;)if(e===t)return!0;return!1},X=e?function(t,e){if(t===e)return j=!0,0;var n=!t.compareDocumentPosition-!e.compareDocumentPosition;return n?n:(n=(t.ownerDocument||t)===(e.ownerDocument||e)?t.compareDocumentPosition(e):1,1&n||!x.sortDetached&&e.compareDocumentPosition(t)===n?t===D||t.ownerDocument===H&&q(H,t)?-1:e===D||e.ownerDocument===H&&q(H,e)?1:O?tt(O,t)-tt(O,e):0:4&n?-1:1)}:function(t,e){if(t===e)return j=!0,0;var n,r=0,i=t.parentNode,o=e.parentNode,s=[t],u=[e];if(!i||!o)return t===D?-1:e===D?1:i?-1:o?1:O?tt(O,t)-tt(O,e):0;if(i===o)return a(t,e);for(n=t;n=n.parentNode;)s.unshift(n);for(n=e;n=n.parentNode;)u.unshift(n);for(;s[r]===u[r];)r++;return r?a(s[r],u[r]):s[r]===H?-1:u[r]===H?1:0},D):D},e.matches=function(t,n){return e(t,null,null,n)},e.matchesSelector=function(t,n){if((t.ownerDocument||t)!==D&&N(t),n=n.replace(lt,"='$1']"),x.matchesSelector&&R&&!V[n+" "]&&(!P||!P.test(n))&&(!L||!L.test(n)))try{var r=F.call(t,n);if(r||x.disconnectedMatch||t.document&&11!==t.document.nodeType)return r}catch(t){}return e(n,D,null,[t]).length>0},e.contains=function(t,e){return(t.ownerDocument||t)!==D&&N(t),q(t,e)},e.attr=function(t,e){(t.ownerDocument||t)!==D&&N(t);var n=C.attrHandle[e.toLowerCase()],r=n&&K.call(C.attrHandle,e.toLowerCase())?n(t,e,!R):void 0;return void 0!==r?r:x.attributes||!R?t.getAttribute(e):(r=t.getAttributeNode(e))&&r.specified?r.value:null},e.escape=function(t){return(t+"").replace(wt,xt)},e.error=function(t){throw new Error("Syntax error, unrecognized expression: "+t)},e.uniqueSort=function(t){var e,n=[],r=0,i=0;if(j=!x.detectDuplicates,O=!x.sortStable&&t.slice(0),t.sort(X),j){for(;e=t[i++];)e===t[i]&&(r=n.push(i));for(;r--;)t.splice(n[r],1)}return O=null,t},T=e.getText=function(t){var e,n="",r=0,i=t.nodeType;if(i){if(1===i||9===i||11===i){if("string"==typeof t.textContent)return t.textContent;for(t=t.firstChild;t;t=t.nextSibling)n+=T(t)}else if(3===i||4===i)return t.nodeValue}else for(;e=t[r++];)n+=T(e);return n},C=e.selectors={cacheLength:50,createPseudo:r,match:dt,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(t){return t[1]=t[1].replace(bt,_t),t[3]=(t[3]||t[4]||t[5]||"").replace(bt,_t),"~="===t[2]&&(t[3]=" "+t[3]+" "),t.slice(0,4)},CHILD:function(t){return t[1]=t[1].toLowerCase(),"nth"===t[1].slice(0,3)?(t[3]||e.error(t[0]),t[4]=+(t[4]?t[5]+(t[6]||1):2*("even"===t[3]||"odd"===t[3])),t[5]=+(t[7]+t[8]||"odd"===t[3])):t[3]&&e.error(t[0]),t},PSEUDO:function(t){var e,n=!t[6]&&t[2];return dt.CHILD.test(t[0])?null:(t[3]?t[2]=t[4]||t[5]||"":n&&ft.test(n)&&(e=k(n,!0))&&(e=n.indexOf(")",n.length-e)-n.length)&&(t[0]=t[0].slice(0,e),t[2]=n.slice(0,e)),t.slice(0,3))}},filter:{TAG:function(t){var e=t.replace(bt,_t).toLowerCase();return"*"===t?function(){return!0}:function(t){return t.nodeName&&t.nodeName.toLowerCase()===e}},CLASS:function(t){var e=W[t+" "];return e||(e=new RegExp("(^|"+nt+")"+t+"("+nt+"|$)"))&&W(t,function(t){return e.test("string"==typeof t.className&&t.className||"undefined"!=typeof t.getAttribute&&t.getAttribute("class")||"")})},ATTR:function(t,n,r){return function(i){var o=e.attr(i,t);return null==o?"!="===n:!n||(o+="","="===n?o===r:"!="===n?o!==r:"^="===n?r&&0===o.indexOf(r):"*="===n?r&&o.indexOf(r)>-1:"$="===n?r&&o.slice(-r.length)===r:"~="===n?(" "+o.replace(at," ")+" ").indexOf(r)>-1:"|="===n&&(o===r||o.slice(0,r.length+1)===r+"-"))}},CHILD:function(t,e,n,r,i){var o="nth"!==t.slice(0,3),a="last"!==t.slice(-4),s="of-type"===e;return 1===r&&0===i?function(t){return!!t.parentNode}:function(e,n,u){var c,l,f,p,d,h,v=o!==a?"nextSibling":"previousSibling",g=e.parentNode,m=s&&e.nodeName.toLowerCase(),y=!u&&!s,b=!1;if(g){if(o){for(;v;){for(p=e;p=p[v];)if(s?p.nodeName.toLowerCase()===m:1===p.nodeType)return!1;h=v="only"===t&&!h&&"nextSibling"}return!0}if(h=[a?g.firstChild:g.lastChild],a&&y){for(p=g,f=p[M]||(p[M]={}),l=f[p.uniqueID]||(f[p.uniqueID]={}),c=l[t]||[],d=c[0]===B&&c[1],b=d&&c[2],p=d&&g.childNodes[d];p=++d&&p&&p[v]||(b=d=0)||h.pop();)if(1===p.nodeType&&++b&&p===e){l[t]=[B,d,b];break}}else if(y&&(p=e,f=p[M]||(p[M]={}),l=f[p.uniqueID]||(f[p.uniqueID]={}),c=l[t]||[],d=c[0]===B&&c[1],b=d),b===!1)for(;(p=++d&&p&&p[v]||(b=d=0)||h.pop())&&((s?p.nodeName.toLowerCase()!==m:1!==p.nodeType)||!++b||(y&&(f=p[M]||(p[M]={}),l=f[p.uniqueID]||(f[p.uniqueID]={}),l[t]=[B,b]),p!==e)););return b-=i,b===r||b%r===0&&b/r>=0}}},PSEUDO:function(t,n){var i,o=C.pseudos[t]||C.setFilters[t.toLowerCase()]||e.error("unsupported pseudo: "+t);return o[M]?o(n):o.length>1?(i=[t,t,"",n],C.setFilters.hasOwnProperty(t.toLowerCase())?r(function(t,e){for(var r,i=o(t,n),a=i.length;a--;)r=tt(t,i[a]),t[r]=!(e[r]=i[a])}):function(t){return o(t,0,i)}):o}},pseudos:{not:r(function(t){var e=[],n=[],i=A(t.replace(st,"$1"));return i[M]?r(function(t,e,n,r){for(var o,a=i(t,null,r,[]),s=t.length;s--;)(o=a[s])&&(t[s]=!(e[s]=o))}):function(t,r,o){return e[0]=t,i(e,null,o,n),e[0]=null,!n.pop()}}),has:r(function(t){return function(n){return e(t,n).length>0}}),contains:r(function(t){return t=t.replace(bt,_t),function(e){return(e.textContent||e.innerText||T(e)).indexOf(t)>-1}}),lang:r(function(t){return pt.test(t||"")||e.error("unsupported lang: "+t),t=t.replace(bt,_t).toLowerCase(),function(e){var n;do if(n=R?e.lang:e.getAttribute("xml:lang")||e.getAttribute("lang"))return n=n.toLowerCase(),n===t||0===n.indexOf(t+"-");while((e=e.parentNode)&&1===e.nodeType);return!1}}),target:function(e){var n=t.location&&t.location.hash;return n&&n.slice(1)===e.id},root:function(t){return t===I},focus:function(t){return t===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(t.type||t.href||~t.tabIndex)},enabled:c(!1),disabled:c(!0),checked:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&!!t.checked||"option"===e&&!!t.selected},selected:function(t){return t.parentNode&&t.parentNode.selectedIndex,t.selected===!0},empty:function(t){for(t=t.firstChild;t;t=t.nextSibling)if(t.nodeType<6)return!1;return!0},parent:function(t){return!C.pseudos.empty(t)},header:function(t){return vt.test(t.nodeName)},input:function(t){return ht.test(t.nodeName)},button:function(t){var e=t.nodeName.toLowerCase();return"input"===e&&"button"===t.type||"button"===e},text:function(t){var e;return"input"===t.nodeName.toLowerCase()&&"text"===t.type&&(null==(e=t.getAttribute("type"))||"text"===e.toLowerCase())},first:l(function(){return[0]}),last:l(function(t,e){return[e-1]}),eq:l(function(t,e,n){return[n<0?n+e:n]}),even:l(function(t,e){for(var n=0;n<e;n+=2)t.push(n);return t}),odd:l(function(t,e){for(var n=1;n<e;n+=2)t.push(n);return t}),lt:l(function(t,e,n){for(var r=n<0?n+e:n;--r>=0;)t.push(r);return t}),gt:l(function(t,e,n){for(var r=n<0?n+e:n;++r<e;)t.push(r);return t})}},C.pseudos.nth=C.pseudos.eq;for(w in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})C.pseudos[w]=s(w);for(w in{submit:!0,reset:!0})C.pseudos[w]=u(w);return p.prototype=C.filters=C.pseudos,C.setFilters=new p,k=e.tokenize=function(t,n){var r,i,o,a,s,u,c,l=z[t+" "];if(l)return n?0:l.slice(0);for(s=t,u=[],c=C.preFilter;s;){r&&!(i=ut.exec(s))||(i&&(s=s.slice(i[0].length)||s),u.push(o=[])),r=!1,(i=ct.exec(s))&&(r=i.shift(),o.push({value:r,type:i[0].replace(st," ")}),s=s.slice(r.length));for(a in C.filter)!(i=dt[a].exec(s))||c[a]&&!(i=c[a](i))||(r=i.shift(),o.push({value:r,type:a,matches:i}),s=s.slice(r.length));if(!r)break}return n?s.length:s?e.error(t):z(t,u).slice(0)},A=e.compile=function(t,e){var n,r=[],i=[],o=V[t+" "];if(!o){for(e||(e=k(t)),n=e.length;n--;)o=b(e[n]),o[M]?r.push(o):i.push(o);o=V(t,_(i,r)),o.selector=t}return o},E=e.select=function(t,e,n,r){var i,o,a,s,u,c="function"==typeof t&&t,l=!r&&k(t=c.selector||t);if(n=n||[],1===l.length){if(o=l[0]=l[0].slice(0),o.length>2&&"ID"===(a=o[0]).type&&9===e.nodeType&&R&&C.relative[o[1].type]){if(e=(C.find.ID(a.matches[0].replace(bt,_t),e)||[])[0],!e)return n;c&&(e=e.parentNode),t=t.slice(o.shift().value.length)}for(i=dt.needsContext.test(t)?0:o.length;i--&&(a=o[i],!C.relative[s=a.type]);)if((u=C.find[s])&&(r=u(a.matches[0].replace(bt,_t),yt.test(o[0].type)&&f(e.parentNode)||e))){if(o.splice(i,1),t=r.length&&d(o),!t)return Y.apply(n,r),n;break}}return(c||A(t,l))(r,e,!R,n,!e||yt.test(t)&&f(e.parentNode)||e),n},x.sortStable=M.split("").sort(X).join("")===M,x.detectDuplicates=!!j,N(),x.sortDetached=i(function(t){return 1&t.compareDocumentPosition(D.createElement("fieldset"))}),i(function(t){return t.innerHTML="<a href='#'></a>","#"===t.firstChild.getAttribute("href")})||o("type|href|height|width",function(t,e,n){if(!n)return t.getAttribute(e,"type"===e.toLowerCase()?1:2)}),x.attributes&&i(function(t){return t.innerHTML="<input/>",t.firstChild.setAttribute("value",""),""===t.firstChild.getAttribute("value")})||o("value",function(t,e,n){if(!n&&"input"===t.nodeName.toLowerCase())return t.defaultValue}),i(function(t){return null==t.getAttribute("disabled")})||o(et,function(t,e,n){var r;if(!n)return t[e]===!0?e.toLowerCase():(r=t.getAttributeNode(e))&&r.specified?r.value:null}),e}(n);yt.find=Ct,yt.expr=Ct.selectors,yt.expr[":"]=yt.expr.pseudos,yt.uniqueSort=yt.unique=Ct.uniqueSort,yt.text=Ct.getText,yt.isXMLDoc=Ct.isXML,yt.contains=Ct.contains,yt.escapeSelector=Ct.escape;var Tt=function(t,e,n){for(var r=[],i=void 0!==n;(t=t[e])&&9!==t.nodeType;)if(1===t.nodeType){if(i&&yt(t).is(n))break;r.push(t)}return r},$t=function(t,e){for(var n=[];t;t=t.nextSibling)1===t.nodeType&&t!==e&&n.push(t);return n},kt=yt.expr.match.needsContext,At=/^<([a-z][^\/\0>:\x20\t\r\n\f]*)[\x20\t\r\n\f]*\/?>(?:<\/\1>|)$/i,Et=/^.[^:#\[\.,]*$/;yt.filter=function(t,e,n){var r=e[0];return n&&(t=":not("+t+")"),1===e.length&&1===r.nodeType?yt.find.matchesSelector(r,t)?[r]:[]:yt.find.matches(t,yt.grep(e,function(t){return 1===t.nodeType}))},yt.fn.extend({find:function(t){var e,n,r=this.length,i=this;if("string"!=typeof t)return this.pushStack(yt(t).filter(function(){for(e=0;e<r;e++)if(yt.contains(i[e],this))return!0}));for(n=this.pushStack([]),e=0;e<r;e++)yt.find(t,i[e],n);return r>1?yt.uniqueSort(n):n},filter:function(t){return this.pushStack(u(this,t||[],!1))},not:function(t){return this.pushStack(u(this,t||[],!0))},is:function(t){return!!u(this,"string"==typeof t&&kt.test(t)?yt(t):t||[],!1).length}});var St,Ot=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]+))$/,jt=yt.fn.init=function(t,e,n){var r,i;if(!t)return this;if(n=n||St,"string"==typeof t){if(r="<"===t[0]&&">"===t[t.length-1]&&t.length>=3?[null,t,null]:Ot.exec(t),!r||!r[1]&&e)return!e||e.jquery?(e||n).find(t):this.constructor(e).find(t);if(r[1]){if(e=e instanceof yt?e[0]:e,yt.merge(this,yt.parseHTML(r[1],e&&e.nodeType?e.ownerDocument||e:ot,!0)),At.test(r[1])&&yt.isPlainObject(e))for(r in e)yt.isFunction(this[r])?this[r](e[r]):this.attr(r,e[r]);return this}return i=ot.getElementById(r[2]),i&&(this[0]=i,this.length=1),this}return t.nodeType?(this[0]=t,this.length=1,this):yt.isFunction(t)?void 0!==n.ready?n.ready(t):t(yt):yt.makeArray(t,this)};jt.prototype=yt.fn,St=yt(ot);var Nt=/^(?:parents|prev(?:Until|All))/,Dt={children:!0,contents:!0,next:!0,prev:!0};yt.fn.extend({has:function(t){var e=yt(t,this),n=e.length;return this.filter(function(){for(var t=0;t<n;t++)if(yt.contains(this,e[t]))return!0})},closest:function(t,e){var n,r=0,i=this.length,o=[],a="string"!=typeof t&&yt(t);if(!kt.test(t))for(;r<i;r++)for(n=this[r];n&&n!==e;n=n.parentNode)if(n.nodeType<11&&(a?a.index(n)>-1:1===n.nodeType&&yt.find.matchesSelector(n,t))){o.push(n);break}return this.pushStack(o.length>1?yt.uniqueSort(o):o)},index:function(t){return t?"string"==typeof t?lt.call(yt(t),this[0]):lt.call(this,t.jquery?t[0]:t):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(t,e){return this.pushStack(yt.uniqueSort(yt.merge(this.get(),yt(t,e))))},addBack:function(t){return this.add(null==t?this.prevObject:this.prevObject.filter(t))}}),yt.each({parent:function(t){var e=t.parentNode;return e&&11!==e.nodeType?e:null},parents:function(t){return Tt(t,"parentNode")},parentsUntil:function(t,e,n){return Tt(t,"parentNode",n)},next:function(t){return c(t,"nextSibling")},prev:function(t){return c(t,"previousSibling")},nextAll:function(t){return Tt(t,"nextSibling")},prevAll:function(t){return Tt(t,"previousSibling")},nextUntil:function(t,e,n){return Tt(t,"nextSibling",n)},prevUntil:function(t,e,n){return Tt(t,"previousSibling",n)},siblings:function(t){return $t((t.parentNode||{}).firstChild,t)},children:function(t){return $t(t.firstChild)},contents:function(t){return t.contentDocument||yt.merge([],t.childNodes)}},function(t,e){yt.fn[t]=function(n,r){var i=yt.map(this,e,n);return"Until"!==t.slice(-5)&&(r=n),r&&"string"==typeof r&&(i=yt.filter(r,i)),this.length>1&&(Dt[t]||yt.uniqueSort(i),Nt.test(t)&&i.reverse()),this.pushStack(i)}});var It=/[^\x20\t\r\n\f]+/g;yt.Callbacks=function(t){t="string"==typeof t?l(t):yt.extend({},t);var e,n,r,i,o=[],a=[],s=-1,u=function(){for(i=t.once,r=e=!0;a.length;s=-1)for(n=a.shift();++s<o.length;)o[s].apply(n[0],n[1])===!1&&t.stopOnFalse&&(s=o.length,n=!1);t.memory||(n=!1),e=!1,i&&(o=n?[]:"")},c={add:function(){return o&&(n&&!e&&(s=o.length-1,a.push(n)),function e(n){yt.each(n,function(n,r){yt.isFunction(r)?t.unique&&c.has(r)||o.push(r):r&&r.length&&"string"!==yt.type(r)&&e(r)})}(arguments),n&&!e&&u()),this},remove:function(){return yt.each(arguments,function(t,e){for(var n;(n=yt.inArray(e,o,n))>-1;)o.splice(n,1),n<=s&&s--}),this},has:function(t){return t?yt.inArray(t,o)>-1:o.length>0},empty:function(){return o&&(o=[]),this},disable:function(){return i=a=[],o=n="",this},disabled:function(){return!o},lock:function(){return i=a=[],n||e||(o=n=""),this},locked:function(){return!!i},fireWith:function(t,n){return i||(n=n||[],n=[t,n.slice?n.slice():n],a.push(n),e||u()),this},fire:function(){return c.fireWith(this,arguments),this},fired:function(){return!!r}};return c},yt.extend({Deferred:function(t){var e=[["notify","progress",yt.Callbacks("memory"),yt.Callbacks("memory"),2],["resolve","done",yt.Callbacks("once memory"),yt.Callbacks("once memory"),0,"resolved"],["reject","fail",yt.Callbacks("once memory"),yt.Callbacks("once memory"),1,"rejected"]],r="pending",i={state:function(){return r},always:function(){return o.done(arguments).fail(arguments),this},catch:function(t){return i.then(null,t)},pipe:function(){var t=arguments;return yt.Deferred(function(n){yt.each(e,function(e,r){var i=yt.isFunction(t[r[4]])&&t[r[4]];o[r[1]](function(){var t=i&&i.apply(this,arguments);t&&yt.isFunction(t.promise)?t.promise().progress(n.notify).done(n.resolve).fail(n.reject):n[r[0]+"With"](this,i?[t]:arguments)})}),t=null}).promise()},then:function(t,r,i){function o(t,e,r,i){return function(){var s=this,u=arguments,c=function(){var n,c;if(!(t<a)){if(n=r.apply(s,u),n===e.promise())throw new TypeError("Thenable self-resolution");c=n&&("object"==typeof n||"function"==typeof n)&&n.then,yt.isFunction(c)?i?c.call(n,o(a,e,f,i),o(a,e,p,i)):(a++,c.call(n,o(a,e,f,i),o(a,e,p,i),o(a,e,f,e.notifyWith))):(r!==f&&(s=void 0,u=[n]),(i||e.resolveWith)(s,u))}},l=i?c:function(){try{c()}catch(n){yt.Deferred.exceptionHook&&yt.Deferred.exceptionHook(n,l.stackTrace),t+1>=a&&(r!==p&&(s=void 0,u=[n]),e.rejectWith(s,u))}};t?l():(yt.Deferred.getStackHook&&(l.stackTrace=yt.Deferred.getStackHook()),n.setTimeout(l))}}var a=0;return yt.Deferred(function(n){e[0][3].add(o(0,n,yt.isFunction(i)?i:f,n.notifyWith)),e[1][3].add(o(0,n,yt.isFunction(t)?t:f)),e[2][3].add(o(0,n,yt.isFunction(r)?r:p))}).promise()},promise:function(t){return null!=t?yt.extend(t,i):i}},o={};return yt.each(e,function(t,n){var a=n[2],s=n[5];i[n[1]]=a.add,s&&a.add(function(){r=s},e[3-t][2].disable,e[0][2].lock),a.add(n[3].fire),o[n[0]]=function(){return o[n[0]+"With"](this===o?void 0:this,arguments),this},o[n[0]+"With"]=a.fireWith}),i.promise(o),t&&t.call(o,o),o},when:function(t){var e=arguments.length,n=e,r=Array(n),i=st.call(arguments),o=yt.Deferred(),a=function(t){return function(n){r[t]=this,i[t]=arguments.length>1?st.call(arguments):n,--e||o.resolveWith(r,i)}};if(e<=1&&(d(t,o.done(a(n)).resolve,o.reject),"pending"===o.state()||yt.isFunction(i[n]&&i[n].then)))return o.then();for(;n--;)d(i[n],a(n),o.reject);return o.promise()}});var Rt=/^(Eval|Internal|Range|Reference|Syntax|Type|URI)Error$/;yt.Deferred.exceptionHook=function(t,e){n.console&&n.console.warn&&t&&Rt.test(t.name)&&n.console.warn("jQuery.Deferred exception: "+t.message,t.stack,e)},yt.readyException=function(t){n.setTimeout(function(){throw t})};var Lt=yt.Deferred();yt.fn.ready=function(t){return Lt.then(t).catch(function(t){yt.readyException(t)}),this},yt.extend({isReady:!1,readyWait:1,holdReady:function(t){t?yt.readyWait++:yt.ready(!0)},ready:function(t){(t===!0?--yt.readyWait:yt.isReady)||(yt.isReady=!0,t!==!0&&--yt.readyWait>0||Lt.resolveWith(ot,[yt]))}}),yt.ready.then=Lt.then,"complete"===ot.readyState||"loading"!==ot.readyState&&!ot.documentElement.doScroll?n.setTimeout(yt.ready):(ot.addEventListener("DOMContentLoaded",h),n.addEventListener("load",h));var Pt=function(t,e,n,r,i,o,a){var s=0,u=t.length,c=null==n;if("object"===yt.type(n)){i=!0;for(s in n)Pt(t,e,s,n[s],!0,o,a)}else if(void 0!==r&&(i=!0,yt.isFunction(r)||(a=!0),c&&(a?(e.call(t,r),e=null):(c=e,e=function(t,e,n){return c.call(yt(t),n)})),e))for(;s<u;s++)e(t[s],n,a?r:r.call(t[s],s,e(t[s],n)));return i?t:c?e.call(t):u?e(t[0],n):o},Ft=function(t){return 1===t.nodeType||9===t.nodeType||!+t.nodeType};v.uid=1,v.prototype={cache:function(t){var e=t[this.expando];return e||(e={},Ft(t)&&(t.nodeType?t[this.expando]=e:Object.defineProperty(t,this.expando,{value:e,configurable:!0}))),e},set:function(t,e,n){var r,i=this.cache(t);if("string"==typeof e)i[yt.camelCase(e)]=n;else for(r in e)i[yt.camelCase(r)]=e[r];return i},get:function(t,e){return void 0===e?this.cache(t):t[this.expando]&&t[this.expando][yt.camelCase(e)]},access:function(t,e,n){return void 0===e||e&&"string"==typeof e&&void 0===n?this.get(t,e):(this.set(t,e,n),void 0!==n?n:e)},remove:function(t,e){var n,r=t[this.expando];if(void 0!==r){if(void 0!==e){yt.isArray(e)?e=e.map(yt.camelCase):(e=yt.camelCase(e),e=e in r?[e]:e.match(It)||[]),n=e.length;for(;n--;)delete r[e[n]]}(void 0===e||yt.isEmptyObject(r))&&(t.nodeType?t[this.expando]=void 0:delete t[this.expando])}},hasData:function(t){var e=t[this.expando];return void 0!==e&&!yt.isEmptyObject(e)}};var qt=new v,Mt=new v,Ht=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,Bt=/[A-Z]/g;yt.extend({hasData:function(t){return Mt.hasData(t)||qt.hasData(t)},data:function(t,e,n){return Mt.access(t,e,n)},removeData:function(t,e){Mt.remove(t,e)},_data:function(t,e,n){return qt.access(t,e,n)},_removeData:function(t,e){qt.remove(t,e)}}),yt.fn.extend({data:function(t,e){var n,r,i,o=this[0],a=o&&o.attributes;if(void 0===t){if(this.length&&(i=Mt.get(o),1===o.nodeType&&!qt.get(o,"hasDataAttrs"))){for(n=a.length;n--;)a[n]&&(r=a[n].name,0===r.indexOf("data-")&&(r=yt.camelCase(r.slice(5)),m(o,r,i[r])));qt.set(o,"hasDataAttrs",!0)}return i}return"object"==typeof t?this.each(function(){Mt.set(this,t)}):Pt(this,function(e){var n;if(o&&void 0===e){if(n=Mt.get(o,t),void 0!==n)return n;if(n=m(o,t),void 0!==n)return n}else this.each(function(){Mt.set(this,t,e)})},null,e,arguments.length>1,null,!0)},removeData:function(t){return this.each(function(){Mt.remove(this,t)})}}),yt.extend({queue:function(t,e,n){var r;if(t)return e=(e||"fx")+"queue",r=qt.get(t,e),n&&(!r||yt.isArray(n)?r=qt.access(t,e,yt.makeArray(n)):r.push(n)),r||[]},dequeue:function(t,e){e=e||"fx";var n=yt.queue(t,e),r=n.length,i=n.shift(),o=yt._queueHooks(t,e),a=function(){yt.dequeue(t,e)};"inprogress"===i&&(i=n.shift(),r--),i&&("fx"===e&&n.unshift("inprogress"),delete o.stop,i.call(t,a,o)),!r&&o&&o.empty.fire()},_queueHooks:function(t,e){var n=e+"queueHooks";return qt.get(t,n)||qt.access(t,n,{empty:yt.Callbacks("once memory").add(function(){qt.remove(t,[e+"queue",n])})})}}),yt.fn.extend({queue:function(t,e){var n=2;return"string"!=typeof t&&(e=t,t="fx",n--),arguments.length<n?yt.queue(this[0],t):void 0===e?this:this.each(function(){var n=yt.queue(this,t,e);yt._queueHooks(this,t),"fx"===t&&"inprogress"!==n[0]&&yt.dequeue(this,t)})},dequeue:function(t){return this.each(function(){yt.dequeue(this,t)})},clearQueue:function(t){return this.queue(t||"fx",[])},promise:function(t,e){var n,r=1,i=yt.Deferred(),o=this,a=this.length,s=function(){--r||i.resolveWith(o,[o])};for("string"!=typeof t&&(e=t,t=void 0),t=t||"fx";a--;)n=qt.get(o[a],t+"queueHooks"),n&&n.empty&&(r++,n.empty.add(s));return s(),i.promise(e)}});var Ut=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Wt=new RegExp("^(?:([+-])=|)("+Ut+")([a-z%]*)$","i"),zt=["Top","Right","Bottom","Left"],Vt=function(t,e){return t=e||t,"none"===t.style.display||""===t.style.display&&yt.contains(t.ownerDocument,t)&&"none"===yt.css(t,"display")},Xt=function(t,e,n,r){var i,o,a={};for(o in e)a[o]=t.style[o],t.style[o]=e[o];i=n.apply(t,r||[]);for(o in e)t.style[o]=a[o];return i},Kt={};yt.fn.extend({show:function(){return _(this,!0)},hide:function(){return _(this)},toggle:function(t){return"boolean"==typeof t?t?this.show():this.hide():this.each(function(){Vt(this)?yt(this).show():yt(this).hide()})}});var Jt=/^(?:checkbox|radio)$/i,Gt=/<([a-z][^\/\0>\x20\t\r\n\f]+)/i,Zt=/^$|\/(?:java|ecma)script/i,Yt={option:[1,"<select multiple='multiple'>","</select>"],thead:[1,"<table>","</table>"],col:[2,"<table><colgroup>","</colgroup></table>"],tr:[2,"<table><tbody>","</tbody></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:[0,"",""]};Yt.optgroup=Yt.option,Yt.tbody=Yt.tfoot=Yt.colgroup=Yt.caption=Yt.thead,Yt.th=Yt.td; var Qt=/<|&#?\w+;/;!function(){var t=ot.createDocumentFragment(),e=t.appendChild(ot.createElement("div")),n=ot.createElement("input");n.setAttribute("type","radio"),n.setAttribute("checked","checked"),n.setAttribute("name","t"),e.appendChild(n),gt.checkClone=e.cloneNode(!0).cloneNode(!0).lastChild.checked,e.innerHTML="<textarea>x</textarea>",gt.noCloneChecked=!!e.cloneNode(!0).lastChild.defaultValue}();var te=ot.documentElement,ee=/^key/,ne=/^(?:mouse|pointer|contextmenu|drag|drop)|click/,re=/^([^.]*)(?:\.(.+)|)/;yt.event={global:{},add:function(t,e,n,r,i){var o,a,s,u,c,l,f,p,d,h,v,g=qt.get(t);if(g)for(n.handler&&(o=n,n=o.handler,i=o.selector),i&&yt.find.matchesSelector(te,i),n.guid||(n.guid=yt.guid++),(u=g.events)||(u=g.events={}),(a=g.handle)||(a=g.handle=function(e){return"undefined"!=typeof yt&&yt.event.triggered!==e.type?yt.event.dispatch.apply(t,arguments):void 0}),e=(e||"").match(It)||[""],c=e.length;c--;)s=re.exec(e[c])||[],d=v=s[1],h=(s[2]||"").split(".").sort(),d&&(f=yt.event.special[d]||{},d=(i?f.delegateType:f.bindType)||d,f=yt.event.special[d]||{},l=yt.extend({type:d,origType:v,data:r,handler:n,guid:n.guid,selector:i,needsContext:i&&yt.expr.match.needsContext.test(i),namespace:h.join(".")},o),(p=u[d])||(p=u[d]=[],p.delegateCount=0,f.setup&&f.setup.call(t,r,h,a)!==!1||t.addEventListener&&t.addEventListener(d,a)),f.add&&(f.add.call(t,l),l.handler.guid||(l.handler.guid=n.guid)),i?p.splice(p.delegateCount++,0,l):p.push(l),yt.event.global[d]=!0)},remove:function(t,e,n,r,i){var o,a,s,u,c,l,f,p,d,h,v,g=qt.hasData(t)&&qt.get(t);if(g&&(u=g.events)){for(e=(e||"").match(It)||[""],c=e.length;c--;)if(s=re.exec(e[c])||[],d=v=s[1],h=(s[2]||"").split(".").sort(),d){for(f=yt.event.special[d]||{},d=(r?f.delegateType:f.bindType)||d,p=u[d]||[],s=s[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"),a=o=p.length;o--;)l=p[o],!i&&v!==l.origType||n&&n.guid!==l.guid||s&&!s.test(l.namespace)||r&&r!==l.selector&&("**"!==r||!l.selector)||(p.splice(o,1),l.selector&&p.delegateCount--,f.remove&&f.remove.call(t,l));a&&!p.length&&(f.teardown&&f.teardown.call(t,h,g.handle)!==!1||yt.removeEvent(t,d,g.handle),delete u[d])}else for(d in u)yt.event.remove(t,d+e[c],n,r,!0);yt.isEmptyObject(u)&&qt.remove(t,"handle events")}},dispatch:function(t){var e,n,r,i,o,a,s=yt.event.fix(t),u=new Array(arguments.length),c=(qt.get(this,"events")||{})[s.type]||[],l=yt.event.special[s.type]||{};for(u[0]=s,e=1;e<arguments.length;e++)u[e]=arguments[e];if(s.delegateTarget=this,!l.preDispatch||l.preDispatch.call(this,s)!==!1){for(a=yt.event.handlers.call(this,s,c),e=0;(i=a[e++])&&!s.isPropagationStopped();)for(s.currentTarget=i.elem,n=0;(o=i.handlers[n++])&&!s.isImmediatePropagationStopped();)s.rnamespace&&!s.rnamespace.test(o.namespace)||(s.handleObj=o,s.data=o.data,r=((yt.event.special[o.origType]||{}).handle||o.handler).apply(i.elem,u),void 0!==r&&(s.result=r)===!1&&(s.preventDefault(),s.stopPropagation()));return l.postDispatch&&l.postDispatch.call(this,s),s.result}},handlers:function(t,e){var n,r,i,o,a,s=[],u=e.delegateCount,c=t.target;if(u&&c.nodeType&&!("click"===t.type&&t.button>=1))for(;c!==this;c=c.parentNode||this)if(1===c.nodeType&&("click"!==t.type||c.disabled!==!0)){for(o=[],a={},n=0;n<u;n++)r=e[n],i=r.selector+" ",void 0===a[i]&&(a[i]=r.needsContext?yt(i,this).index(c)>-1:yt.find(i,this,null,[c]).length),a[i]&&o.push(r);o.length&&s.push({elem:c,handlers:o})}return c=this,u<e.length&&s.push({elem:c,handlers:e.slice(u)}),s},addProp:function(t,e){Object.defineProperty(yt.Event.prototype,t,{enumerable:!0,configurable:!0,get:yt.isFunction(e)?function(){if(this.originalEvent)return e(this.originalEvent)}:function(){if(this.originalEvent)return this.originalEvent[t]},set:function(e){Object.defineProperty(this,t,{enumerable:!0,configurable:!0,writable:!0,value:e})}})},fix:function(t){return t[yt.expando]?t:new yt.Event(t)},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==k()&&this.focus)return this.focus(),!1},delegateType:"focusin"},blur:{trigger:function(){if(this===k()&&this.blur)return this.blur(),!1},delegateType:"focusout"},click:{trigger:function(){if("checkbox"===this.type&&this.click&&yt.nodeName(this,"input"))return this.click(),!1},_default:function(t){return yt.nodeName(t.target,"a")}},beforeunload:{postDispatch:function(t){void 0!==t.result&&t.originalEvent&&(t.originalEvent.returnValue=t.result)}}}},yt.removeEvent=function(t,e,n){t.removeEventListener&&t.removeEventListener(e,n)},yt.Event=function(t,e){return this instanceof yt.Event?(t&&t.type?(this.originalEvent=t,this.type=t.type,this.isDefaultPrevented=t.defaultPrevented||void 0===t.defaultPrevented&&t.returnValue===!1?T:$,this.target=t.target&&3===t.target.nodeType?t.target.parentNode:t.target,this.currentTarget=t.currentTarget,this.relatedTarget=t.relatedTarget):this.type=t,e&&yt.extend(this,e),this.timeStamp=t&&t.timeStamp||yt.now(),void(this[yt.expando]=!0)):new yt.Event(t,e)},yt.Event.prototype={constructor:yt.Event,isDefaultPrevented:$,isPropagationStopped:$,isImmediatePropagationStopped:$,isSimulated:!1,preventDefault:function(){var t=this.originalEvent;this.isDefaultPrevented=T,t&&!this.isSimulated&&t.preventDefault()},stopPropagation:function(){var t=this.originalEvent;this.isPropagationStopped=T,t&&!this.isSimulated&&t.stopPropagation()},stopImmediatePropagation:function(){var t=this.originalEvent;this.isImmediatePropagationStopped=T,t&&!this.isSimulated&&t.stopImmediatePropagation(),this.stopPropagation()}},yt.each({altKey:!0,bubbles:!0,cancelable:!0,changedTouches:!0,ctrlKey:!0,detail:!0,eventPhase:!0,metaKey:!0,pageX:!0,pageY:!0,shiftKey:!0,view:!0,char:!0,charCode:!0,key:!0,keyCode:!0,button:!0,buttons:!0,clientX:!0,clientY:!0,offsetX:!0,offsetY:!0,pointerId:!0,pointerType:!0,screenX:!0,screenY:!0,targetTouches:!0,toElement:!0,touches:!0,which:function(t){var e=t.button;return null==t.which&&ee.test(t.type)?null!=t.charCode?t.charCode:t.keyCode:!t.which&&void 0!==e&&ne.test(t.type)?1&e?1:2&e?3:4&e?2:0:t.which}},yt.event.addProp),yt.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(t,e){yt.event.special[t]={delegateType:e,bindType:e,handle:function(t){var n,r=this,i=t.relatedTarget,o=t.handleObj;return i&&(i===r||yt.contains(r,i))||(t.type=o.origType,n=o.handler.apply(this,arguments),t.type=e),n}}}),yt.fn.extend({on:function(t,e,n,r){return A(this,t,e,n,r)},one:function(t,e,n,r){return A(this,t,e,n,r,1)},off:function(t,e,n){var r,i;if(t&&t.preventDefault&&t.handleObj)return r=t.handleObj,yt(t.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler),this;if("object"==typeof t){for(i in t)this.off(i,e,t[i]);return this}return e!==!1&&"function"!=typeof e||(n=e,e=void 0),n===!1&&(n=$),this.each(function(){yt.event.remove(this,t,n,e)})}});var ie=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([a-z][^\/\0>\x20\t\r\n\f]*)[^>]*)\/>/gi,oe=/<script|<style|<link/i,ae=/checked\s*(?:[^=]|=\s*.checked.)/i,se=/^true\/(.*)/,ue=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g;yt.extend({htmlPrefilter:function(t){return t.replace(ie,"<$1></$2>")},clone:function(t,e,n){var r,i,o,a,s=t.cloneNode(!0),u=yt.contains(t.ownerDocument,t);if(!(gt.noCloneChecked||1!==t.nodeType&&11!==t.nodeType||yt.isXMLDoc(t)))for(a=w(s),o=w(t),r=0,i=o.length;r<i;r++)N(o[r],a[r]);if(e)if(n)for(o=o||w(t),a=a||w(s),r=0,i=o.length;r<i;r++)j(o[r],a[r]);else j(t,s);return a=w(s,"script"),a.length>0&&x(a,!u&&w(t,"script")),s},cleanData:function(t){for(var e,n,r,i=yt.event.special,o=0;void 0!==(n=t[o]);o++)if(Ft(n)){if(e=n[qt.expando]){if(e.events)for(r in e.events)i[r]?yt.event.remove(n,r):yt.removeEvent(n,r,e.handle);n[qt.expando]=void 0}n[Mt.expando]&&(n[Mt.expando]=void 0)}}}),yt.fn.extend({detach:function(t){return I(this,t,!0)},remove:function(t){return I(this,t)},text:function(t){return Pt(this,function(t){return void 0===t?yt.text(this):this.empty().each(function(){1!==this.nodeType&&11!==this.nodeType&&9!==this.nodeType||(this.textContent=t)})},null,t,arguments.length)},append:function(){return D(this,arguments,function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=E(this,t);e.appendChild(t)}})},prepend:function(){return D(this,arguments,function(t){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var e=E(this,t);e.insertBefore(t,e.firstChild)}})},before:function(){return D(this,arguments,function(t){this.parentNode&&this.parentNode.insertBefore(t,this)})},after:function(){return D(this,arguments,function(t){this.parentNode&&this.parentNode.insertBefore(t,this.nextSibling)})},empty:function(){for(var t,e=0;null!=(t=this[e]);e++)1===t.nodeType&&(yt.cleanData(w(t,!1)),t.textContent="");return this},clone:function(t,e){return t=null!=t&&t,e=null==e?t:e,this.map(function(){return yt.clone(this,t,e)})},html:function(t){return Pt(this,function(t){var e=this[0]||{},n=0,r=this.length;if(void 0===t&&1===e.nodeType)return e.innerHTML;if("string"==typeof t&&!oe.test(t)&&!Yt[(Gt.exec(t)||["",""])[1].toLowerCase()]){t=yt.htmlPrefilter(t);try{for(;n<r;n++)e=this[n]||{},1===e.nodeType&&(yt.cleanData(w(e,!1)),e.innerHTML=t);e=0}catch(t){}}e&&this.empty().append(t)},null,t,arguments.length)},replaceWith:function(){var t=[];return D(this,arguments,function(e){var n=this.parentNode;yt.inArray(this,t)<0&&(yt.cleanData(w(this)),n&&n.replaceChild(e,this))},t)}}),yt.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(t,e){yt.fn[t]=function(t){for(var n,r=[],i=yt(t),o=i.length-1,a=0;a<=o;a++)n=a===o?this:this.clone(!0),yt(i[a])[e](n),ct.apply(r,n.get());return this.pushStack(r)}});var ce=/^margin/,le=new RegExp("^("+Ut+")(?!px)[a-z%]+$","i"),fe=function(t){var e=t.ownerDocument.defaultView;return e&&e.opener||(e=n),e.getComputedStyle(t)};!function(){function t(){if(s){s.style.cssText="box-sizing:border-box;position:relative;display:block;margin:auto;border:1px;padding:1px;top:1%;width:50%",s.innerHTML="",te.appendChild(a);var t=n.getComputedStyle(s);e="1%"!==t.top,o="2px"===t.marginLeft,r="4px"===t.width,s.style.marginRight="50%",i="4px"===t.marginRight,te.removeChild(a),s=null}}var e,r,i,o,a=ot.createElement("div"),s=ot.createElement("div");s.style&&(s.style.backgroundClip="content-box",s.cloneNode(!0).style.backgroundClip="",gt.clearCloneStyle="content-box"===s.style.backgroundClip,a.style.cssText="border:0;width:8px;height:0;top:0;left:-9999px;padding:0;margin-top:1px;position:absolute",a.appendChild(s),yt.extend(gt,{pixelPosition:function(){return t(),e},boxSizingReliable:function(){return t(),r},pixelMarginRight:function(){return t(),i},reliableMarginLeft:function(){return t(),o}}))}();var pe=/^(none|table(?!-c[ea]).+)/,de={position:"absolute",visibility:"hidden",display:"block"},he={letterSpacing:"0",fontWeight:"400"},ve=["Webkit","Moz","ms"],ge=ot.createElement("div").style;yt.extend({cssHooks:{opacity:{get:function(t,e){if(e){var n=R(t,"opacity");return""===n?"1":n}}}},cssNumber:{animationIterationCount:!0,columnCount:!0,fillOpacity:!0,flexGrow:!0,flexShrink:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{float:"cssFloat"},style:function(t,e,n,r){if(t&&3!==t.nodeType&&8!==t.nodeType&&t.style){var i,o,a,s=yt.camelCase(e),u=t.style;return e=yt.cssProps[s]||(yt.cssProps[s]=P(s)||s),a=yt.cssHooks[e]||yt.cssHooks[s],void 0===n?a&&"get"in a&&void 0!==(i=a.get(t,!1,r))?i:u[e]:(o=typeof n,"string"===o&&(i=Wt.exec(n))&&i[1]&&(n=y(t,e,i),o="number"),null!=n&&n===n&&("number"===o&&(n+=i&&i[3]||(yt.cssNumber[s]?"":"px")),gt.clearCloneStyle||""!==n||0!==e.indexOf("background")||(u[e]="inherit"),a&&"set"in a&&void 0===(n=a.set(t,n,r))||(u[e]=n)),void 0)}},css:function(t,e,n,r){var i,o,a,s=yt.camelCase(e);return e=yt.cssProps[s]||(yt.cssProps[s]=P(s)||s),a=yt.cssHooks[e]||yt.cssHooks[s],a&&"get"in a&&(i=a.get(t,!0,n)),void 0===i&&(i=R(t,e,r)),"normal"===i&&e in he&&(i=he[e]),""===n||n?(o=parseFloat(i),n===!0||isFinite(o)?o||0:i):i}}),yt.each(["height","width"],function(t,e){yt.cssHooks[e]={get:function(t,n,r){if(n)return!pe.test(yt.css(t,"display"))||t.getClientRects().length&&t.getBoundingClientRect().width?M(t,e,r):Xt(t,de,function(){return M(t,e,r)})},set:function(t,n,r){var i,o=r&&fe(t),a=r&&q(t,e,r,"border-box"===yt.css(t,"boxSizing",!1,o),o);return a&&(i=Wt.exec(n))&&"px"!==(i[3]||"px")&&(t.style[e]=n,n=yt.css(t,e)),F(t,n,a)}}}),yt.cssHooks.marginLeft=L(gt.reliableMarginLeft,function(t,e){if(e)return(parseFloat(R(t,"marginLeft"))||t.getBoundingClientRect().left-Xt(t,{marginLeft:0},function(){return t.getBoundingClientRect().left}))+"px"}),yt.each({margin:"",padding:"",border:"Width"},function(t,e){yt.cssHooks[t+e]={expand:function(n){for(var r=0,i={},o="string"==typeof n?n.split(" "):[n];r<4;r++)i[t+zt[r]+e]=o[r]||o[r-2]||o[0];return i}},ce.test(t)||(yt.cssHooks[t+e].set=F)}),yt.fn.extend({css:function(t,e){return Pt(this,function(t,e,n){var r,i,o={},a=0;if(yt.isArray(e)){for(r=fe(t),i=e.length;a<i;a++)o[e[a]]=yt.css(t,e[a],!1,r);return o}return void 0!==n?yt.style(t,e,n):yt.css(t,e)},t,e,arguments.length>1)}}),yt.Tween=H,H.prototype={constructor:H,init:function(t,e,n,r,i,o){this.elem=t,this.prop=n,this.easing=i||yt.easing._default,this.options=e,this.start=this.now=this.cur(),this.end=r,this.unit=o||(yt.cssNumber[n]?"":"px")},cur:function(){var t=H.propHooks[this.prop];return t&&t.get?t.get(this):H.propHooks._default.get(this)},run:function(t){var e,n=H.propHooks[this.prop];return this.options.duration?this.pos=e=yt.easing[this.easing](t,this.options.duration*t,0,1,this.options.duration):this.pos=e=t,this.now=(this.end-this.start)*e+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),n&&n.set?n.set(this):H.propHooks._default.set(this),this}},H.prototype.init.prototype=H.prototype,H.propHooks={_default:{get:function(t){var e;return 1!==t.elem.nodeType||null!=t.elem[t.prop]&&null==t.elem.style[t.prop]?t.elem[t.prop]:(e=yt.css(t.elem,t.prop,""),e&&"auto"!==e?e:0)},set:function(t){yt.fx.step[t.prop]?yt.fx.step[t.prop](t):1!==t.elem.nodeType||null==t.elem.style[yt.cssProps[t.prop]]&&!yt.cssHooks[t.prop]?t.elem[t.prop]=t.now:yt.style(t.elem,t.prop,t.now+t.unit)}}},H.propHooks.scrollTop=H.propHooks.scrollLeft={set:function(t){t.elem.nodeType&&t.elem.parentNode&&(t.elem[t.prop]=t.now)}},yt.easing={linear:function(t){return t},swing:function(t){return.5-Math.cos(t*Math.PI)/2},_default:"swing"},yt.fx=H.prototype.init,yt.fx.step={};var me,ye,be=/^(?:toggle|show|hide)$/,_e=/queueHooks$/;yt.Animation=yt.extend(K,{tweeners:{"*":[function(t,e){var n=this.createTween(t,e);return y(n.elem,t,Wt.exec(e),n),n}]},tweener:function(t,e){yt.isFunction(t)?(e=t,t=["*"]):t=t.match(It);for(var n,r=0,i=t.length;r<i;r++)n=t[r],K.tweeners[n]=K.tweeners[n]||[],K.tweeners[n].unshift(e)},prefilters:[V],prefilter:function(t,e){e?K.prefilters.unshift(t):K.prefilters.push(t)}}),yt.speed=function(t,e,n){var r=t&&"object"==typeof t?yt.extend({},t):{complete:n||!n&&e||yt.isFunction(t)&&t,duration:t,easing:n&&e||e&&!yt.isFunction(e)&&e};return yt.fx.off||ot.hidden?r.duration=0:"number"!=typeof r.duration&&(r.duration in yt.fx.speeds?r.duration=yt.fx.speeds[r.duration]:r.duration=yt.fx.speeds._default),null!=r.queue&&r.queue!==!0||(r.queue="fx"),r.old=r.complete,r.complete=function(){yt.isFunction(r.old)&&r.old.call(this),r.queue&&yt.dequeue(this,r.queue)},r},yt.fn.extend({fadeTo:function(t,e,n,r){return this.filter(Vt).css("opacity",0).show().end().animate({opacity:e},t,n,r)},animate:function(t,e,n,r){var i=yt.isEmptyObject(t),o=yt.speed(e,n,r),a=function(){var e=K(this,yt.extend({},t),o);(i||qt.get(this,"finish"))&&e.stop(!0)};return a.finish=a,i||o.queue===!1?this.each(a):this.queue(o.queue,a)},stop:function(t,e,n){var r=function(t){var e=t.stop;delete t.stop,e(n)};return"string"!=typeof t&&(n=e,e=t,t=void 0),e&&t!==!1&&this.queue(t||"fx",[]),this.each(function(){var e=!0,i=null!=t&&t+"queueHooks",o=yt.timers,a=qt.get(this);if(i)a[i]&&a[i].stop&&r(a[i]);else for(i in a)a[i]&&a[i].stop&&_e.test(i)&&r(a[i]);for(i=o.length;i--;)o[i].elem!==this||null!=t&&o[i].queue!==t||(o[i].anim.stop(n),e=!1,o.splice(i,1));!e&&n||yt.dequeue(this,t)})},finish:function(t){return t!==!1&&(t=t||"fx"),this.each(function(){var e,n=qt.get(this),r=n[t+"queue"],i=n[t+"queueHooks"],o=yt.timers,a=r?r.length:0;for(n.finish=!0,yt.queue(this,t,[]),i&&i.stop&&i.stop.call(this,!0),e=o.length;e--;)o[e].elem===this&&o[e].queue===t&&(o[e].anim.stop(!0),o.splice(e,1));for(e=0;e<a;e++)r[e]&&r[e].finish&&r[e].finish.call(this);delete n.finish})}}),yt.each(["toggle","show","hide"],function(t,e){var n=yt.fn[e];yt.fn[e]=function(t,r,i){return null==t||"boolean"==typeof t?n.apply(this,arguments):this.animate(W(e,!0),t,r,i)}}),yt.each({slideDown:W("show"),slideUp:W("hide"),slideToggle:W("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(t,e){yt.fn[t]=function(t,n,r){return this.animate(e,t,n,r)}}),yt.timers=[],yt.fx.tick=function(){var t,e=0,n=yt.timers;for(me=yt.now();e<n.length;e++)t=n[e],t()||n[e]!==t||n.splice(e--,1);n.length||yt.fx.stop(),me=void 0},yt.fx.timer=function(t){yt.timers.push(t),t()?yt.fx.start():yt.timers.pop()},yt.fx.interval=13,yt.fx.start=function(){ye||(ye=n.requestAnimationFrame?n.requestAnimationFrame(B):n.setInterval(yt.fx.tick,yt.fx.interval))},yt.fx.stop=function(){n.cancelAnimationFrame?n.cancelAnimationFrame(ye):n.clearInterval(ye),ye=null},yt.fx.speeds={slow:600,fast:200,_default:400},yt.fn.delay=function(t,e){return t=yt.fx?yt.fx.speeds[t]||t:t,e=e||"fx",this.queue(e,function(e,r){var i=n.setTimeout(e,t);r.stop=function(){n.clearTimeout(i)}})},function(){var t=ot.createElement("input"),e=ot.createElement("select"),n=e.appendChild(ot.createElement("option"));t.type="checkbox",gt.checkOn=""!==t.value,gt.optSelected=n.selected,t=ot.createElement("input"),t.value="t",t.type="radio",gt.radioValue="t"===t.value}();var we,xe=yt.expr.attrHandle;yt.fn.extend({attr:function(t,e){return Pt(this,yt.attr,t,e,arguments.length>1)},removeAttr:function(t){return this.each(function(){yt.removeAttr(this,t)})}}),yt.extend({attr:function(t,e,n){var r,i,o=t.nodeType;if(3!==o&&8!==o&&2!==o)return"undefined"==typeof t.getAttribute?yt.prop(t,e,n):(1===o&&yt.isXMLDoc(t)||(i=yt.attrHooks[e.toLowerCase()]||(yt.expr.match.bool.test(e)?we:void 0)),void 0!==n?null===n?void yt.removeAttr(t,e):i&&"set"in i&&void 0!==(r=i.set(t,n,e))?r:(t.setAttribute(e,n+""),n):i&&"get"in i&&null!==(r=i.get(t,e))?r:(r=yt.find.attr(t,e),null==r?void 0:r))},attrHooks:{type:{set:function(t,e){if(!gt.radioValue&&"radio"===e&&yt.nodeName(t,"input")){var n=t.value;return t.setAttribute("type",e),n&&(t.value=n),e}}}},removeAttr:function(t,e){var n,r=0,i=e&&e.match(It);if(i&&1===t.nodeType)for(;n=i[r++];)t.removeAttribute(n)}}),we={set:function(t,e,n){return e===!1?yt.removeAttr(t,n):t.setAttribute(n,n),n}},yt.each(yt.expr.match.bool.source.match(/\w+/g),function(t,e){var n=xe[e]||yt.find.attr;xe[e]=function(t,e,r){var i,o,a=e.toLowerCase();return r||(o=xe[a],xe[a]=i,i=null!=n(t,e,r)?a:null,xe[a]=o),i}});var Ce=/^(?:input|select|textarea|button)$/i,Te=/^(?:a|area)$/i;yt.fn.extend({prop:function(t,e){return Pt(this,yt.prop,t,e,arguments.length>1)},removeProp:function(t){return this.each(function(){delete this[yt.propFix[t]||t]})}}),yt.extend({prop:function(t,e,n){var r,i,o=t.nodeType;if(3!==o&&8!==o&&2!==o)return 1===o&&yt.isXMLDoc(t)||(e=yt.propFix[e]||e,i=yt.propHooks[e]),void 0!==n?i&&"set"in i&&void 0!==(r=i.set(t,n,e))?r:t[e]=n:i&&"get"in i&&null!==(r=i.get(t,e))?r:t[e]},propHooks:{tabIndex:{get:function(t){var e=yt.find.attr(t,"tabindex");return e?parseInt(e,10):Ce.test(t.nodeName)||Te.test(t.nodeName)&&t.href?0:-1}}},propFix:{for:"htmlFor",class:"className"}}),gt.optSelected||(yt.propHooks.selected={get:function(t){var e=t.parentNode;return e&&e.parentNode&&e.parentNode.selectedIndex,null},set:function(t){var e=t.parentNode;e&&(e.selectedIndex,e.parentNode&&e.parentNode.selectedIndex)}}),yt.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){yt.propFix[this.toLowerCase()]=this}),yt.fn.extend({addClass:function(t){var e,n,r,i,o,a,s,u=0;if(yt.isFunction(t))return this.each(function(e){yt(this).addClass(t.call(this,e,G(this)))});if("string"==typeof t&&t)for(e=t.match(It)||[];n=this[u++];)if(i=G(n),r=1===n.nodeType&&" "+J(i)+" "){for(a=0;o=e[a++];)r.indexOf(" "+o+" ")<0&&(r+=o+" ");s=J(r),i!==s&&n.setAttribute("class",s)}return this},removeClass:function(t){var e,n,r,i,o,a,s,u=0;if(yt.isFunction(t))return this.each(function(e){yt(this).removeClass(t.call(this,e,G(this)))});if(!arguments.length)return this.attr("class","");if("string"==typeof t&&t)for(e=t.match(It)||[];n=this[u++];)if(i=G(n),r=1===n.nodeType&&" "+J(i)+" "){for(a=0;o=e[a++];)for(;r.indexOf(" "+o+" ")>-1;)r=r.replace(" "+o+" "," ");s=J(r),i!==s&&n.setAttribute("class",s)}return this},toggleClass:function(t,e){var n=typeof t;return"boolean"==typeof e&&"string"===n?e?this.addClass(t):this.removeClass(t):yt.isFunction(t)?this.each(function(n){yt(this).toggleClass(t.call(this,n,G(this),e),e)}):this.each(function(){var e,r,i,o;if("string"===n)for(r=0,i=yt(this),o=t.match(It)||[];e=o[r++];)i.hasClass(e)?i.removeClass(e):i.addClass(e);else void 0!==t&&"boolean"!==n||(e=G(this),e&&qt.set(this,"__className__",e),this.setAttribute&&this.setAttribute("class",e||t===!1?"":qt.get(this,"__className__")||""))})},hasClass:function(t){var e,n,r=0;for(e=" "+t+" ";n=this[r++];)if(1===n.nodeType&&(" "+J(G(n))+" ").indexOf(e)>-1)return!0;return!1}});var $e=/\r/g;yt.fn.extend({val:function(t){var e,n,r,i=this[0];{if(arguments.length)return r=yt.isFunction(t),this.each(function(n){var i;1===this.nodeType&&(i=r?t.call(this,n,yt(this).val()):t,null==i?i="":"number"==typeof i?i+="":yt.isArray(i)&&(i=yt.map(i,function(t){return null==t?"":t+""})),e=yt.valHooks[this.type]||yt.valHooks[this.nodeName.toLowerCase()],e&&"set"in e&&void 0!==e.set(this,i,"value")||(this.value=i))});if(i)return e=yt.valHooks[i.type]||yt.valHooks[i.nodeName.toLowerCase()],e&&"get"in e&&void 0!==(n=e.get(i,"value"))?n:(n=i.value,"string"==typeof n?n.replace($e,""):null==n?"":n)}}}),yt.extend({valHooks:{option:{get:function(t){var e=yt.find.attr(t,"value");return null!=e?e:J(yt.text(t))}},select:{get:function(t){var e,n,r,i=t.options,o=t.selectedIndex,a="select-one"===t.type,s=a?null:[],u=a?o+1:i.length;for(r=o<0?u:a?o:0;r<u;r++)if(n=i[r],(n.selected||r===o)&&!n.disabled&&(!n.parentNode.disabled||!yt.nodeName(n.parentNode,"optgroup"))){if(e=yt(n).val(),a)return e;s.push(e)}return s},set:function(t,e){for(var n,r,i=t.options,o=yt.makeArray(e),a=i.length;a--;)r=i[a],(r.selected=yt.inArray(yt.valHooks.option.get(r),o)>-1)&&(n=!0);return n||(t.selectedIndex=-1),o}}}}),yt.each(["radio","checkbox"],function(){yt.valHooks[this]={set:function(t,e){if(yt.isArray(e))return t.checked=yt.inArray(yt(t).val(),e)>-1}},gt.checkOn||(yt.valHooks[this].get=function(t){return null===t.getAttribute("value")?"on":t.value})});var ke=/^(?:focusinfocus|focusoutblur)$/;yt.extend(yt.event,{trigger:function(t,e,r,i){var o,a,s,u,c,l,f,p=[r||ot],d=dt.call(t,"type")?t.type:t,h=dt.call(t,"namespace")?t.namespace.split("."):[];if(a=s=r=r||ot,3!==r.nodeType&&8!==r.nodeType&&!ke.test(d+yt.event.triggered)&&(d.indexOf(".")>-1&&(h=d.split("."),d=h.shift(),h.sort()),c=d.indexOf(":")<0&&"on"+d,t=t[yt.expando]?t:new yt.Event(d,"object"==typeof t&&t),t.isTrigger=i?2:3,t.namespace=h.join("."),t.rnamespace=t.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,t.result=void 0,t.target||(t.target=r),e=null==e?[t]:yt.makeArray(e,[t]),f=yt.event.special[d]||{},i||!f.trigger||f.trigger.apply(r,e)!==!1)){if(!i&&!f.noBubble&&!yt.isWindow(r)){for(u=f.delegateType||d,ke.test(u+d)||(a=a.parentNode);a;a=a.parentNode)p.push(a),s=a;s===(r.ownerDocument||ot)&&p.push(s.defaultView||s.parentWindow||n)}for(o=0;(a=p[o++])&&!t.isPropagationStopped();)t.type=o>1?u:f.bindType||d,l=(qt.get(a,"events")||{})[t.type]&&qt.get(a,"handle"),l&&l.apply(a,e),l=c&&a[c],l&&l.apply&&Ft(a)&&(t.result=l.apply(a,e),t.result===!1&&t.preventDefault());return t.type=d,i||t.isDefaultPrevented()||f._default&&f._default.apply(p.pop(),e)!==!1||!Ft(r)||c&&yt.isFunction(r[d])&&!yt.isWindow(r)&&(s=r[c],s&&(r[c]=null),yt.event.triggered=d,r[d](),yt.event.triggered=void 0,s&&(r[c]=s)),t.result}},simulate:function(t,e,n){var r=yt.extend(new yt.Event,n,{type:t,isSimulated:!0});yt.event.trigger(r,null,e)}}),yt.fn.extend({trigger:function(t,e){return this.each(function(){yt.event.trigger(t,e,this)})},triggerHandler:function(t,e){var n=this[0];if(n)return yt.event.trigger(t,e,n,!0)}}),yt.each("blur focus focusin focusout resize scroll click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup contextmenu".split(" "),function(t,e){yt.fn[e]=function(t,n){return arguments.length>0?this.on(e,null,t,n):this.trigger(e)}}),yt.fn.extend({hover:function(t,e){return this.mouseenter(t).mouseleave(e||t)}}),gt.focusin="onfocusin"in n,gt.focusin||yt.each({focus:"focusin",blur:"focusout"},function(t,e){var n=function(t){yt.event.simulate(e,t.target,yt.event.fix(t))};yt.event.special[e]={setup:function(){var r=this.ownerDocument||this,i=qt.access(r,e);i||r.addEventListener(t,n,!0),qt.access(r,e,(i||0)+1)},teardown:function(){var r=this.ownerDocument||this,i=qt.access(r,e)-1;i?qt.access(r,e,i):(r.removeEventListener(t,n,!0),qt.remove(r,e))}}});var Ae=n.location,Ee=yt.now(),Se=/\?/;yt.parseXML=function(t){var e;if(!t||"string"!=typeof t)return null;try{e=(new n.DOMParser).parseFromString(t,"text/xml")}catch(t){e=void 0}return e&&!e.getElementsByTagName("parsererror").length||yt.error("Invalid XML: "+t),e};var Oe=/\[\]$/,je=/\r?\n/g,Ne=/^(?:submit|button|image|reset|file)$/i,De=/^(?:input|select|textarea|keygen)/i;yt.param=function(t,e){var n,r=[],i=function(t,e){var n=yt.isFunction(e)?e():e;r[r.length]=encodeURIComponent(t)+"="+encodeURIComponent(null==n?"":n)};if(yt.isArray(t)||t.jquery&&!yt.isPlainObject(t))yt.each(t,function(){i(this.name,this.value)});else for(n in t)Z(n,t[n],e,i);return r.join("&")},yt.fn.extend({serialize:function(){return yt.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var t=yt.prop(this,"elements");return t?yt.makeArray(t):this}).filter(function(){var t=this.type;return this.name&&!yt(this).is(":disabled")&&De.test(this.nodeName)&&!Ne.test(t)&&(this.checked||!Jt.test(t))}).map(function(t,e){var n=yt(this).val();return null==n?null:yt.isArray(n)?yt.map(n,function(t){return{name:e.name,value:t.replace(je,"\r\n")}}):{name:e.name,value:n.replace(je,"\r\n")}}).get()}});var Ie=/%20/g,Re=/#.*$/,Le=/([?&])_=[^&]*/,Pe=/^(.*?):[ \t]*([^\r\n]*)$/gm,Fe=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,qe=/^(?:GET|HEAD)$/,Me=/^\/\//,He={},Be={},Ue="*/".concat("*"),We=ot.createElement("a");We.href=Ae.href,yt.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ae.href,type:"GET",isLocal:Fe.test(Ae.protocol),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Ue,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/\bxml\b/,html:/\bhtml/,json:/\bjson\b/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":JSON.parse,"text xml":yt.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(t,e){return e?tt(tt(t,yt.ajaxSettings),e):tt(yt.ajaxSettings,t)},ajaxPrefilter:Y(He),ajaxTransport:Y(Be),ajax:function(t,e){function r(t,e,r,s){var c,p,d,_,w,x=e;l||(l=!0,u&&n.clearTimeout(u),i=void 0,a=s||"",C.readyState=t>0?4:0,c=t>=200&&t<300||304===t,r&&(_=et(h,C,r)),_=nt(h,_,C,c),c?(h.ifModified&&(w=C.getResponseHeader("Last-Modified"),w&&(yt.lastModified[o]=w),w=C.getResponseHeader("etag"),w&&(yt.etag[o]=w)),204===t||"HEAD"===h.type?x="nocontent":304===t?x="notmodified":(x=_.state,p=_.data,d=_.error,c=!d)):(d=x,!t&&x||(x="error",t<0&&(t=0))),C.status=t,C.statusText=(e||x)+"",c?m.resolveWith(v,[p,x,C]):m.rejectWith(v,[C,x,d]),C.statusCode(b),b=void 0,f&&g.trigger(c?"ajaxSuccess":"ajaxError",[C,h,c?p:d]),y.fireWith(v,[C,x]),f&&(g.trigger("ajaxComplete",[C,h]),--yt.active||yt.event.trigger("ajaxStop")))}"object"==typeof t&&(e=t,t=void 0),e=e||{};var i,o,a,s,u,c,l,f,p,d,h=yt.ajaxSetup({},e),v=h.context||h,g=h.context&&(v.nodeType||v.jquery)?yt(v):yt.event,m=yt.Deferred(),y=yt.Callbacks("once memory"),b=h.statusCode||{},_={},w={},x="canceled",C={readyState:0,getResponseHeader:function(t){var e;if(l){if(!s)for(s={};e=Pe.exec(a);)s[e[1].toLowerCase()]=e[2];e=s[t.toLowerCase()]}return null==e?null:e},getAllResponseHeaders:function(){return l?a:null},setRequestHeader:function(t,e){return null==l&&(t=w[t.toLowerCase()]=w[t.toLowerCase()]||t,_[t]=e),this},overrideMimeType:function(t){return null==l&&(h.mimeType=t),this},statusCode:function(t){var e;if(t)if(l)C.always(t[C.status]);else for(e in t)b[e]=[b[e],t[e]];return this},abort:function(t){var e=t||x;return i&&i.abort(e),r(0,e),this}};if(m.promise(C),h.url=((t||h.url||Ae.href)+"").replace(Me,Ae.protocol+"//"),h.type=e.method||e.type||h.method||h.type,h.dataTypes=(h.dataType||"*").toLowerCase().match(It)||[""],null==h.crossDomain){c=ot.createElement("a");try{c.href=h.url,c.href=c.href,h.crossDomain=We.protocol+"//"+We.host!=c.protocol+"//"+c.host}catch(t){h.crossDomain=!0}}if(h.data&&h.processData&&"string"!=typeof h.data&&(h.data=yt.param(h.data,h.traditional)),Q(He,h,e,C),l)return C;f=yt.event&&h.global,f&&0===yt.active++&&yt.event.trigger("ajaxStart"),h.type=h.type.toUpperCase(),h.hasContent=!qe.test(h.type),o=h.url.replace(Re,""),h.hasContent?h.data&&h.processData&&0===(h.contentType||"").indexOf("application/x-www-form-urlencoded")&&(h.data=h.data.replace(Ie,"+")):(d=h.url.slice(o.length),h.data&&(o+=(Se.test(o)?"&":"?")+h.data,delete h.data),h.cache===!1&&(o=o.replace(Le,"$1"),d=(Se.test(o)?"&":"?")+"_="+Ee++ +d),h.url=o+d),h.ifModified&&(yt.lastModified[o]&&C.setRequestHeader("If-Modified-Since",yt.lastModified[o]),yt.etag[o]&&C.setRequestHeader("If-None-Match",yt.etag[o])),(h.data&&h.hasContent&&h.contentType!==!1||e.contentType)&&C.setRequestHeader("Content-Type",h.contentType),C.setRequestHeader("Accept",h.dataTypes[0]&&h.accepts[h.dataTypes[0]]?h.accepts[h.dataTypes[0]]+("*"!==h.dataTypes[0]?", "+Ue+"; q=0.01":""):h.accepts["*"]);for(p in h.headers)C.setRequestHeader(p,h.headers[p]);if(h.beforeSend&&(h.beforeSend.call(v,C,h)===!1||l))return C.abort();if(x="abort",y.add(h.complete),C.done(h.success),C.fail(h.error),i=Q(Be,h,e,C)){if(C.readyState=1,f&&g.trigger("ajaxSend",[C,h]),l)return C;h.async&&h.timeout>0&&(u=n.setTimeout(function(){C.abort("timeout")},h.timeout));try{l=!1,i.send(_,r)}catch(t){if(l)throw t;r(-1,t)}}else r(-1,"No Transport");return C},getJSON:function(t,e,n){return yt.get(t,e,n,"json")},getScript:function(t,e){return yt.get(t,void 0,e,"script")}}),yt.each(["get","post"],function(t,e){yt[e]=function(t,n,r,i){return yt.isFunction(n)&&(i=i||r,r=n,n=void 0),yt.ajax(yt.extend({url:t,type:e,dataType:i,data:n,success:r},yt.isPlainObject(t)&&t))}}),yt._evalUrl=function(t){return yt.ajax({url:t,type:"GET",dataType:"script",cache:!0,async:!1,global:!1,throws:!0})},yt.fn.extend({wrapAll:function(t){var e;return this[0]&&(yt.isFunction(t)&&(t=t.call(this[0])),e=yt(t,this[0].ownerDocument).eq(0).clone(!0),this[0].parentNode&&e.insertBefore(this[0]),e.map(function(){for(var t=this;t.firstElementChild;)t=t.firstElementChild;return t}).append(this)),this},wrapInner:function(t){return yt.isFunction(t)?this.each(function(e){yt(this).wrapInner(t.call(this,e))}):this.each(function(){var e=yt(this),n=e.contents();n.length?n.wrapAll(t):e.append(t)})},wrap:function(t){var e=yt.isFunction(t);return this.each(function(n){yt(this).wrapAll(e?t.call(this,n):t)})},unwrap:function(t){return this.parent(t).not("body").each(function(){ yt(this).replaceWith(this.childNodes)}),this}}),yt.expr.pseudos.hidden=function(t){return!yt.expr.pseudos.visible(t)},yt.expr.pseudos.visible=function(t){return!!(t.offsetWidth||t.offsetHeight||t.getClientRects().length)},yt.ajaxSettings.xhr=function(){try{return new n.XMLHttpRequest}catch(t){}};var ze={0:200,1223:204},Ve=yt.ajaxSettings.xhr();gt.cors=!!Ve&&"withCredentials"in Ve,gt.ajax=Ve=!!Ve,yt.ajaxTransport(function(t){var e,r;if(gt.cors||Ve&&!t.crossDomain)return{send:function(i,o){var a,s=t.xhr();if(s.open(t.type,t.url,t.async,t.username,t.password),t.xhrFields)for(a in t.xhrFields)s[a]=t.xhrFields[a];t.mimeType&&s.overrideMimeType&&s.overrideMimeType(t.mimeType),t.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(a in i)s.setRequestHeader(a,i[a]);e=function(t){return function(){e&&(e=r=s.onload=s.onerror=s.onabort=s.onreadystatechange=null,"abort"===t?s.abort():"error"===t?"number"!=typeof s.status?o(0,"error"):o(s.status,s.statusText):o(ze[s.status]||s.status,s.statusText,"text"!==(s.responseType||"text")||"string"!=typeof s.responseText?{binary:s.response}:{text:s.responseText},s.getAllResponseHeaders()))}},s.onload=e(),r=s.onerror=e("error"),void 0!==s.onabort?s.onabort=r:s.onreadystatechange=function(){4===s.readyState&&n.setTimeout(function(){e&&r()})},e=e("abort");try{s.send(t.hasContent&&t.data||null)}catch(t){if(e)throw t}},abort:function(){e&&e()}}}),yt.ajaxPrefilter(function(t){t.crossDomain&&(t.contents.script=!1)}),yt.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/\b(?:java|ecma)script\b/},converters:{"text script":function(t){return yt.globalEval(t),t}}}),yt.ajaxPrefilter("script",function(t){void 0===t.cache&&(t.cache=!1),t.crossDomain&&(t.type="GET")}),yt.ajaxTransport("script",function(t){if(t.crossDomain){var e,n;return{send:function(r,i){e=yt("<script>").prop({charset:t.scriptCharset,src:t.url}).on("load error",n=function(t){e.remove(),n=null,t&&i("error"===t.type?404:200,t.type)}),ot.head.appendChild(e[0])},abort:function(){n&&n()}}}});var Xe=[],Ke=/(=)\?(?=&|$)|\?\?/;yt.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var t=Xe.pop()||yt.expando+"_"+Ee++;return this[t]=!0,t}}),yt.ajaxPrefilter("json jsonp",function(t,e,r){var i,o,a,s=t.jsonp!==!1&&(Ke.test(t.url)?"url":"string"==typeof t.data&&0===(t.contentType||"").indexOf("application/x-www-form-urlencoded")&&Ke.test(t.data)&&"data");if(s||"jsonp"===t.dataTypes[0])return i=t.jsonpCallback=yt.isFunction(t.jsonpCallback)?t.jsonpCallback():t.jsonpCallback,s?t[s]=t[s].replace(Ke,"$1"+i):t.jsonp!==!1&&(t.url+=(Se.test(t.url)?"&":"?")+t.jsonp+"="+i),t.converters["script json"]=function(){return a||yt.error(i+" was not called"),a[0]},t.dataTypes[0]="json",o=n[i],n[i]=function(){a=arguments},r.always(function(){void 0===o?yt(n).removeProp(i):n[i]=o,t[i]&&(t.jsonpCallback=e.jsonpCallback,Xe.push(i)),a&&yt.isFunction(o)&&o(a[0]),a=o=void 0}),"script"}),gt.createHTMLDocument=function(){var t=ot.implementation.createHTMLDocument("").body;return t.innerHTML="<form></form><form></form>",2===t.childNodes.length}(),yt.parseHTML=function(t,e,n){if("string"!=typeof t)return[];"boolean"==typeof e&&(n=e,e=!1);var r,i,o;return e||(gt.createHTMLDocument?(e=ot.implementation.createHTMLDocument(""),r=e.createElement("base"),r.href=ot.location.href,e.head.appendChild(r)):e=ot),i=At.exec(t),o=!n&&[],i?[e.createElement(i[1])]:(i=C([t],e,o),o&&o.length&&yt(o).remove(),yt.merge([],i.childNodes))},yt.fn.load=function(t,e,n){var r,i,o,a=this,s=t.indexOf(" ");return s>-1&&(r=J(t.slice(s)),t=t.slice(0,s)),yt.isFunction(e)?(n=e,e=void 0):e&&"object"==typeof e&&(i="POST"),a.length>0&&yt.ajax({url:t,type:i||"GET",dataType:"html",data:e}).done(function(t){o=arguments,a.html(r?yt("<div>").append(yt.parseHTML(t)).find(r):t)}).always(n&&function(t,e){a.each(function(){n.apply(this,o||[t.responseText,e,t])})}),this},yt.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(t,e){yt.fn[e]=function(t){return this.on(e,t)}}),yt.expr.pseudos.animated=function(t){return yt.grep(yt.timers,function(e){return t===e.elem}).length},yt.offset={setOffset:function(t,e,n){var r,i,o,a,s,u,c,l=yt.css(t,"position"),f=yt(t),p={};"static"===l&&(t.style.position="relative"),s=f.offset(),o=yt.css(t,"top"),u=yt.css(t,"left"),c=("absolute"===l||"fixed"===l)&&(o+u).indexOf("auto")>-1,c?(r=f.position(),a=r.top,i=r.left):(a=parseFloat(o)||0,i=parseFloat(u)||0),yt.isFunction(e)&&(e=e.call(t,n,yt.extend({},s))),null!=e.top&&(p.top=e.top-s.top+a),null!=e.left&&(p.left=e.left-s.left+i),"using"in e?e.using.call(t,p):f.css(p)}},yt.fn.extend({offset:function(t){if(arguments.length)return void 0===t?this:this.each(function(e){yt.offset.setOffset(this,t,e)});var e,n,r,i,o=this[0];if(o)return o.getClientRects().length?(r=o.getBoundingClientRect(),r.width||r.height?(i=o.ownerDocument,n=rt(i),e=i.documentElement,{top:r.top+n.pageYOffset-e.clientTop,left:r.left+n.pageXOffset-e.clientLeft}):r):{top:0,left:0}},position:function(){if(this[0]){var t,e,n=this[0],r={top:0,left:0};return"fixed"===yt.css(n,"position")?e=n.getBoundingClientRect():(t=this.offsetParent(),e=this.offset(),yt.nodeName(t[0],"html")||(r=t.offset()),r={top:r.top+yt.css(t[0],"borderTopWidth",!0),left:r.left+yt.css(t[0],"borderLeftWidth",!0)}),{top:e.top-r.top-yt.css(n,"marginTop",!0),left:e.left-r.left-yt.css(n,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var t=this.offsetParent;t&&"static"===yt.css(t,"position");)t=t.offsetParent;return t||te})}}),yt.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(t,e){var n="pageYOffset"===e;yt.fn[t]=function(r){return Pt(this,function(t,r,i){var o=rt(t);return void 0===i?o?o[e]:t[r]:void(o?o.scrollTo(n?o.pageXOffset:i,n?i:o.pageYOffset):t[r]=i)},t,r,arguments.length)}}),yt.each(["top","left"],function(t,e){yt.cssHooks[e]=L(gt.pixelPosition,function(t,n){if(n)return n=R(t,e),le.test(n)?yt(t).position()[e]+"px":n})}),yt.each({Height:"height",Width:"width"},function(t,e){yt.each({padding:"inner"+t,content:e,"":"outer"+t},function(n,r){yt.fn[r]=function(i,o){var a=arguments.length&&(n||"boolean"!=typeof i),s=n||(i===!0||o===!0?"margin":"border");return Pt(this,function(e,n,i){var o;return yt.isWindow(e)?0===r.indexOf("outer")?e["inner"+t]:e.document.documentElement["client"+t]:9===e.nodeType?(o=e.documentElement,Math.max(e.body["scroll"+t],o["scroll"+t],e.body["offset"+t],o["offset"+t],o["client"+t])):void 0===i?yt.css(e,n,s):yt.style(e,n,i,s)},e,a?i:void 0,a)}})}),yt.fn.extend({bind:function(t,e,n){return this.on(t,null,e,n)},unbind:function(t,e){return this.off(t,null,e)},delegate:function(t,e,n,r){return this.on(e,t,n,r)},undelegate:function(t,e,n){return 1===arguments.length?this.off(t,"**"):this.off(e,t||"**",n)}}),yt.parseJSON=JSON.parse,r=[],i=function(){return yt}.apply(e,r),!(void 0!==i&&(t.exports=i));var Je=n.jQuery,Ge=n.$;return yt.noConflict=function(t){return n.$===yt&&(n.$=Ge),t&&n.jQuery===yt&&(n.jQuery=Je),yt},o||(n.jQuery=n.$=yt),yt})},function(t,e){var n;n=function(){return this}();try{n=n||Function("return this")()||(0,eval)("this")}catch(t){"object"==typeof window&&(n=window)}t.exports=n},function(t,e,n){n(30),Vue.component("example",n(34));new Vue({el:"#app"})},function(t,e){},function(t,e,n){t.exports=n(12)},function(t,e,n){"use strict";function r(t){var e=new a(t),n=o(a.prototype.request,e);return i.extend(n,a.prototype,e),i.extend(n,e),n}var i=n(0),o=n(6),a=n(14),s=n(1),u=r(s);u.Axios=a,u.create=function(t){return r(i.merge(s,t))},u.Cancel=n(3),u.CancelToken=n(13),u.isCancel=n(4),u.all=function(t){return Promise.all(t)},u.spread=n(28),t.exports=u,t.exports.default=u},function(t,e,n){"use strict";function r(t){if("function"!=typeof t)throw new TypeError("executor must be a function.");var e;this.promise=new Promise(function(t){e=t});var n=this;t(function(t){n.reason||(n.reason=new i(t),e(n.reason))})}var i=n(3);r.prototype.throwIfRequested=function(){if(this.reason)throw this.reason},r.source=function(){var t,e=new r(function(e){t=e});return{token:e,cancel:t}},t.exports=r},function(t,e,n){"use strict";function r(t){this.defaults=t,this.interceptors={request:new a,response:new a}}var i=n(1),o=n(0),a=n(15),s=n(16),u=n(24),c=n(22);r.prototype.request=function(t){"string"==typeof t&&(t=o.merge({url:arguments[0]},arguments[1])),t=o.merge(i,this.defaults,{method:"get"},t),t.baseURL&&!u(t.url)&&(t.url=c(t.baseURL,t.url));var e=[s,void 0],n=Promise.resolve(t);for(this.interceptors.request.forEach(function(t){e.unshift(t.fulfilled,t.rejected)}),this.interceptors.response.forEach(function(t){e.push(t.fulfilled,t.rejected)});e.length;)n=n.then(e.shift(),e.shift());return n},o.forEach(["delete","get","head"],function(t){r.prototype[t]=function(e,n){return this.request(o.merge(n||{},{method:t,url:e}))}}),o.forEach(["post","put","patch"],function(t){r.prototype[t]=function(e,n,r){return this.request(o.merge(r||{},{method:t,url:e,data:n}))}}),t.exports=r},function(t,e,n){"use strict";function r(){this.handlers=[]}var i=n(0);r.prototype.use=function(t,e){return this.handlers.push({fulfilled:t,rejected:e}),this.handlers.length-1},r.prototype.eject=function(t){this.handlers[t]&&(this.handlers[t]=null)},r.prototype.forEach=function(t){i.forEach(this.handlers,function(e){null!==e&&t(e)})},t.exports=r},function(t,e,n){"use strict";function r(t){t.cancelToken&&t.cancelToken.throwIfRequested()}var i=n(0),o=n(19),a=n(4),s=n(1);t.exports=function(t){r(t),t.headers=t.headers||{},t.data=o(t.data,t.headers,t.transformRequest),t.headers=i.merge(t.headers.common||{},t.headers[t.method]||{},t.headers||{}),i.forEach(["delete","get","head","post","put","patch","common"],function(e){delete t.headers[e]});var e=t.adapter||s.adapter;return e(t).then(function(e){return r(t),e.data=o(e.data,e.headers,t.transformResponse),e},function(e){return a(e)||(r(t),e&&e.response&&(e.response.data=o(e.response.data,e.response.headers,t.transformResponse))),Promise.reject(e)})}},function(t,e,n){"use strict";t.exports=function(t,e,n,r){return t.config=e,n&&(t.code=n),t.response=r,t}},function(t,e,n){"use strict";var r=n(5);t.exports=function(t,e,n){var i=n.config.validateStatus;n.status&&i&&!i(n.status)?e(r("Request failed with status code "+n.status,n.config,null,n)):t(n)}},function(t,e,n){"use strict";var r=n(0);t.exports=function(t,e,n){return r.forEach(n,function(n){t=n(t,e)}),t}},function(t,e,n){"use strict";function r(){this.message="String contains an invalid character"}function i(t){for(var e,n,i=String(t),a="",s=0,u=o;i.charAt(0|s)||(u="=",s%1);a+=u.charAt(63&e>>8-s%1*8)){if(n=i.charCodeAt(s+=.75),n>255)throw new r;e=e<<8|n}return a}var o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";r.prototype=new Error,r.prototype.code=5,r.prototype.name="InvalidCharacterError",t.exports=i},function(t,e,n){"use strict";function r(t){return encodeURIComponent(t).replace(/%40/gi,"@").replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var i=n(0);t.exports=function(t,e,n){if(!e)return t;var o;if(n)o=n(e);else if(i.isURLSearchParams(e))o=e.toString();else{var a=[];i.forEach(e,function(t,e){null!==t&&"undefined"!=typeof t&&(i.isArray(t)&&(e+="[]"),i.isArray(t)||(t=[t]),i.forEach(t,function(t){i.isDate(t)?t=t.toISOString():i.isObject(t)&&(t=JSON.stringify(t)),a.push(r(e)+"="+r(t))}))}),o=a.join("&")}return o&&(t+=(t.indexOf("?")===-1?"?":"&")+o),t}},function(t,e,n){"use strict";t.exports=function(t,e){return t.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,"")}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?function(){return{write:function(t,e,n,i,o,a){var s=[];s.push(t+"="+encodeURIComponent(e)),r.isNumber(n)&&s.push("expires="+new Date(n).toGMTString()),r.isString(i)&&s.push("path="+i),r.isString(o)&&s.push("domain="+o),a===!0&&s.push("secure"),document.cookie=s.join("; ")},read:function(t){var e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(t){this.write(t,"",Date.now()-864e5)}}}():function(){return{write:function(){},read:function(){return null},remove:function(){}}}()},function(t,e,n){"use strict";t.exports=function(t){return/^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(t)}},function(t,e,n){"use strict";var r=n(0);t.exports=r.isStandardBrowserEnv()?function(){function t(t){var e=t;return n&&(i.setAttribute("href",e),e=i.href),i.setAttribute("href",e),{href:i.href,protocol:i.protocol?i.protocol.replace(/:$/,""):"",host:i.host,search:i.search?i.search.replace(/^\?/,""):"",hash:i.hash?i.hash.replace(/^#/,""):"",hostname:i.hostname,port:i.port,pathname:"/"===i.pathname.charAt(0)?i.pathname:"/"+i.pathname}}var e,n=/(msie|trident)/i.test(navigator.userAgent),i=document.createElement("a");return e=t(window.location.href),function(n){var i=r.isString(n)?t(n):n;return i.protocol===e.protocol&&i.host===e.host}}():function(){return function(){return!0}}()},function(t,e,n){"use strict";var r=n(0);t.exports=function(t,e){r.forEach(t,function(n,r){r!==e&&r.toUpperCase()===e.toUpperCase()&&(t[e]=n,delete t[r])})}},function(t,e,n){"use strict";var r=n(0);t.exports=function(t){var e,n,i,o={};return t?(r.forEach(t.split("\n"),function(t){i=t.indexOf(":"),e=r.trim(t.substr(0,i)).toLowerCase(),n=r.trim(t.substr(i+1)),e&&(o[e]=o[e]?o[e]+", "+n:n)}),o):o}},function(t,e,n){"use strict";t.exports=function(t){return function(e){return t.apply(null,e)}}},function(t,e,n){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.default={mounted:function(){console.log("Component mounted.")}}},function(t,e,n){window._=n(32),window.$=window.jQuery=n(7),n(31),window.Vue=n(36),window.axios=n(11),window.axios.defaults.headers.common={"X-Requested-With":"XMLHttpRequest"}},function(t,e,n){(function(t){/*! * Bootstrap v3.3.7 (http://getbootstrap.com) * Copyright 2011-2016 Twitter, Inc. * Licensed under the MIT license */ if("undefined"==typeof t)throw new Error("Bootstrap's JavaScript requires jQuery");+function(t){"use strict";var e=t.fn.jquery.split(" ")[0].split(".");if(e[0]<2&&e[1]<9||1==e[0]&&9==e[1]&&e[2]<1||e[0]>3)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 4")}(t),+function(t){"use strict";function e(){var t=document.createElement("bootstrap"),e={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var n in e)if(void 0!==t.style[n])return{end:e[n]};return!1}t.fn.emulateTransitionEnd=function(e){var n=!1,r=this;t(this).one("bsTransitionEnd",function(){n=!0});var i=function(){n||t(r).trigger(t.support.transition.end)};return setTimeout(i,e),this},t(function(){t.support.transition=e(),t.support.transition&&(t.event.special.bsTransitionEnd={bindType:t.support.transition.end,delegateType:t.support.transition.end,handle:function(e){if(t(e.target).is(this))return e.handleObj.handler.apply(this,arguments)}})})}(t),+function(t){"use strict";function e(e){return this.each(function(){var n=t(this),i=n.data("bs.alert");i||n.data("bs.alert",i=new r(this)),"string"==typeof e&&i[e].call(n)})}var n='[data-dismiss="alert"]',r=function(e){t(e).on("click",n,this.close)};r.VERSION="3.3.7",r.TRANSITION_DURATION=150,r.prototype.close=function(e){function n(){a.detach().trigger("closed.bs.alert").remove()}var i=t(this),o=i.attr("data-target");o||(o=i.attr("href"),o=o&&o.replace(/.*(?=#[^\s]*$)/,""));var a=t("#"===o?[]:o);e&&e.preventDefault(),a.length||(a=i.closest(".alert")),a.trigger(e=t.Event("close.bs.alert")),e.isDefaultPrevented()||(a.removeClass("in"),t.support.transition&&a.hasClass("fade")?a.one("bsTransitionEnd",n).emulateTransitionEnd(r.TRANSITION_DURATION):n())};var i=t.fn.alert;t.fn.alert=e,t.fn.alert.Constructor=r,t.fn.alert.noConflict=function(){return t.fn.alert=i,this},t(document).on("click.bs.alert.data-api",n,r.prototype.close)}(t),+function(t){"use strict";function e(e){return this.each(function(){var r=t(this),i=r.data("bs.button"),o="object"==typeof e&&e;i||r.data("bs.button",i=new n(this,o)),"toggle"==e?i.toggle():e&&i.setState(e)})}var n=function(e,r){this.$element=t(e),this.options=t.extend({},n.DEFAULTS,r),this.isLoading=!1};n.VERSION="3.3.7",n.DEFAULTS={loadingText:"loading..."},n.prototype.setState=function(e){var n="disabled",r=this.$element,i=r.is("input")?"val":"html",o=r.data();e+="Text",null==o.resetText&&r.data("resetText",r[i]()),setTimeout(t.proxy(function(){r[i](null==o[e]?this.options[e]:o[e]),"loadingText"==e?(this.isLoading=!0,r.addClass(n).attr(n,n).prop(n,!0)):this.isLoading&&(this.isLoading=!1,r.removeClass(n).removeAttr(n).prop(n,!1))},this),0)},n.prototype.toggle=function(){var t=!0,e=this.$element.closest('[data-toggle="buttons"]');if(e.length){var n=this.$element.find("input");"radio"==n.prop("type")?(n.prop("checked")&&(t=!1),e.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==n.prop("type")&&(n.prop("checked")!==this.$element.hasClass("active")&&(t=!1),this.$element.toggleClass("active")),n.prop("checked",this.$element.hasClass("active")),t&&n.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var r=t.fn.button;t.fn.button=e,t.fn.button.Constructor=n,t.fn.button.noConflict=function(){return t.fn.button=r,this},t(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(n){var r=t(n.target).closest(".btn");e.call(r,"toggle"),t(n.target).is('input[type="radio"], input[type="checkbox"]')||(n.preventDefault(),r.is("input,button")?r.trigger("focus"):r.find("input:visible,button:visible").first().trigger("focus"))}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(e){t(e.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(e.type))})}(t),+function(t){"use strict";function e(e){return this.each(function(){var r=t(this),i=r.data("bs.carousel"),o=t.extend({},n.DEFAULTS,r.data(),"object"==typeof e&&e),a="string"==typeof e?e:o.slide;i||r.data("bs.carousel",i=new n(this,o)),"number"==typeof e?i.to(e):a?i[a]():o.interval&&i.pause().cycle()})}var n=function(e,n){this.$element=t(e),this.$indicators=this.$element.find(".carousel-indicators"),this.options=n,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",t.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",t.proxy(this.pause,this)).on("mouseleave.bs.carousel",t.proxy(this.cycle,this))};n.VERSION="3.3.7",n.TRANSITION_DURATION=600,n.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},n.prototype.keydown=function(t){if(!/input|textarea/i.test(t.target.tagName)){switch(t.which){case 37:this.prev();break;case 39:this.next();break;default:return}t.preventDefault()}},n.prototype.cycle=function(e){return e||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(t.proxy(this.next,this),this.options.interval)),this},n.prototype.getItemIndex=function(t){return this.$items=t.parent().children(".item"),this.$items.index(t||this.$active)},n.prototype.getItemForDirection=function(t,e){var n=this.getItemIndex(e),r="prev"==t&&0===n||"next"==t&&n==this.$items.length-1;if(r&&!this.options.wrap)return e;var i="prev"==t?-1:1,o=(n+i)%this.$items.length;return this.$items.eq(o)},n.prototype.to=function(t){var e=this,n=this.getItemIndex(this.$active=this.$element.find(".item.active"));if(!(t>this.$items.length-1||t<0))return this.sliding?this.$element.one("slid.bs.carousel",function(){e.to(t)}):n==t?this.pause().cycle():this.slide(t>n?"next":"prev",this.$items.eq(t))},n.prototype.pause=function(e){return e||(this.paused=!0),this.$element.find(".next, .prev").length&&t.support.transition&&(this.$element.trigger(t.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},n.prototype.next=function(){if(!this.sliding)return this.slide("next")},n.prototype.prev=function(){if(!this.sliding)return this.slide("prev")},n.prototype.slide=function(e,r){var i=this.$element.find(".item.active"),o=r||this.getItemForDirection(e,i),a=this.interval,s="next"==e?"left":"right",u=this;if(o.hasClass("active"))return this.sliding=!1;var c=o[0],l=t.Event("slide.bs.carousel",{relatedTarget:c,direction:s});if(this.$element.trigger(l),!l.isDefaultPrevented()){if(this.sliding=!0,a&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var f=t(this.$indicators.children()[this.getItemIndex(o)]);f&&f.addClass("active")}var p=t.Event("slid.bs.carousel",{relatedTarget:c,direction:s});return t.support.transition&&this.$element.hasClass("slide")?(o.addClass(e),o[0].offsetWidth,i.addClass(s),o.addClass(s),i.one("bsTransitionEnd",function(){o.removeClass([e,s].join(" ")).addClass("active"),i.removeClass(["active",s].join(" ")),u.sliding=!1,setTimeout(function(){u.$element.trigger(p)},0)}).emulateTransitionEnd(n.TRANSITION_DURATION)):(i.removeClass("active"),o.addClass("active"),this.sliding=!1,this.$element.trigger(p)),a&&this.cycle(),this}};var r=t.fn.carousel;t.fn.carousel=e,t.fn.carousel.Constructor=n,t.fn.carousel.noConflict=function(){return t.fn.carousel=r,this};var i=function(n){var r,i=t(this),o=t(i.attr("data-target")||(r=i.attr("href"))&&r.replace(/.*(?=#[^\s]+$)/,""));if(o.hasClass("carousel")){var a=t.extend({},o.data(),i.data()),s=i.attr("data-slide-to");s&&(a.interval=!1),e.call(o,a),s&&o.data("bs.carousel").to(s),n.preventDefault()}};t(document).on("click.bs.carousel.data-api","[data-slide]",i).on("click.bs.carousel.data-api","[data-slide-to]",i),t(window).on("load",function(){t('[data-ride="carousel"]').each(function(){var n=t(this);e.call(n,n.data())})})}(t),+function(t){"use strict";function e(e){var n,r=e.attr("data-target")||(n=e.attr("href"))&&n.replace(/.*(?=#[^\s]+$)/,"");return t(r)}function n(e){return this.each(function(){var n=t(this),i=n.data("bs.collapse"),o=t.extend({},r.DEFAULTS,n.data(),"object"==typeof e&&e);!i&&o.toggle&&/show|hide/.test(e)&&(o.toggle=!1),i||n.data("bs.collapse",i=new r(this,o)),"string"==typeof e&&i[e]()})}var r=function(e,n){this.$element=t(e),this.options=t.extend({},r.DEFAULTS,n),this.$trigger=t('[data-toggle="collapse"][href="#'+e.id+'"],[data-toggle="collapse"][data-target="#'+e.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};r.VERSION="3.3.7",r.TRANSITION_DURATION=350,r.DEFAULTS={toggle:!0},r.prototype.dimension=function(){var t=this.$element.hasClass("width");return t?"width":"height"},r.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var e,i=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(i&&i.length&&(e=i.data("bs.collapse"),e&&e.transitioning))){var o=t.Event("show.bs.collapse");if(this.$element.trigger(o),!o.isDefaultPrevented()){i&&i.length&&(n.call(i,"hide"),e||i.data("bs.collapse",null));var a=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[a](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var s=function(){this.$element.removeClass("collapsing").addClass("collapse in")[a](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!t.support.transition)return s.call(this);var u=t.camelCase(["scroll",a].join("-"));this.$element.one("bsTransitionEnd",t.proxy(s,this)).emulateTransitionEnd(r.TRANSITION_DURATION)[a](this.$element[0][u])}}}},r.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var e=t.Event("hide.bs.collapse");if(this.$element.trigger(e),!e.isDefaultPrevented()){var n=this.dimension();this.$element[n](this.$element[n]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var i=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return t.support.transition?void this.$element[n](0).one("bsTransitionEnd",t.proxy(i,this)).emulateTransitionEnd(r.TRANSITION_DURATION):i.call(this)}}},r.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},r.prototype.getParent=function(){return t(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(t.proxy(function(n,r){var i=t(r);this.addAriaAndCollapsedClass(e(i),i)},this)).end()},r.prototype.addAriaAndCollapsedClass=function(t,e){var n=t.hasClass("in");t.attr("aria-expanded",n),e.toggleClass("collapsed",!n).attr("aria-expanded",n)};var i=t.fn.collapse;t.fn.collapse=n,t.fn.collapse.Constructor=r,t.fn.collapse.noConflict=function(){return t.fn.collapse=i,this},t(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(r){var i=t(this);i.attr("data-target")||r.preventDefault();var o=e(i),a=o.data("bs.collapse"),s=a?"toggle":i.data();n.call(o,s)})}(t),+function(t){"use strict";function e(e){var n=e.attr("data-target");n||(n=e.attr("href"),n=n&&/#[A-Za-z]/.test(n)&&n.replace(/.*(?=#[^\s]*$)/,""));var r=n&&t(n);return r&&r.length?r:e.parent()}function n(n){n&&3===n.which||(t(i).remove(),t(o).each(function(){var r=t(this),i=e(r),o={relatedTarget:this};i.hasClass("open")&&(n&&"click"==n.type&&/input|textarea/i.test(n.target.tagName)&&t.contains(i[0],n.target)||(i.trigger(n=t.Event("hide.bs.dropdown",o)),n.isDefaultPrevented()||(r.attr("aria-expanded","false"),i.removeClass("open").trigger(t.Event("hidden.bs.dropdown",o)))))}))}function r(e){return this.each(function(){var n=t(this),r=n.data("bs.dropdown");r||n.data("bs.dropdown",r=new a(this)),"string"==typeof e&&r[e].call(n)})}var i=".dropdown-backdrop",o='[data-toggle="dropdown"]',a=function(e){t(e).on("click.bs.dropdown",this.toggle)};a.VERSION="3.3.7",a.prototype.toggle=function(r){var i=t(this);if(!i.is(".disabled, :disabled")){var o=e(i),a=o.hasClass("open");if(n(),!a){"ontouchstart"in document.documentElement&&!o.closest(".navbar-nav").length&&t(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(t(this)).on("click",n);var s={relatedTarget:this};if(o.trigger(r=t.Event("show.bs.dropdown",s)),r.isDefaultPrevented())return;i.trigger("focus").attr("aria-expanded","true"),o.toggleClass("open").trigger(t.Event("shown.bs.dropdown",s))}return!1}},a.prototype.keydown=function(n){if(/(38|40|27|32)/.test(n.which)&&!/input|textarea/i.test(n.target.tagName)){var r=t(this);if(n.preventDefault(),n.stopPropagation(),!r.is(".disabled, :disabled")){var i=e(r),a=i.hasClass("open");if(!a&&27!=n.which||a&&27==n.which)return 27==n.which&&i.find(o).trigger("focus"),r.trigger("click");var s=" li:not(.disabled):visible a",u=i.find(".dropdown-menu"+s);if(u.length){var c=u.index(n.target);38==n.which&&c>0&&c--,40==n.which&&c<u.length-1&&c++,~c||(c=0),u.eq(c).trigger("focus")}}}};var s=t.fn.dropdown;t.fn.dropdown=r,t.fn.dropdown.Constructor=a,t.fn.dropdown.noConflict=function(){return t.fn.dropdown=s,this},t(document).on("click.bs.dropdown.data-api",n).on("click.bs.dropdown.data-api",".dropdown form",function(t){t.stopPropagation()}).on("click.bs.dropdown.data-api",o,a.prototype.toggle).on("keydown.bs.dropdown.data-api",o,a.prototype.keydown).on("keydown.bs.dropdown.data-api",".dropdown-menu",a.prototype.keydown)}(t),+function(t){"use strict";function e(e,r){return this.each(function(){var i=t(this),o=i.data("bs.modal"),a=t.extend({},n.DEFAULTS,i.data(),"object"==typeof e&&e);o||i.data("bs.modal",o=new n(this,a)),"string"==typeof e?o[e](r):a.show&&o.show(r)})}var n=function(e,n){this.options=n,this.$body=t(document.body),this.$element=t(e),this.$dialog=this.$element.find(".modal-dialog"),this.$backdrop=null,this.isShown=null,this.originalBodyPad=null,this.scrollbarWidth=0,this.ignoreBackdropClick=!1,this.options.remote&&this.$element.find(".modal-content").load(this.options.remote,t.proxy(function(){this.$element.trigger("loaded.bs.modal")},this))};n.VERSION="3.3.7",n.TRANSITION_DURATION=300,n.BACKDROP_TRANSITION_DURATION=150,n.DEFAULTS={backdrop:!0,keyboard:!0,show:!0},n.prototype.toggle=function(t){return this.isShown?this.hide():this.show(t)},n.prototype.show=function(e){var r=this,i=t.Event("show.bs.modal",{relatedTarget:e});this.$element.trigger(i),this.isShown||i.isDefaultPrevented()||(this.isShown=!0,this.checkScrollbar(),this.setScrollbar(),this.$body.addClass("modal-open"),this.escape(),this.resize(),this.$element.on("click.dismiss.bs.modal",'[data-dismiss="modal"]',t.proxy(this.hide,this)),this.$dialog.on("mousedown.dismiss.bs.modal",function(){r.$element.one("mouseup.dismiss.bs.modal",function(e){t(e.target).is(r.$element)&&(r.ignoreBackdropClick=!0)})}),this.backdrop(function(){var i=t.support.transition&&r.$element.hasClass("fade");r.$element.parent().length||r.$element.appendTo(r.$body),r.$element.show().scrollTop(0),r.adjustDialog(),i&&r.$element[0].offsetWidth,r.$element.addClass("in"),r.enforceFocus();var o=t.Event("shown.bs.modal",{relatedTarget:e});i?r.$dialog.one("bsTransitionEnd",function(){r.$element.trigger("focus").trigger(o)}).emulateTransitionEnd(n.TRANSITION_DURATION):r.$element.trigger("focus").trigger(o)}))},n.prototype.hide=function(e){e&&e.preventDefault(),e=t.Event("hide.bs.modal"),this.$element.trigger(e),this.isShown&&!e.isDefaultPrevented()&&(this.isShown=!1,this.escape(),this.resize(),t(document).off("focusin.bs.modal"),this.$element.removeClass("in").off("click.dismiss.bs.modal").off("mouseup.dismiss.bs.modal"),this.$dialog.off("mousedown.dismiss.bs.modal"),t.support.transition&&this.$element.hasClass("fade")?this.$element.one("bsTransitionEnd",t.proxy(this.hideModal,this)).emulateTransitionEnd(n.TRANSITION_DURATION):this.hideModal())},n.prototype.enforceFocus=function(){t(document).off("focusin.bs.modal").on("focusin.bs.modal",t.proxy(function(t){document===t.target||this.$element[0]===t.target||this.$element.has(t.target).length||this.$element.trigger("focus")},this))},n.prototype.escape=function(){this.isShown&&this.options.keyboard?this.$element.on("keydown.dismiss.bs.modal",t.proxy(function(t){27==t.which&&this.hide()},this)):this.isShown||this.$element.off("keydown.dismiss.bs.modal")},n.prototype.resize=function(){this.isShown?t(window).on("resize.bs.modal",t.proxy(this.handleUpdate,this)):t(window).off("resize.bs.modal")},n.prototype.hideModal=function(){var t=this;this.$element.hide(),this.backdrop(function(){t.$body.removeClass("modal-open"),t.resetAdjustments(),t.resetScrollbar(),t.$element.trigger("hidden.bs.modal")})},n.prototype.removeBackdrop=function(){this.$backdrop&&this.$backdrop.remove(),this.$backdrop=null},n.prototype.backdrop=function(e){var r=this,i=this.$element.hasClass("fade")?"fade":"";if(this.isShown&&this.options.backdrop){var o=t.support.transition&&i;if(this.$backdrop=t(document.createElement("div")).addClass("modal-backdrop "+i).appendTo(this.$body),this.$element.on("click.dismiss.bs.modal",t.proxy(function(t){return this.ignoreBackdropClick?void(this.ignoreBackdropClick=!1):void(t.target===t.currentTarget&&("static"==this.options.backdrop?this.$element[0].focus():this.hide()))},this)),o&&this.$backdrop[0].offsetWidth,this.$backdrop.addClass("in"),!e)return;o?this.$backdrop.one("bsTransitionEnd",e).emulateTransitionEnd(n.BACKDROP_TRANSITION_DURATION):e()}else if(!this.isShown&&this.$backdrop){this.$backdrop.removeClass("in");var a=function(){r.removeBackdrop(),e&&e()};t.support.transition&&this.$element.hasClass("fade")?this.$backdrop.one("bsTransitionEnd",a).emulateTransitionEnd(n.BACKDROP_TRANSITION_DURATION):a()}else e&&e()},n.prototype.handleUpdate=function(){this.adjustDialog()},n.prototype.adjustDialog=function(){var t=this.$element[0].scrollHeight>document.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&t?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!t?this.scrollbarWidth:""})},n.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},n.prototype.checkScrollbar=function(){var t=window.innerWidth;if(!t){var e=document.documentElement.getBoundingClientRect();t=e.right-Math.abs(e.left)}this.bodyIsOverflowing=document.body.clientWidth<t,this.scrollbarWidth=this.measureScrollbar()},n.prototype.setScrollbar=function(){var t=parseInt(this.$body.css("padding-right")||0,10);this.originalBodyPad=document.body.style.paddingRight||"",this.bodyIsOverflowing&&this.$body.css("padding-right",t+this.scrollbarWidth)},n.prototype.resetScrollbar=function(){this.$body.css("padding-right",this.originalBodyPad)},n.prototype.measureScrollbar=function(){var t=document.createElement("div");t.className="modal-scrollbar-measure",this.$body.append(t);var e=t.offsetWidth-t.clientWidth;return this.$body[0].removeChild(t),e};var r=t.fn.modal;t.fn.modal=e,t.fn.modal.Constructor=n,t.fn.modal.noConflict=function(){return t.fn.modal=r,this},t(document).on("click.bs.modal.data-api",'[data-toggle="modal"]',function(n){var r=t(this),i=r.attr("href"),o=t(r.attr("data-target")||i&&i.replace(/.*(?=#[^\s]+$)/,"")),a=o.data("bs.modal")?"toggle":t.extend({remote:!/#/.test(i)&&i},o.data(),r.data());r.is("a")&&n.preventDefault(),o.one("show.bs.modal",function(t){t.isDefaultPrevented()||o.one("hidden.bs.modal",function(){r.is(":visible")&&r.trigger("focus")})}),e.call(o,a,this)})}(t),+function(t){"use strict";function e(e){return this.each(function(){var r=t(this),i=r.data("bs.tooltip"),o="object"==typeof e&&e;!i&&/destroy|hide/.test(e)||(i||r.data("bs.tooltip",i=new n(this,o)),"string"==typeof e&&i[e]())})}var n=function(t,e){this.type=null,this.options=null,this.enabled=null,this.timeout=null,this.hoverState=null,this.$element=null,this.inState=null,this.init("tooltip",t,e)};n.VERSION="3.3.7",n.TRANSITION_DURATION=150,n.DEFAULTS={animation:!0,placement:"top",selector:!1,template:'<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},n.prototype.init=function(e,n,r){if(this.enabled=!0,this.type=e,this.$element=t(n),this.options=this.getOptions(r),this.$viewport=this.options.viewport&&t(t.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var i=this.options.trigger.split(" "),o=i.length;o--;){var a=i[o];if("click"==a)this.$element.on("click."+this.type,this.options.selector,t.proxy(this.toggle,this));else if("manual"!=a){var s="hover"==a?"mouseenter":"focusin",u="hover"==a?"mouseleave":"focusout";this.$element.on(s+"."+this.type,this.options.selector,t.proxy(this.enter,this)),this.$element.on(u+"."+this.type,this.options.selector,t.proxy(this.leave,this))}}this.options.selector?this._options=t.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},n.prototype.getDefaults=function(){return n.DEFAULTS},n.prototype.getOptions=function(e){return e=t.extend({},this.getDefaults(),this.$element.data(),e),e.delay&&"number"==typeof e.delay&&(e.delay={show:e.delay,hide:e.delay}),e},n.prototype.getDelegateOptions=function(){var e={},n=this.getDefaults();return this._options&&t.each(this._options,function(t,r){n[t]!=r&&(e[t]=r)}),e},n.prototype.enter=function(e){var n=e instanceof this.constructor?e:t(e.currentTarget).data("bs."+this.type);return n||(n=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,n)),e instanceof t.Event&&(n.inState["focusin"==e.type?"focus":"hover"]=!0),n.tip().hasClass("in")||"in"==n.hoverState?void(n.hoverState="in"):(clearTimeout(n.timeout),n.hoverState="in",n.options.delay&&n.options.delay.show?void(n.timeout=setTimeout(function(){"in"==n.hoverState&&n.show()},n.options.delay.show)):n.show())},n.prototype.isInStateTrue=function(){for(var t in this.inState)if(this.inState[t])return!0;return!1},n.prototype.leave=function(e){var n=e instanceof this.constructor?e:t(e.currentTarget).data("bs."+this.type);if(n||(n=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,n)),e instanceof t.Event&&(n.inState["focusout"==e.type?"focus":"hover"]=!1),!n.isInStateTrue())return clearTimeout(n.timeout),n.hoverState="out",n.options.delay&&n.options.delay.hide?void(n.timeout=setTimeout(function(){"out"==n.hoverState&&n.hide()},n.options.delay.hide)):n.hide()},n.prototype.show=function(){var e=t.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(e);var r=t.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(e.isDefaultPrevented()||!r)return;var i=this,o=this.tip(),a=this.getUID(this.type);this.setContent(),o.attr("id",a),this.$element.attr("aria-describedby",a),this.options.animation&&o.addClass("fade");var s="function"==typeof this.options.placement?this.options.placement.call(this,o[0],this.$element[0]):this.options.placement,u=/\s?auto?\s?/i,c=u.test(s);c&&(s=s.replace(u,"")||"top"),o.detach().css({top:0,left:0,display:"block"}).addClass(s).data("bs."+this.type,this),this.options.container?o.appendTo(this.options.container):o.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var l=this.getPosition(),f=o[0].offsetWidth,p=o[0].offsetHeight;if(c){var d=s,h=this.getPosition(this.$viewport);s="bottom"==s&&l.bottom+p>h.bottom?"top":"top"==s&&l.top-p<h.top?"bottom":"right"==s&&l.right+f>h.width?"left":"left"==s&&l.left-f<h.left?"right":s,o.removeClass(d).addClass(s)}var v=this.getCalculatedOffset(s,l,f,p);this.applyPlacement(v,s);var g=function(){var t=i.hoverState;i.$element.trigger("shown.bs."+i.type),i.hoverState=null,"out"==t&&i.leave(i)};t.support.transition&&this.$tip.hasClass("fade")?o.one("bsTransitionEnd",g).emulateTransitionEnd(n.TRANSITION_DURATION):g()}},n.prototype.applyPlacement=function(e,n){var r=this.tip(),i=r[0].offsetWidth,o=r[0].offsetHeight,a=parseInt(r.css("margin-top"),10),s=parseInt(r.css("margin-left"),10);isNaN(a)&&(a=0),isNaN(s)&&(s=0),e.top+=a,e.left+=s,t.offset.setOffset(r[0],t.extend({using:function(t){r.css({top:Math.round(t.top),left:Math.round(t.left)})}},e),0),r.addClass("in");var u=r[0].offsetWidth,c=r[0].offsetHeight;"top"==n&&c!=o&&(e.top=e.top+o-c);var l=this.getViewportAdjustedDelta(n,e,u,c);l.left?e.left+=l.left:e.top+=l.top;var f=/top|bottom/.test(n),p=f?2*l.left-i+u:2*l.top-o+c,d=f?"offsetWidth":"offsetHeight";r.offset(e),this.replaceArrow(p,r[0][d],f)},n.prototype.replaceArrow=function(t,e,n){this.arrow().css(n?"left":"top",50*(1-t/e)+"%").css(n?"top":"left","")},n.prototype.setContent=function(){var t=this.tip(),e=this.getTitle();t.find(".tooltip-inner")[this.options.html?"html":"text"](e),t.removeClass("fade in top bottom left right")},n.prototype.hide=function(e){function r(){"in"!=i.hoverState&&o.detach(),i.$element&&i.$element.removeAttr("aria-describedby").trigger("hidden.bs."+i.type),e&&e()}var i=this,o=t(this.$tip),a=t.Event("hide.bs."+this.type);if(this.$element.trigger(a),!a.isDefaultPrevented())return o.removeClass("in"),t.support.transition&&o.hasClass("fade")?o.one("bsTransitionEnd",r).emulateTransitionEnd(n.TRANSITION_DURATION):r(),this.hoverState=null,this},n.prototype.fixTitle=function(){var t=this.$element;(t.attr("title")||"string"!=typeof t.attr("data-original-title"))&&t.attr("data-original-title",t.attr("title")||"").attr("title","")},n.prototype.hasContent=function(){return this.getTitle()},n.prototype.getPosition=function(e){e=e||this.$element;var n=e[0],r="BODY"==n.tagName,i=n.getBoundingClientRect();null==i.width&&(i=t.extend({},i,{width:i.right-i.left,height:i.bottom-i.top}));var o=window.SVGElement&&n instanceof window.SVGElement,a=r?{top:0,left:0}:o?null:e.offset(),s={scroll:r?document.documentElement.scrollTop||document.body.scrollTop:e.scrollTop()},u=r?{width:t(window).width(),height:t(window).height()}:null;return t.extend({},i,s,u,a)},n.prototype.getCalculatedOffset=function(t,e,n,r){return"bottom"==t?{top:e.top+e.height,left:e.left+e.width/2-n/2}:"top"==t?{top:e.top-r,left:e.left+e.width/2-n/2}:"left"==t?{top:e.top+e.height/2-r/2,left:e.left-n}:{top:e.top+e.height/2-r/2,left:e.left+e.width}},n.prototype.getViewportAdjustedDelta=function(t,e,n,r){var i={top:0,left:0};if(!this.$viewport)return i;var o=this.options.viewport&&this.options.viewport.padding||0,a=this.getPosition(this.$viewport);if(/right|left/.test(t)){var s=e.top-o-a.scroll,u=e.top+o-a.scroll+r;s<a.top?i.top=a.top-s:u>a.top+a.height&&(i.top=a.top+a.height-u)}else{var c=e.left-o,l=e.left+o+n;c<a.left?i.left=a.left-c:l>a.right&&(i.left=a.left+a.width-l)}return i},n.prototype.getTitle=function(){var t,e=this.$element,n=this.options;return t=e.attr("data-original-title")||("function"==typeof n.title?n.title.call(e[0]):n.title)},n.prototype.getUID=function(t){do t+=~~(1e6*Math.random());while(document.getElementById(t));return t},n.prototype.tip=function(){if(!this.$tip&&(this.$tip=t(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},n.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},n.prototype.enable=function(){this.enabled=!0},n.prototype.disable=function(){this.enabled=!1},n.prototype.toggleEnabled=function(){this.enabled=!this.enabled},n.prototype.toggle=function(e){var n=this;e&&(n=t(e.currentTarget).data("bs."+this.type),n||(n=new this.constructor(e.currentTarget,this.getDelegateOptions()),t(e.currentTarget).data("bs."+this.type,n))),e?(n.inState.click=!n.inState.click,n.isInStateTrue()?n.enter(n):n.leave(n)):n.tip().hasClass("in")?n.leave(n):n.enter(n)},n.prototype.destroy=function(){var t=this;clearTimeout(this.timeout),this.hide(function(){t.$element.off("."+t.type).removeData("bs."+t.type),t.$tip&&t.$tip.detach(),t.$tip=null,t.$arrow=null,t.$viewport=null,t.$element=null})};var r=t.fn.tooltip;t.fn.tooltip=e,t.fn.tooltip.Constructor=n,t.fn.tooltip.noConflict=function(){return t.fn.tooltip=r,this}}(t),+function(t){"use strict";function e(e){return this.each(function(){var r=t(this),i=r.data("bs.popover"),o="object"==typeof e&&e;!i&&/destroy|hide/.test(e)||(i||r.data("bs.popover",i=new n(this,o)),"string"==typeof e&&i[e]())})}var n=function(t,e){this.init("popover",t,e)};if(!t.fn.tooltip)throw new Error("Popover requires tooltip.js");n.VERSION="3.3.7",n.DEFAULTS=t.extend({},t.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:'<div class="popover" role="tooltip"><div class="arrow"></div><h3 class="popover-title"></h3><div class="popover-content"></div></div>'}),n.prototype=t.extend({},t.fn.tooltip.Constructor.prototype),n.prototype.constructor=n,n.prototype.getDefaults=function(){return n.DEFAULTS},n.prototype.setContent=function(){var t=this.tip(),e=this.getTitle(),n=this.getContent();t.find(".popover-title")[this.options.html?"html":"text"](e),t.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof n?"html":"append":"text"](n),t.removeClass("fade top bottom left right in"),t.find(".popover-title").html()||t.find(".popover-title").hide()},n.prototype.hasContent=function(){return this.getTitle()||this.getContent()},n.prototype.getContent=function(){var t=this.$element,e=this.options;return t.attr("data-content")||("function"==typeof e.content?e.content.call(t[0]):e.content)},n.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var r=t.fn.popover;t.fn.popover=e,t.fn.popover.Constructor=n,t.fn.popover.noConflict=function(){return t.fn.popover=r,this}}(t),+function(t){"use strict";function e(n,r){this.$body=t(document.body),this.$scrollElement=t(t(n).is(document.body)?window:n),this.options=t.extend({},e.DEFAULTS,r),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",t.proxy(this.process,this)),this.refresh(),this.process()}function n(n){return this.each(function(){var r=t(this),i=r.data("bs.scrollspy"),o="object"==typeof n&&n;i||r.data("bs.scrollspy",i=new e(this,o)),"string"==typeof n&&i[n]()})}e.VERSION="3.3.7",e.DEFAULTS={offset:10},e.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},e.prototype.refresh=function(){var e=this,n="offset",r=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),t.isWindow(this.$scrollElement[0])||(n="position",r=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var e=t(this),i=e.data("target")||e.attr("href"),o=/^#./.test(i)&&t(i);return o&&o.length&&o.is(":visible")&&[[o[n]().top+r,i]]||null}).sort(function(t,e){return t[0]-e[0]}).each(function(){e.offsets.push(this[0]),e.targets.push(this[1])})},e.prototype.process=function(){var t,e=this.$scrollElement.scrollTop()+this.options.offset,n=this.getScrollHeight(),r=this.options.offset+n-this.$scrollElement.height(),i=this.offsets,o=this.targets,a=this.activeTarget;if(this.scrollHeight!=n&&this.refresh(),e>=r)return a!=(t=o[o.length-1])&&this.activate(t);if(a&&e<i[0])return this.activeTarget=null,this.clear();for(t=i.length;t--;)a!=o[t]&&e>=i[t]&&(void 0===i[t+1]||e<i[t+1])&&this.activate(o[t])},e.prototype.activate=function(e){this.activeTarget=e,this.clear(); var n=this.selector+'[data-target="'+e+'"],'+this.selector+'[href="'+e+'"]',r=t(n).parents("li").addClass("active");r.parent(".dropdown-menu").length&&(r=r.closest("li.dropdown").addClass("active")),r.trigger("activate.bs.scrollspy")},e.prototype.clear=function(){t(this.selector).parentsUntil(this.options.target,".active").removeClass("active")};var r=t.fn.scrollspy;t.fn.scrollspy=n,t.fn.scrollspy.Constructor=e,t.fn.scrollspy.noConflict=function(){return t.fn.scrollspy=r,this},t(window).on("load.bs.scrollspy.data-api",function(){t('[data-spy="scroll"]').each(function(){var e=t(this);n.call(e,e.data())})})}(t),+function(t){"use strict";function e(e){return this.each(function(){var r=t(this),i=r.data("bs.tab");i||r.data("bs.tab",i=new n(this)),"string"==typeof e&&i[e]()})}var n=function(e){this.element=t(e)};n.VERSION="3.3.7",n.TRANSITION_DURATION=150,n.prototype.show=function(){var e=this.element,n=e.closest("ul:not(.dropdown-menu)"),r=e.data("target");if(r||(r=e.attr("href"),r=r&&r.replace(/.*(?=#[^\s]*$)/,"")),!e.parent("li").hasClass("active")){var i=n.find(".active:last a"),o=t.Event("hide.bs.tab",{relatedTarget:e[0]}),a=t.Event("show.bs.tab",{relatedTarget:i[0]});if(i.trigger(o),e.trigger(a),!a.isDefaultPrevented()&&!o.isDefaultPrevented()){var s=t(r);this.activate(e.closest("li"),n),this.activate(s,s.parent(),function(){i.trigger({type:"hidden.bs.tab",relatedTarget:e[0]}),e.trigger({type:"shown.bs.tab",relatedTarget:i[0]})})}}},n.prototype.activate=function(e,r,i){function o(){a.removeClass("active").find("> .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),e.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),s?(e[0].offsetWidth,e.addClass("in")):e.removeClass("fade"),e.parent(".dropdown-menu").length&&e.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),i&&i()}var a=r.find("> .active"),s=i&&t.support.transition&&(a.length&&a.hasClass("fade")||!!r.find("> .fade").length);a.length&&s?a.one("bsTransitionEnd",o).emulateTransitionEnd(n.TRANSITION_DURATION):o(),a.removeClass("in")};var r=t.fn.tab;t.fn.tab=e,t.fn.tab.Constructor=n,t.fn.tab.noConflict=function(){return t.fn.tab=r,this};var i=function(n){n.preventDefault(),e.call(t(this),"show")};t(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',i).on("click.bs.tab.data-api",'[data-toggle="pill"]',i)}(t),+function(t){"use strict";function e(e){return this.each(function(){var r=t(this),i=r.data("bs.affix"),o="object"==typeof e&&e;i||r.data("bs.affix",i=new n(this,o)),"string"==typeof e&&i[e]()})}var n=function(e,r){this.options=t.extend({},n.DEFAULTS,r),this.$target=t(this.options.target).on("scroll.bs.affix.data-api",t.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",t.proxy(this.checkPositionWithEventLoop,this)),this.$element=t(e),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};n.VERSION="3.3.7",n.RESET="affix affix-top affix-bottom",n.DEFAULTS={offset:0,target:window},n.prototype.getState=function(t,e,n,r){var i=this.$target.scrollTop(),o=this.$element.offset(),a=this.$target.height();if(null!=n&&"top"==this.affixed)return i<n&&"top";if("bottom"==this.affixed)return null!=n?!(i+this.unpin<=o.top)&&"bottom":!(i+a<=t-r)&&"bottom";var s=null==this.affixed,u=s?i:o.top,c=s?a:e;return null!=n&&i<=n?"top":null!=r&&u+c>=t-r&&"bottom"},n.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(n.RESET).addClass("affix");var t=this.$target.scrollTop(),e=this.$element.offset();return this.pinnedOffset=e.top-t},n.prototype.checkPositionWithEventLoop=function(){setTimeout(t.proxy(this.checkPosition,this),1)},n.prototype.checkPosition=function(){if(this.$element.is(":visible")){var e=this.$element.height(),r=this.options.offset,i=r.top,o=r.bottom,a=Math.max(t(document).height(),t(document.body).height());"object"!=typeof r&&(o=i=r),"function"==typeof i&&(i=r.top(this.$element)),"function"==typeof o&&(o=r.bottom(this.$element));var s=this.getState(a,e,i,o);if(this.affixed!=s){null!=this.unpin&&this.$element.css("top","");var u="affix"+(s?"-"+s:""),c=t.Event(u+".bs.affix");if(this.$element.trigger(c),c.isDefaultPrevented())return;this.affixed=s,this.unpin="bottom"==s?this.getPinnedOffset():null,this.$element.removeClass(n.RESET).addClass(u).trigger(u.replace("affix","affixed")+".bs.affix")}"bottom"==s&&this.$element.offset({top:a-e-o})}};var r=t.fn.affix;t.fn.affix=e,t.fn.affix.Constructor=n,t.fn.affix.noConflict=function(){return t.fn.affix=r,this},t(window).on("load",function(){t('[data-spy="affix"]').each(function(){var n=t(this),r=n.data();r.offset=r.offset||{},null!=r.offsetBottom&&(r.offset.bottom=r.offsetBottom),null!=r.offsetTop&&(r.offset.top=r.offsetTop),e.call(n,r)})})}(t)}).call(e,n(7))},function(t,e,n){(function(t,r){var i;(function(){function o(t,e){return t.set(e[0],e[1]),t}function a(t,e){return t.add(e),t}function s(t,e,n){switch(n.length){case 0:return t.call(e);case 1:return t.call(e,n[0]);case 2:return t.call(e,n[0],n[1]);case 3:return t.call(e,n[0],n[1],n[2])}return t.apply(e,n)}function u(t,e,n,r){for(var i=-1,o=null==t?0:t.length;++i<o;){var a=t[i];e(r,a,n(a),t)}return r}function c(t,e){for(var n=-1,r=null==t?0:t.length;++n<r&&e(t[n],n,t)!==!1;);return t}function l(t,e){for(var n=null==t?0:t.length;n--&&e(t[n],n,t)!==!1;);return t}function f(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(!e(t[n],n,t))return!1;return!0}function p(t,e){for(var n=-1,r=null==t?0:t.length,i=0,o=[];++n<r;){var a=t[n];e(a,n,t)&&(o[i++]=a)}return o}function d(t,e){var n=null==t?0:t.length;return!!n&&T(t,e,0)>-1}function h(t,e,n){for(var r=-1,i=null==t?0:t.length;++r<i;)if(n(e,t[r]))return!0;return!1}function v(t,e){for(var n=-1,r=null==t?0:t.length,i=Array(r);++n<r;)i[n]=e(t[n],n,t);return i}function g(t,e){for(var n=-1,r=e.length,i=t.length;++n<r;)t[i+n]=e[n];return t}function m(t,e,n,r){var i=-1,o=null==t?0:t.length;for(r&&o&&(n=t[++i]);++i<o;)n=e(n,t[i],i,t);return n}function y(t,e,n,r){var i=null==t?0:t.length;for(r&&i&&(n=t[--i]);i--;)n=e(n,t[i],i,t);return n}function b(t,e){for(var n=-1,r=null==t?0:t.length;++n<r;)if(e(t[n],n,t))return!0;return!1}function _(t){return t.split("")}function w(t){return t.match(Ue)||[]}function x(t,e,n){var r;return n(t,function(t,n,i){if(e(t,n,i))return r=n,!1}),r}function C(t,e,n,r){for(var i=t.length,o=n+(r?1:-1);r?o--:++o<i;)if(e(t[o],o,t))return o;return-1}function T(t,e,n){return e===e?Z(t,e,n):C(t,k,n)}function $(t,e,n,r){for(var i=n-1,o=t.length;++i<o;)if(r(t[i],e))return i;return-1}function k(t){return t!==t}function A(t,e){var n=null==t?0:t.length;return n?N(t,e)/n:Pt}function E(t){return function(e){return null==e?it:e[t]}}function S(t){return function(e){return null==t?it:t[e]}}function O(t,e,n,r,i){return i(t,function(t,i,o){n=r?(r=!1,t):e(n,t,i,o)}),n}function j(t,e){var n=t.length;for(t.sort(e);n--;)t[n]=t[n].value;return t}function N(t,e){for(var n,r=-1,i=t.length;++r<i;){var o=e(t[r]);o!==it&&(n=n===it?o:n+o)}return n}function D(t,e){for(var n=-1,r=Array(t);++n<t;)r[n]=e(n);return r}function I(t,e){return v(e,function(e){return[e,t[e]]})}function R(t){return function(e){return t(e)}}function L(t,e){return v(e,function(e){return t[e]})}function P(t,e){return t.has(e)}function F(t,e){for(var n=-1,r=t.length;++n<r&&T(e,t[n],0)>-1;);return n}function q(t,e){for(var n=t.length;n--&&T(e,t[n],0)>-1;);return n}function M(t,e){for(var n=t.length,r=0;n--;)t[n]===e&&++r;return r}function H(t){return"\\"+nr[t]}function B(t,e){return null==t?it:t[e]}function U(t){return Xn.test(t)}function W(t){return Kn.test(t)}function z(t){for(var e,n=[];!(e=t.next()).done;)n.push(e.value);return n}function V(t){var e=-1,n=Array(t.size);return t.forEach(function(t,r){n[++e]=[r,t]}),n}function X(t,e){return function(n){return t(e(n))}}function K(t,e){for(var n=-1,r=t.length,i=0,o=[];++n<r;){var a=t[n];a!==e&&a!==ft||(t[n]=ft,o[i++]=n)}return o}function J(t){var e=-1,n=Array(t.size);return t.forEach(function(t){n[++e]=t}),n}function G(t){var e=-1,n=Array(t.size);return t.forEach(function(t){n[++e]=[t,t]}),n}function Z(t,e,n){for(var r=n-1,i=t.length;++r<i;)if(t[r]===e)return r;return-1}function Y(t,e,n){for(var r=n+1;r--;)if(t[r]===e)return r;return r}function Q(t){return U(t)?et(t):br(t)}function tt(t){return U(t)?nt(t):_(t)}function et(t){for(var e=zn.lastIndex=0;zn.test(t);)++e;return e}function nt(t){return t.match(zn)||[]}function rt(t){return t.match(Vn)||[]}var it,ot="4.17.4",at=200,st="Unsupported core-js use. Try https://npms.io/search?q=ponyfill.",ut="Expected a function",ct="__lodash_hash_undefined__",lt=500,ft="__lodash_placeholder__",pt=1,dt=2,ht=4,vt=1,gt=2,mt=1,yt=2,bt=4,_t=8,wt=16,xt=32,Ct=64,Tt=128,$t=256,kt=512,At=30,Et="...",St=800,Ot=16,jt=1,Nt=2,Dt=3,It=1/0,Rt=9007199254740991,Lt=1.7976931348623157e308,Pt=NaN,Ft=4294967295,qt=Ft-1,Mt=Ft>>>1,Ht=[["ary",Tt],["bind",mt],["bindKey",yt],["curry",_t],["curryRight",wt],["flip",kt],["partial",xt],["partialRight",Ct],["rearg",$t]],Bt="[object Arguments]",Ut="[object Array]",Wt="[object AsyncFunction]",zt="[object Boolean]",Vt="[object Date]",Xt="[object DOMException]",Kt="[object Error]",Jt="[object Function]",Gt="[object GeneratorFunction]",Zt="[object Map]",Yt="[object Number]",Qt="[object Null]",te="[object Object]",ee="[object Promise]",ne="[object Proxy]",re="[object RegExp]",ie="[object Set]",oe="[object String]",ae="[object Symbol]",se="[object Undefined]",ue="[object WeakMap]",ce="[object WeakSet]",le="[object ArrayBuffer]",fe="[object DataView]",pe="[object Float32Array]",de="[object Float64Array]",he="[object Int8Array]",ve="[object Int16Array]",ge="[object Int32Array]",me="[object Uint8Array]",ye="[object Uint8ClampedArray]",be="[object Uint16Array]",_e="[object Uint32Array]",we=/\b__p \+= '';/g,xe=/\b(__p \+=) '' \+/g,Ce=/(__e\(.*?\)|\b__t\)) \+\n'';/g,Te=/&(?:amp|lt|gt|quot|#39);/g,$e=/[&<>"']/g,ke=RegExp(Te.source),Ae=RegExp($e.source),Ee=/<%-([\s\S]+?)%>/g,Se=/<%([\s\S]+?)%>/g,Oe=/<%=([\s\S]+?)%>/g,je=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,Ne=/^\w*$/,De=/^\./,Ie=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,Re=/[\\^$.*+?()[\]{}|]/g,Le=RegExp(Re.source),Pe=/^\s+|\s+$/g,Fe=/^\s+/,qe=/\s+$/,Me=/\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,He=/\{\n\/\* \[wrapped with (.+)\] \*/,Be=/,? & /,Ue=/[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g,We=/\\(\\)?/g,ze=/\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g,Ve=/\w*$/,Xe=/^[-+]0x[0-9a-f]+$/i,Ke=/^0b[01]+$/i,Je=/^\[object .+?Constructor\]$/,Ge=/^0o[0-7]+$/i,Ze=/^(?:0|[1-9]\d*)$/,Ye=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,Qe=/($^)/,tn=/['\n\r\u2028\u2029\\]/g,en="\\ud800-\\udfff",nn="\\u0300-\\u036f",rn="\\ufe20-\\ufe2f",on="\\u20d0-\\u20ff",an=nn+rn+on,sn="\\u2700-\\u27bf",un="a-z\\xdf-\\xf6\\xf8-\\xff",cn="\\xac\\xb1\\xd7\\xf7",ln="\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf",fn="\\u2000-\\u206f",pn=" \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000",dn="A-Z\\xc0-\\xd6\\xd8-\\xde",hn="\\ufe0e\\ufe0f",vn=cn+ln+fn+pn,gn="['’]",mn="["+en+"]",yn="["+vn+"]",bn="["+an+"]",_n="\\d+",wn="["+sn+"]",xn="["+un+"]",Cn="[^"+en+vn+_n+sn+un+dn+"]",Tn="\\ud83c[\\udffb-\\udfff]",$n="(?:"+bn+"|"+Tn+")",kn="[^"+en+"]",An="(?:\\ud83c[\\udde6-\\uddff]){2}",En="[\\ud800-\\udbff][\\udc00-\\udfff]",Sn="["+dn+"]",On="\\u200d",jn="(?:"+xn+"|"+Cn+")",Nn="(?:"+Sn+"|"+Cn+")",Dn="(?:"+gn+"(?:d|ll|m|re|s|t|ve))?",In="(?:"+gn+"(?:D|LL|M|RE|S|T|VE))?",Rn=$n+"?",Ln="["+hn+"]?",Pn="(?:"+On+"(?:"+[kn,An,En].join("|")+")"+Ln+Rn+")*",Fn="\\d*(?:(?:1st|2nd|3rd|(?![123])\\dth)\\b)",qn="\\d*(?:(?:1ST|2ND|3RD|(?![123])\\dTH)\\b)",Mn=Ln+Rn+Pn,Hn="(?:"+[wn,An,En].join("|")+")"+Mn,Bn="(?:"+[kn+bn+"?",bn,An,En,mn].join("|")+")",Un=RegExp(gn,"g"),Wn=RegExp(bn,"g"),zn=RegExp(Tn+"(?="+Tn+")|"+Bn+Mn,"g"),Vn=RegExp([Sn+"?"+xn+"+"+Dn+"(?="+[yn,Sn,"$"].join("|")+")",Nn+"+"+In+"(?="+[yn,Sn+jn,"$"].join("|")+")",Sn+"?"+jn+"+"+Dn,Sn+"+"+In,qn,Fn,_n,Hn].join("|"),"g"),Xn=RegExp("["+On+en+an+hn+"]"),Kn=/[a-z][A-Z]|[A-Z]{2,}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/,Jn=["Array","Buffer","DataView","Date","Error","Float32Array","Float64Array","Function","Int8Array","Int16Array","Int32Array","Map","Math","Object","Promise","RegExp","Set","String","Symbol","TypeError","Uint8Array","Uint8ClampedArray","Uint16Array","Uint32Array","WeakMap","_","clearTimeout","isFinite","parseInt","setTimeout"],Gn=-1,Zn={};Zn[pe]=Zn[de]=Zn[he]=Zn[ve]=Zn[ge]=Zn[me]=Zn[ye]=Zn[be]=Zn[_e]=!0,Zn[Bt]=Zn[Ut]=Zn[le]=Zn[zt]=Zn[fe]=Zn[Vt]=Zn[Kt]=Zn[Jt]=Zn[Zt]=Zn[Yt]=Zn[te]=Zn[re]=Zn[ie]=Zn[oe]=Zn[ue]=!1;var Yn={};Yn[Bt]=Yn[Ut]=Yn[le]=Yn[fe]=Yn[zt]=Yn[Vt]=Yn[pe]=Yn[de]=Yn[he]=Yn[ve]=Yn[ge]=Yn[Zt]=Yn[Yt]=Yn[te]=Yn[re]=Yn[ie]=Yn[oe]=Yn[ae]=Yn[me]=Yn[ye]=Yn[be]=Yn[_e]=!0,Yn[Kt]=Yn[Jt]=Yn[ue]=!1;var Qn={"À":"A","Á":"A","Â":"A","Ã":"A","Ä":"A","Å":"A","à":"a","á":"a","â":"a","ã":"a","ä":"a","å":"a","Ç":"C","ç":"c","Ð":"D","ð":"d","È":"E","É":"E","Ê":"E","Ë":"E","è":"e","é":"e","ê":"e","ë":"e","Ì":"I","Í":"I","Î":"I","Ï":"I","ì":"i","í":"i","î":"i","ï":"i","Ñ":"N","ñ":"n","Ò":"O","Ó":"O","Ô":"O","Õ":"O","Ö":"O","Ø":"O","ò":"o","ó":"o","ô":"o","õ":"o","ö":"o","ø":"o","Ù":"U","Ú":"U","Û":"U","Ü":"U","ù":"u","ú":"u","û":"u","ü":"u","Ý":"Y","ý":"y","ÿ":"y","Æ":"Ae","æ":"ae","Þ":"Th","þ":"th","ß":"ss","Ā":"A","Ă":"A","Ą":"A","ā":"a","ă":"a","ą":"a","Ć":"C","Ĉ":"C","Ċ":"C","Č":"C","ć":"c","ĉ":"c","ċ":"c","č":"c","Ď":"D","Đ":"D","ď":"d","đ":"d","Ē":"E","Ĕ":"E","Ė":"E","Ę":"E","Ě":"E","ē":"e","ĕ":"e","ė":"e","ę":"e","ě":"e","Ĝ":"G","Ğ":"G","Ġ":"G","Ģ":"G","ĝ":"g","ğ":"g","ġ":"g","ģ":"g","Ĥ":"H","Ħ":"H","ĥ":"h","ħ":"h","Ĩ":"I","Ī":"I","Ĭ":"I","Į":"I","İ":"I","ĩ":"i","ī":"i","ĭ":"i","į":"i","ı":"i","Ĵ":"J","ĵ":"j","Ķ":"K","ķ":"k","ĸ":"k","Ĺ":"L","Ļ":"L","Ľ":"L","Ŀ":"L","Ł":"L","ĺ":"l","ļ":"l","ľ":"l","ŀ":"l","ł":"l","Ń":"N","Ņ":"N","Ň":"N","Ŋ":"N","ń":"n","ņ":"n","ň":"n","ŋ":"n","Ō":"O","Ŏ":"O","Ő":"O","ō":"o","ŏ":"o","ő":"o","Ŕ":"R","Ŗ":"R","Ř":"R","ŕ":"r","ŗ":"r","ř":"r","Ś":"S","Ŝ":"S","Ş":"S","Š":"S","ś":"s","ŝ":"s","ş":"s","š":"s","Ţ":"T","Ť":"T","Ŧ":"T","ţ":"t","ť":"t","ŧ":"t","Ũ":"U","Ū":"U","Ŭ":"U","Ů":"U","Ű":"U","Ų":"U","ũ":"u","ū":"u","ŭ":"u","ů":"u","ű":"u","ų":"u","Ŵ":"W","ŵ":"w","Ŷ":"Y","ŷ":"y","Ÿ":"Y","Ź":"Z","Ż":"Z","Ž":"Z","ź":"z","ż":"z","ž":"z","IJ":"IJ","ij":"ij","Œ":"Oe","œ":"oe","ʼn":"'n","ſ":"s"},tr={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#39;"},er={"&amp;":"&","&lt;":"<","&gt;":">","&quot;":'"',"&#39;":"'"},nr={"\\":"\\","'":"'","\n":"n","\r":"r","\u2028":"u2028","\u2029":"u2029"},rr=parseFloat,ir=parseInt,or="object"==typeof t&&t&&t.Object===Object&&t,ar="object"==typeof self&&self&&self.Object===Object&&self,sr=or||ar||Function("return this")(),ur="object"==typeof e&&e&&!e.nodeType&&e,cr=ur&&"object"==typeof r&&r&&!r.nodeType&&r,lr=cr&&cr.exports===ur,fr=lr&&or.process,pr=function(){try{return fr&&fr.binding&&fr.binding("util")}catch(t){}}(),dr=pr&&pr.isArrayBuffer,hr=pr&&pr.isDate,vr=pr&&pr.isMap,gr=pr&&pr.isRegExp,mr=pr&&pr.isSet,yr=pr&&pr.isTypedArray,br=E("length"),_r=S(Qn),wr=S(tr),xr=S(er),Cr=function t(e){function n(t){if(cu(t)&&!wp(t)&&!(t instanceof _)){if(t instanceof i)return t;if(_l.call(t,"__wrapped__"))return aa(t)}return new i(t)}function r(){}function i(t,e){this.__wrapped__=t,this.__actions__=[],this.__chain__=!!e,this.__index__=0,this.__values__=it}function _(t){this.__wrapped__=t,this.__actions__=[],this.__dir__=1,this.__filtered__=!1,this.__iteratees__=[],this.__takeCount__=Ft,this.__views__=[]}function S(){var t=new _(this.__wrapped__);return t.__actions__=Mi(this.__actions__),t.__dir__=this.__dir__,t.__filtered__=this.__filtered__,t.__iteratees__=Mi(this.__iteratees__),t.__takeCount__=this.__takeCount__,t.__views__=Mi(this.__views__),t}function Z(){if(this.__filtered__){var t=new _(this);t.__dir__=-1,t.__filtered__=!0}else t=this.clone(),t.__dir__*=-1;return t}function et(){var t=this.__wrapped__.value(),e=this.__dir__,n=wp(t),r=e<0,i=n?t.length:0,o=Oo(0,i,this.__views__),a=o.start,s=o.end,u=s-a,c=r?s:a-1,l=this.__iteratees__,f=l.length,p=0,d=Gl(u,this.__takeCount__);if(!n||!r&&i==u&&d==u)return wi(t,this.__actions__);var h=[];t:for(;u--&&p<d;){c+=e;for(var v=-1,g=t[c];++v<f;){var m=l[v],y=m.iteratee,b=m.type,_=y(g);if(b==Nt)g=_;else if(!_){if(b==jt)continue t;break t}}h[p++]=g}return h}function nt(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function Ue(){this.__data__=sf?sf(null):{},this.size=0}function en(t){var e=this.has(t)&&delete this.__data__[t];return this.size-=e?1:0,e}function nn(t){var e=this.__data__;if(sf){var n=e[t];return n===ct?it:n}return _l.call(e,t)?e[t]:it}function rn(t){var e=this.__data__;return sf?e[t]!==it:_l.call(e,t)}function on(t,e){var n=this.__data__;return this.size+=this.has(t)?0:1,n[t]=sf&&e===it?ct:e,this}function an(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function sn(){this.__data__=[],this.size=0}function un(t){var e=this.__data__,n=Dn(e,t);if(n<0)return!1;var r=e.length-1;return n==r?e.pop():Il.call(e,n,1),--this.size,!0}function cn(t){var e=this.__data__,n=Dn(e,t);return n<0?it:e[n][1]}function ln(t){return Dn(this.__data__,t)>-1}function fn(t,e){var n=this.__data__,r=Dn(n,t);return r<0?(++this.size,n.push([t,e])):n[r][1]=e,this}function pn(t){var e=-1,n=null==t?0:t.length;for(this.clear();++e<n;){var r=t[e];this.set(r[0],r[1])}}function dn(){this.size=0,this.__data__={hash:new nt,map:new(nf||an),string:new nt}}function hn(t){var e=ko(this,t).delete(t);return this.size-=e?1:0,e}function vn(t){return ko(this,t).get(t)}function gn(t){return ko(this,t).has(t)}function mn(t,e){var n=ko(this,t),r=n.size;return n.set(t,e),this.size+=n.size==r?0:1,this}function yn(t){var e=-1,n=null==t?0:t.length;for(this.__data__=new pn;++e<n;)this.add(t[e])}function bn(t){return this.__data__.set(t,ct),this}function _n(t){return this.__data__.has(t)}function wn(t){var e=this.__data__=new an(t);this.size=e.size}function xn(){this.__data__=new an,this.size=0}function Cn(t){var e=this.__data__,n=e.delete(t);return this.size=e.size,n}function Tn(t){return this.__data__.get(t)}function $n(t){return this.__data__.has(t)}function kn(t,e){var n=this.__data__;if(n instanceof an){var r=n.__data__;if(!nf||r.length<at-1)return r.push([t,e]),this.size=++n.size,this;n=this.__data__=new pn(r)}return n.set(t,e),this.size=n.size,this}function An(t,e){var n=wp(t),r=!n&&_p(t),i=!n&&!r&&Cp(t),o=!n&&!r&&!i&&Ep(t),a=n||r||i||o,s=a?D(t.length,dl):[],u=s.length;for(var c in t)!e&&!_l.call(t,c)||a&&("length"==c||i&&("offset"==c||"parent"==c)||o&&("buffer"==c||"byteLength"==c||"byteOffset"==c)||Fo(c,u))||s.push(c);return s}function En(t){var e=t.length;return e?t[ni(0,e-1)]:it}function Sn(t,e){return na(Mi(t),qn(e,0,t.length))}function On(t){return na(Mi(t))}function jn(t,e,n){(n===it||Js(t[e],n))&&(n!==it||e in t)||Pn(t,e,n)}function Nn(t,e,n){var r=t[e];_l.call(t,e)&&Js(r,n)&&(n!==it||e in t)||Pn(t,e,n)}function Dn(t,e){for(var n=t.length;n--;)if(Js(t[n][0],e))return n;return-1}function In(t,e,n,r){return bf(t,function(t,i,o){e(r,t,n(t),o)}),r}function Rn(t,e){return t&&Hi(e,Wu(e),t)}function Ln(t,e){return t&&Hi(e,zu(e),t)}function Pn(t,e,n){"__proto__"==e&&Fl?Fl(t,e,{configurable:!0,enumerable:!0,value:n,writable:!0}):t[e]=n}function Fn(t,e){for(var n=-1,r=e.length,i=al(r),o=null==t;++n<r;)i[n]=o?it:Hu(t,e[n]);return i}function qn(t,e,n){return t===t&&(n!==it&&(t=t<=n?t:n),e!==it&&(t=t>=e?t:e)),t}function Mn(t,e,n,r,i,o){var a,s=e&pt,u=e&dt,l=e&ht;if(n&&(a=i?n(t,r,i,o):n(t)),a!==it)return a;if(!uu(t))return t;var f=wp(t);if(f){if(a=Do(t),!s)return Mi(t,a)}else{var p=jf(t),d=p==Jt||p==Gt;if(Cp(t))return Ei(t,s);if(p==te||p==Bt||d&&!i){if(a=u||d?{}:Io(t),!s)return u?Ui(t,Ln(a,t)):Bi(t,Rn(a,t))}else{if(!Yn[p])return i?t:{};a=Ro(t,p,Mn,s)}}o||(o=new wn);var h=o.get(t);if(h)return h;o.set(t,a);var v=l?u?xo:wo:u?zu:Wu,g=f?it:v(t);return c(g||t,function(r,i){g&&(i=r,r=t[i]),Nn(a,i,Mn(r,e,n,i,t,o))}),a}function Hn(t){var e=Wu(t);return function(n){return Bn(n,t,e)}}function Bn(t,e,n){var r=n.length;if(null==t)return!r;for(t=fl(t);r--;){var i=n[r],o=e[i],a=t[i];if(a===it&&!(i in t)||!o(a))return!1}return!0}function zn(t,e,n){if("function"!=typeof t)throw new hl(ut);return If(function(){t.apply(it,n)},e)}function Vn(t,e,n,r){var i=-1,o=d,a=!0,s=t.length,u=[],c=e.length;if(!s)return u;n&&(e=v(e,R(n))),r?(o=h,a=!1):e.length>=at&&(o=P,a=!1,e=new yn(e));t:for(;++i<s;){var l=t[i],f=null==n?l:n(l);if(l=r||0!==l?l:0,a&&f===f){for(var p=c;p--;)if(e[p]===f)continue t;u.push(l)}else o(e,f,r)||u.push(l)}return u}function Xn(t,e){var n=!0;return bf(t,function(t,r,i){return n=!!e(t,r,i)}),n}function Kn(t,e,n){for(var r=-1,i=t.length;++r<i;){var o=t[r],a=e(o);if(null!=a&&(s===it?a===a&&!_u(a):n(a,s)))var s=a,u=o}return u}function Qn(t,e,n,r){var i=t.length;for(n=ku(n),n<0&&(n=-n>i?0:i+n),r=r===it||r>i?i:ku(r),r<0&&(r+=i),r=n>r?0:Au(r);n<r;)t[n++]=e;return t}function tr(t,e){var n=[];return bf(t,function(t,r,i){e(t,r,i)&&n.push(t)}),n}function er(t,e,n,r,i){var o=-1,a=t.length;for(n||(n=Po),i||(i=[]);++o<a;){var s=t[o];e>0&&n(s)?e>1?er(s,e-1,n,r,i):g(i,s):r||(i[i.length]=s)}return i}function nr(t,e){return t&&wf(t,e,Wu)}function or(t,e){return t&&xf(t,e,Wu)}function ar(t,e){return p(e,function(e){return ou(t[e])})}function ur(t,e){e=ki(e,t);for(var n=0,r=e.length;null!=t&&n<r;)t=t[ra(e[n++])];return n&&n==r?t:it}function cr(t,e,n){var r=e(t);return wp(t)?r:g(r,n(t))}function fr(t){return null==t?t===it?se:Qt:Pl&&Pl in fl(t)?So(t):Go(t)}function pr(t,e){return t>e}function br(t,e){return null!=t&&_l.call(t,e)}function Cr(t,e){return null!=t&&e in fl(t)}function $r(t,e,n){return t>=Gl(e,n)&&t<Jl(e,n)}function kr(t,e,n){for(var r=n?h:d,i=t[0].length,o=t.length,a=o,s=al(o),u=1/0,c=[];a--;){var l=t[a];a&&e&&(l=v(l,R(e))),u=Gl(l.length,u),s[a]=!n&&(e||i>=120&&l.length>=120)?new yn(a&&l):it}l=t[0];var f=-1,p=s[0];t:for(;++f<i&&c.length<u;){var g=l[f],m=e?e(g):g;if(g=n||0!==g?g:0,!(p?P(p,m):r(c,m,n))){for(a=o;--a;){var y=s[a];if(!(y?P(y,m):r(t[a],m,n)))continue t}p&&p.push(m),c.push(g)}}return c}function Ar(t,e,n,r){return nr(t,function(t,i,o){e(r,n(t),i,o)}),r}function Er(t,e,n){e=ki(e,t),t=Yo(t,e);var r=null==t?t:t[ra($a(e))];return null==r?it:s(r,t,n)}function Sr(t){return cu(t)&&fr(t)==Bt}function Or(t){return cu(t)&&fr(t)==le}function jr(t){return cu(t)&&fr(t)==Vt}function Nr(t,e,n,r,i){return t===e||(null==t||null==e||!cu(t)&&!cu(e)?t!==t&&e!==e:Dr(t,e,n,r,Nr,i))}function Dr(t,e,n,r,i,o){var a=wp(t),s=wp(e),u=a?Ut:jf(t),c=s?Ut:jf(e);u=u==Bt?te:u,c=c==Bt?te:c;var l=u==te,f=c==te,p=u==c;if(p&&Cp(t)){if(!Cp(e))return!1;a=!0,l=!1}if(p&&!l)return o||(o=new wn),a||Ep(t)?mo(t,e,n,r,i,o):yo(t,e,u,n,r,i,o);if(!(n&vt)){var d=l&&_l.call(t,"__wrapped__"),h=f&&_l.call(e,"__wrapped__");if(d||h){var v=d?t.value():t,g=h?e.value():e;return o||(o=new wn),i(v,g,n,r,o)}}return!!p&&(o||(o=new wn),bo(t,e,n,r,i,o))}function Ir(t){return cu(t)&&jf(t)==Zt}function Rr(t,e,n,r){var i=n.length,o=i,a=!r;if(null==t)return!o;for(t=fl(t);i--;){var s=n[i];if(a&&s[2]?s[1]!==t[s[0]]:!(s[0]in t))return!1}for(;++i<o;){s=n[i];var u=s[0],c=t[u],l=s[1];if(a&&s[2]){if(c===it&&!(u in t))return!1}else{var f=new wn;if(r)var p=r(c,l,u,t,e,f);if(!(p===it?Nr(l,c,vt|gt,r,f):p))return!1}}return!0}function Lr(t){if(!uu(t)||Uo(t))return!1;var e=ou(t)?kl:Je;return e.test(ia(t))}function Pr(t){return cu(t)&&fr(t)==re}function Fr(t){return cu(t)&&jf(t)==ie}function qr(t){return cu(t)&&su(t.length)&&!!Zn[fr(t)]}function Mr(t){return"function"==typeof t?t:null==t?Ic:"object"==typeof t?wp(t)?Vr(t[0],t[1]):zr(t):Bc(t)}function Hr(t){if(!Wo(t))return Kl(t);var e=[];for(var n in fl(t))_l.call(t,n)&&"constructor"!=n&&e.push(n);return e}function Br(t){if(!uu(t))return Jo(t);var e=Wo(t),n=[];for(var r in t)("constructor"!=r||!e&&_l.call(t,r))&&n.push(r);return n}function Ur(t,e){return t<e}function Wr(t,e){var n=-1,r=Gs(t)?al(t.length):[];return bf(t,function(t,i,o){r[++n]=e(t,i,o)}),r}function zr(t){var e=Ao(t);return 1==e.length&&e[0][2]?Vo(e[0][0],e[0][1]):function(n){return n===t||Rr(n,t,e)}}function Vr(t,e){return Mo(t)&&zo(e)?Vo(ra(t),e):function(n){var r=Hu(n,t);return r===it&&r===e?Uu(n,t):Nr(e,r,vt|gt)}}function Xr(t,e,n,r,i){t!==e&&wf(e,function(o,a){if(uu(o))i||(i=new wn),Kr(t,e,a,n,Xr,r,i);else{var s=r?r(t[a],o,a+"",t,e,i):it;s===it&&(s=o),jn(t,a,s)}},zu)}function Kr(t,e,n,r,i,o,a){var s=t[n],u=e[n],c=a.get(u);if(c)return void jn(t,n,c);var l=o?o(s,u,n+"",t,e,a):it,f=l===it;if(f){var p=wp(u),d=!p&&Cp(u),h=!p&&!d&&Ep(u);l=u,p||d||h?wp(s)?l=s:Zs(s)?l=Mi(s):d?(f=!1,l=Ei(u,!0)):h?(f=!1,l=Ri(u,!0)):l=[]:mu(u)||_p(u)?(l=s,_p(s)?l=Su(s):(!uu(s)||r&&ou(s))&&(l=Io(u))):f=!1}f&&(a.set(u,l),i(l,u,r,o,a),a.delete(u)),jn(t,n,l)}function Jr(t,e){var n=t.length;if(n)return e+=e<0?n:0,Fo(e,n)?t[e]:it}function Gr(t,e,n){var r=-1;e=v(e.length?e:[Ic],R($o()));var i=Wr(t,function(t,n,i){var o=v(e,function(e){return e(t)});return{criteria:o,index:++r,value:t}});return j(i,function(t,e){return Pi(t,e,n)})}function Zr(t,e){return Yr(t,e,function(e,n){return Uu(t,n)})}function Yr(t,e,n){for(var r=-1,i=e.length,o={};++r<i;){var a=e[r],s=ur(t,a);n(s,a)&&ui(o,ki(a,t),s)}return o}function Qr(t){return function(e){return ur(e,t)}}function ti(t,e,n,r){var i=r?$:T,o=-1,a=e.length,s=t;for(t===e&&(e=Mi(e)),n&&(s=v(t,R(n)));++o<a;)for(var u=0,c=e[o],l=n?n(c):c;(u=i(s,l,u,r))>-1;)s!==t&&Il.call(s,u,1),Il.call(t,u,1);return t}function ei(t,e){for(var n=t?e.length:0,r=n-1;n--;){var i=e[n];if(n==r||i!==o){var o=i;Fo(i)?Il.call(t,i,1):yi(t,i)}}return t}function ni(t,e){return t+Ul(Ql()*(e-t+1))}function ri(t,e,n,r){for(var i=-1,o=Jl(Bl((e-t)/(n||1)),0),a=al(o);o--;)a[r?o:++i]=t,t+=n;return a}function ii(t,e){var n="";if(!t||e<1||e>Rt)return n;do e%2&&(n+=t),e=Ul(e/2),e&&(t+=t);while(e);return n}function oi(t,e){return Rf(Zo(t,e,Ic),t+"")}function ai(t){return En(rc(t))}function si(t,e){var n=rc(t);return na(n,qn(e,0,n.length))}function ui(t,e,n,r){if(!uu(t))return t;e=ki(e,t);for(var i=-1,o=e.length,a=o-1,s=t;null!=s&&++i<o;){var u=ra(e[i]),c=n;if(i!=a){var l=s[u];c=r?r(l,u,s):it,c===it&&(c=uu(l)?l:Fo(e[i+1])?[]:{})}Nn(s,u,c),s=s[u]}return t}function ci(t){return na(rc(t))}function li(t,e,n){var r=-1,i=t.length;e<0&&(e=-e>i?0:i+e),n=n>i?i:n,n<0&&(n+=i),i=e>n?0:n-e>>>0,e>>>=0;for(var o=al(i);++r<i;)o[r]=t[r+e];return o}function fi(t,e){var n;return bf(t,function(t,r,i){return n=e(t,r,i),!n}),!!n}function pi(t,e,n){var r=0,i=null==t?r:t.length;if("number"==typeof e&&e===e&&i<=Mt){for(;r<i;){var o=r+i>>>1,a=t[o];null!==a&&!_u(a)&&(n?a<=e:a<e)?r=o+1:i=o}return i}return di(t,e,Ic,n)}function di(t,e,n,r){e=n(e);for(var i=0,o=null==t?0:t.length,a=e!==e,s=null===e,u=_u(e),c=e===it;i<o;){var l=Ul((i+o)/2),f=n(t[l]),p=f!==it,d=null===f,h=f===f,v=_u(f);if(a)var g=r||h;else g=c?h&&(r||p):s?h&&p&&(r||!d):u?h&&p&&!d&&(r||!v):!d&&!v&&(r?f<=e:f<e);g?i=l+1:o=l}return Gl(o,qt)}function hi(t,e){for(var n=-1,r=t.length,i=0,o=[];++n<r;){var a=t[n],s=e?e(a):a;if(!n||!Js(s,u)){var u=s;o[i++]=0===a?0:a}}return o}function vi(t){return"number"==typeof t?t:_u(t)?Pt:+t}function gi(t){if("string"==typeof t)return t;if(wp(t))return v(t,gi)+"";if(_u(t))return mf?mf.call(t):"";var e=t+"";return"0"==e&&1/t==-It?"-0":e}function mi(t,e,n){var r=-1,i=d,o=t.length,a=!0,s=[],u=s;if(n)a=!1,i=h;else if(o>=at){var c=e?null:Af(t);if(c)return J(c);a=!1,i=P,u=new yn}else u=e?[]:s;t:for(;++r<o;){var l=t[r],f=e?e(l):l;if(l=n||0!==l?l:0,a&&f===f){for(var p=u.length;p--;)if(u[p]===f)continue t;e&&u.push(f),s.push(l)}else i(u,f,n)||(u!==s&&u.push(f),s.push(l))}return s}function yi(t,e){return e=ki(e,t),t=Yo(t,e),null==t||delete t[ra($a(e))]}function bi(t,e,n,r){return ui(t,e,n(ur(t,e)),r)}function _i(t,e,n,r){for(var i=t.length,o=r?i:-1;(r?o--:++o<i)&&e(t[o],o,t););return n?li(t,r?0:o,r?o+1:i):li(t,r?o+1:0,r?i:o)}function wi(t,e){var n=t;return n instanceof _&&(n=n.value()),m(e,function(t,e){return e.func.apply(e.thisArg,g([t],e.args))},n)}function xi(t,e,n){var r=t.length;if(r<2)return r?mi(t[0]):[];for(var i=-1,o=al(r);++i<r;)for(var a=t[i],s=-1;++s<r;)s!=i&&(o[i]=Vn(o[i]||a,t[s],e,n));return mi(er(o,1),e,n)}function Ci(t,e,n){for(var r=-1,i=t.length,o=e.length,a={};++r<i;){var s=r<o?e[r]:it;n(a,t[r],s)}return a}function Ti(t){return Zs(t)?t:[]}function $i(t){return"function"==typeof t?t:Ic}function ki(t,e){return wp(t)?t:Mo(t,e)?[t]:Lf(ju(t))}function Ai(t,e,n){var r=t.length;return n=n===it?r:n,!e&&n>=r?t:li(t,e,n)}function Ei(t,e){if(e)return t.slice();var n=t.length,r=Ol?Ol(n):new t.constructor(n);return t.copy(r),r}function Si(t){var e=new t.constructor(t.byteLength);return new Sl(e).set(new Sl(t)),e}function Oi(t,e){var n=e?Si(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.byteLength)}function ji(t,e,n){var r=e?n(V(t),pt):V(t);return m(r,o,new t.constructor)}function Ni(t){var e=new t.constructor(t.source,Ve.exec(t));return e.lastIndex=t.lastIndex,e}function Di(t,e,n){var r=e?n(J(t),pt):J(t);return m(r,a,new t.constructor)}function Ii(t){return gf?fl(gf.call(t)):{}}function Ri(t,e){var n=e?Si(t.buffer):t.buffer;return new t.constructor(n,t.byteOffset,t.length)}function Li(t,e){if(t!==e){var n=t!==it,r=null===t,i=t===t,o=_u(t),a=e!==it,s=null===e,u=e===e,c=_u(e);if(!s&&!c&&!o&&t>e||o&&a&&u&&!s&&!c||r&&a&&u||!n&&u||!i)return 1;if(!r&&!o&&!c&&t<e||c&&n&&i&&!r&&!o||s&&n&&i||!a&&i||!u)return-1}return 0}function Pi(t,e,n){for(var r=-1,i=t.criteria,o=e.criteria,a=i.length,s=n.length;++r<a;){var u=Li(i[r],o[r]);if(u){if(r>=s)return u;var c=n[r];return u*("desc"==c?-1:1)}}return t.index-e.index}function Fi(t,e,n,r){for(var i=-1,o=t.length,a=n.length,s=-1,u=e.length,c=Jl(o-a,0),l=al(u+c),f=!r;++s<u;)l[s]=e[s];for(;++i<a;)(f||i<o)&&(l[n[i]]=t[i]);for(;c--;)l[s++]=t[i++];return l}function qi(t,e,n,r){for(var i=-1,o=t.length,a=-1,s=n.length,u=-1,c=e.length,l=Jl(o-s,0),f=al(l+c),p=!r;++i<l;)f[i]=t[i];for(var d=i;++u<c;)f[d+u]=e[u];for(;++a<s;)(p||i<o)&&(f[d+n[a]]=t[i++]);return f}function Mi(t,e){var n=-1,r=t.length;for(e||(e=al(r));++n<r;)e[n]=t[n];return e}function Hi(t,e,n,r){var i=!n;n||(n={});for(var o=-1,a=e.length;++o<a;){var s=e[o],u=r?r(n[s],t[s],s,n,t):it;u===it&&(u=t[s]),i?Pn(n,s,u):Nn(n,s,u)}return n}function Bi(t,e){return Hi(t,Sf(t),e)}function Ui(t,e){return Hi(t,Of(t),e)}function Wi(t,e){return function(n,r){var i=wp(n)?u:In,o=e?e():{};return i(n,t,$o(r,2),o)}}function zi(t){return oi(function(e,n){var r=-1,i=n.length,o=i>1?n[i-1]:it,a=i>2?n[2]:it;for(o=t.length>3&&"function"==typeof o?(i--,o):it,a&&qo(n[0],n[1],a)&&(o=i<3?it:o,i=1),e=fl(e);++r<i;){var s=n[r];s&&t(e,s,r,o)}return e})}function Vi(t,e){return function(n,r){if(null==n)return n;if(!Gs(n))return t(n,r);for(var i=n.length,o=e?i:-1,a=fl(n);(e?o--:++o<i)&&r(a[o],o,a)!==!1;);return n}}function Xi(t){return function(e,n,r){for(var i=-1,o=fl(e),a=r(e),s=a.length;s--;){var u=a[t?s:++i];if(n(o[u],u,o)===!1)break}return e}}function Ki(t,e,n){function r(){var e=this&&this!==sr&&this instanceof r?o:t;return e.apply(i?n:this,arguments)}var i=e&mt,o=Zi(t);return r}function Ji(t){return function(e){e=ju(e);var n=U(e)?tt(e):it,r=n?n[0]:e.charAt(0),i=n?Ai(n,1).join(""):e.slice(1);return r[t]()+i}}function Gi(t){return function(e){return m(Sc(cc(e).replace(Un,"")),t,"")}}function Zi(t){return function(){var e=arguments;switch(e.length){case 0:return new t;case 1:return new t(e[0]);case 2:return new t(e[0],e[1]);case 3:return new t(e[0],e[1],e[2]);case 4:return new t(e[0],e[1],e[2],e[3]);case 5:return new t(e[0],e[1],e[2],e[3],e[4]);case 6:return new t(e[0],e[1],e[2],e[3],e[4],e[5]);case 7:return new t(e[0],e[1],e[2],e[3],e[4],e[5],e[6])}var n=yf(t.prototype),r=t.apply(n,e);return uu(r)?r:n}}function Yi(t,e,n){function r(){for(var o=arguments.length,a=al(o),u=o,c=To(r);u--;)a[u]=arguments[u];var l=o<3&&a[0]!==c&&a[o-1]!==c?[]:K(a,c);if(o-=l.length,o<n)return co(t,e,eo,r.placeholder,it,a,l,it,it,n-o);var f=this&&this!==sr&&this instanceof r?i:t;return s(f,this,a)}var i=Zi(t); return r}function Qi(t){return function(e,n,r){var i=fl(e);if(!Gs(e)){var o=$o(n,3);e=Wu(e),n=function(t){return o(i[t],t,i)}}var a=t(e,n,r);return a>-1?i[o?e[a]:a]:it}}function to(t){return _o(function(e){var n=e.length,r=n,o=i.prototype.thru;for(t&&e.reverse();r--;){var a=e[r];if("function"!=typeof a)throw new hl(ut);if(o&&!s&&"wrapper"==Co(a))var s=new i([],!0)}for(r=s?r:n;++r<n;){a=e[r];var u=Co(a),c="wrapper"==u?Ef(a):it;s=c&&Bo(c[0])&&c[1]==(Tt|_t|xt|$t)&&!c[4].length&&1==c[9]?s[Co(c[0])].apply(s,c[3]):1==a.length&&Bo(a)?s[u]():s.thru(a)}return function(){var t=arguments,r=t[0];if(s&&1==t.length&&wp(r))return s.plant(r).value();for(var i=0,o=n?e[i].apply(this,t):r;++i<n;)o=e[i].call(this,o);return o}})}function eo(t,e,n,r,i,o,a,s,u,c){function l(){for(var m=arguments.length,y=al(m),b=m;b--;)y[b]=arguments[b];if(h)var _=To(l),w=M(y,_);if(r&&(y=Fi(y,r,i,h)),o&&(y=qi(y,o,a,h)),m-=w,h&&m<c){var x=K(y,_);return co(t,e,eo,l.placeholder,n,y,x,s,u,c-m)}var C=p?n:this,T=d?C[t]:t;return m=y.length,s?y=Qo(y,s):v&&m>1&&y.reverse(),f&&u<m&&(y.length=u),this&&this!==sr&&this instanceof l&&(T=g||Zi(T)),T.apply(C,y)}var f=e&Tt,p=e&mt,d=e&yt,h=e&(_t|wt),v=e&kt,g=d?it:Zi(t);return l}function no(t,e){return function(n,r){return Ar(n,t,e(r),{})}}function ro(t,e){return function(n,r){var i;if(n===it&&r===it)return e;if(n!==it&&(i=n),r!==it){if(i===it)return r;"string"==typeof n||"string"==typeof r?(n=gi(n),r=gi(r)):(n=vi(n),r=vi(r)),i=t(n,r)}return i}}function io(t){return _o(function(e){return e=v(e,R($o())),oi(function(n){var r=this;return t(e,function(t){return s(t,r,n)})})})}function oo(t,e){e=e===it?" ":gi(e);var n=e.length;if(n<2)return n?ii(e,t):e;var r=ii(e,Bl(t/Q(e)));return U(e)?Ai(tt(r),0,t).join(""):r.slice(0,t)}function ao(t,e,n,r){function i(){for(var e=-1,u=arguments.length,c=-1,l=r.length,f=al(l+u),p=this&&this!==sr&&this instanceof i?a:t;++c<l;)f[c]=r[c];for(;u--;)f[c++]=arguments[++e];return s(p,o?n:this,f)}var o=e&mt,a=Zi(t);return i}function so(t){return function(e,n,r){return r&&"number"!=typeof r&&qo(e,n,r)&&(n=r=it),e=$u(e),n===it?(n=e,e=0):n=$u(n),r=r===it?e<n?1:-1:$u(r),ri(e,n,r,t)}}function uo(t){return function(e,n){return"string"==typeof e&&"string"==typeof n||(e=Eu(e),n=Eu(n)),t(e,n)}}function co(t,e,n,r,i,o,a,s,u,c){var l=e&_t,f=l?a:it,p=l?it:a,d=l?o:it,h=l?it:o;e|=l?xt:Ct,e&=~(l?Ct:xt),e&bt||(e&=~(mt|yt));var v=[t,e,i,d,f,h,p,s,u,c],g=n.apply(it,v);return Bo(t)&&Df(g,v),g.placeholder=r,ta(g,t,e)}function lo(t){var e=ll[t];return function(t,n){if(t=Eu(t),n=null==n?0:Gl(ku(n),292)){var r=(ju(t)+"e").split("e"),i=e(r[0]+"e"+(+r[1]+n));return r=(ju(i)+"e").split("e"),+(r[0]+"e"+(+r[1]-n))}return e(t)}}function fo(t){return function(e){var n=jf(e);return n==Zt?V(e):n==ie?G(e):I(e,t(e))}}function po(t,e,n,r,i,o,a,s){var u=e&yt;if(!u&&"function"!=typeof t)throw new hl(ut);var c=r?r.length:0;if(c||(e&=~(xt|Ct),r=i=it),a=a===it?a:Jl(ku(a),0),s=s===it?s:ku(s),c-=i?i.length:0,e&Ct){var l=r,f=i;r=i=it}var p=u?it:Ef(t),d=[t,e,n,r,i,l,f,o,a,s];if(p&&Ko(d,p),t=d[0],e=d[1],n=d[2],r=d[3],i=d[4],s=d[9]=d[9]===it?u?0:t.length:Jl(d[9]-c,0),!s&&e&(_t|wt)&&(e&=~(_t|wt)),e&&e!=mt)h=e==_t||e==wt?Yi(t,e,s):e!=xt&&e!=(mt|xt)||i.length?eo.apply(it,d):ao(t,e,n,r);else var h=Ki(t,e,n);var v=p?Cf:Df;return ta(v(h,d),t,e)}function ho(t,e,n,r){return t===it||Js(t,ml[n])&&!_l.call(r,n)?e:t}function vo(t,e,n,r,i,o){return uu(t)&&uu(e)&&(o.set(e,t),Xr(t,e,it,vo,o),o.delete(e)),t}function go(t){return mu(t)?it:t}function mo(t,e,n,r,i,o){var a=n&vt,s=t.length,u=e.length;if(s!=u&&!(a&&u>s))return!1;var c=o.get(t);if(c&&o.get(e))return c==e;var l=-1,f=!0,p=n&gt?new yn:it;for(o.set(t,e),o.set(e,t);++l<s;){var d=t[l],h=e[l];if(r)var v=a?r(h,d,l,e,t,o):r(d,h,l,t,e,o);if(v!==it){if(v)continue;f=!1;break}if(p){if(!b(e,function(t,e){if(!P(p,e)&&(d===t||i(d,t,n,r,o)))return p.push(e)})){f=!1;break}}else if(d!==h&&!i(d,h,n,r,o)){f=!1;break}}return o.delete(t),o.delete(e),f}function yo(t,e,n,r,i,o,a){switch(n){case fe:if(t.byteLength!=e.byteLength||t.byteOffset!=e.byteOffset)return!1;t=t.buffer,e=e.buffer;case le:return!(t.byteLength!=e.byteLength||!o(new Sl(t),new Sl(e)));case zt:case Vt:case Yt:return Js(+t,+e);case Kt:return t.name==e.name&&t.message==e.message;case re:case oe:return t==e+"";case Zt:var s=V;case ie:var u=r&vt;if(s||(s=J),t.size!=e.size&&!u)return!1;var c=a.get(t);if(c)return c==e;r|=gt,a.set(t,e);var l=mo(s(t),s(e),r,i,o,a);return a.delete(t),l;case ae:if(gf)return gf.call(t)==gf.call(e)}return!1}function bo(t,e,n,r,i,o){var a=n&vt,s=wo(t),u=s.length,c=wo(e),l=c.length;if(u!=l&&!a)return!1;for(var f=u;f--;){var p=s[f];if(!(a?p in e:_l.call(e,p)))return!1}var d=o.get(t);if(d&&o.get(e))return d==e;var h=!0;o.set(t,e),o.set(e,t);for(var v=a;++f<u;){p=s[f];var g=t[p],m=e[p];if(r)var y=a?r(m,g,p,e,t,o):r(g,m,p,t,e,o);if(!(y===it?g===m||i(g,m,n,r,o):y)){h=!1;break}v||(v="constructor"==p)}if(h&&!v){var b=t.constructor,_=e.constructor;b!=_&&"constructor"in t&&"constructor"in e&&!("function"==typeof b&&b instanceof b&&"function"==typeof _&&_ instanceof _)&&(h=!1)}return o.delete(t),o.delete(e),h}function _o(t){return Rf(Zo(t,it,ma),t+"")}function wo(t){return cr(t,Wu,Sf)}function xo(t){return cr(t,zu,Of)}function Co(t){for(var e=t.name+"",n=cf[e],r=_l.call(cf,e)?n.length:0;r--;){var i=n[r],o=i.func;if(null==o||o==t)return i.name}return e}function To(t){var e=_l.call(n,"placeholder")?n:t;return e.placeholder}function $o(){var t=n.iteratee||Rc;return t=t===Rc?Mr:t,arguments.length?t(arguments[0],arguments[1]):t}function ko(t,e){var n=t.__data__;return Ho(e)?n["string"==typeof e?"string":"hash"]:n.map}function Ao(t){for(var e=Wu(t),n=e.length;n--;){var r=e[n],i=t[r];e[n]=[r,i,zo(i)]}return e}function Eo(t,e){var n=B(t,e);return Lr(n)?n:it}function So(t){var e=_l.call(t,Pl),n=t[Pl];try{t[Pl]=it;var r=!0}catch(t){}var i=Cl.call(t);return r&&(e?t[Pl]=n:delete t[Pl]),i}function Oo(t,e,n){for(var r=-1,i=n.length;++r<i;){var o=n[r],a=o.size;switch(o.type){case"drop":t+=a;break;case"dropRight":e-=a;break;case"take":e=Gl(e,t+a);break;case"takeRight":t=Jl(t,e-a)}}return{start:t,end:e}}function jo(t){var e=t.match(He);return e?e[1].split(Be):[]}function No(t,e,n){e=ki(e,t);for(var r=-1,i=e.length,o=!1;++r<i;){var a=ra(e[r]);if(!(o=null!=t&&n(t,a)))break;t=t[a]}return o||++r!=i?o:(i=null==t?0:t.length,!!i&&su(i)&&Fo(a,i)&&(wp(t)||_p(t)))}function Do(t){var e=t.length,n=t.constructor(e);return e&&"string"==typeof t[0]&&_l.call(t,"index")&&(n.index=t.index,n.input=t.input),n}function Io(t){return"function"!=typeof t.constructor||Wo(t)?{}:yf(jl(t))}function Ro(t,e,n,r){var i=t.constructor;switch(e){case le:return Si(t);case zt:case Vt:return new i(+t);case fe:return Oi(t,r);case pe:case de:case he:case ve:case ge:case me:case ye:case be:case _e:return Ri(t,r);case Zt:return ji(t,r,n);case Yt:case oe:return new i(t);case re:return Ni(t);case ie:return Di(t,r,n);case ae:return Ii(t)}}function Lo(t,e){var n=e.length;if(!n)return t;var r=n-1;return e[r]=(n>1?"& ":"")+e[r],e=e.join(n>2?", ":" "),t.replace(Me,"{\n/* [wrapped with "+e+"] */\n")}function Po(t){return wp(t)||_p(t)||!!(Rl&&t&&t[Rl])}function Fo(t,e){return e=null==e?Rt:e,!!e&&("number"==typeof t||Ze.test(t))&&t>-1&&t%1==0&&t<e}function qo(t,e,n){if(!uu(n))return!1;var r=typeof e;return!!("number"==r?Gs(n)&&Fo(e,n.length):"string"==r&&e in n)&&Js(n[e],t)}function Mo(t,e){if(wp(t))return!1;var n=typeof t;return!("number"!=n&&"symbol"!=n&&"boolean"!=n&&null!=t&&!_u(t))||(Ne.test(t)||!je.test(t)||null!=e&&t in fl(e))}function Ho(t){var e=typeof t;return"string"==e||"number"==e||"symbol"==e||"boolean"==e?"__proto__"!==t:null===t}function Bo(t){var e=Co(t),r=n[e];if("function"!=typeof r||!(e in _.prototype))return!1;if(t===r)return!0;var i=Ef(r);return!!i&&t===i[0]}function Uo(t){return!!xl&&xl in t}function Wo(t){var e=t&&t.constructor,n="function"==typeof e&&e.prototype||ml;return t===n}function zo(t){return t===t&&!uu(t)}function Vo(t,e){return function(n){return null!=n&&(n[t]===e&&(e!==it||t in fl(n)))}}function Xo(t){var e=Rs(t,function(t){return n.size===lt&&n.clear(),t}),n=e.cache;return e}function Ko(t,e){var n=t[1],r=e[1],i=n|r,o=i<(mt|yt|Tt),a=r==Tt&&n==_t||r==Tt&&n==$t&&t[7].length<=e[8]||r==(Tt|$t)&&e[7].length<=e[8]&&n==_t;if(!o&&!a)return t;r&mt&&(t[2]=e[2],i|=n&mt?0:bt);var s=e[3];if(s){var u=t[3];t[3]=u?Fi(u,s,e[4]):s,t[4]=u?K(t[3],ft):e[4]}return s=e[5],s&&(u=t[5],t[5]=u?qi(u,s,e[6]):s,t[6]=u?K(t[5],ft):e[6]),s=e[7],s&&(t[7]=s),r&Tt&&(t[8]=null==t[8]?e[8]:Gl(t[8],e[8])),null==t[9]&&(t[9]=e[9]),t[0]=e[0],t[1]=i,t}function Jo(t){var e=[];if(null!=t)for(var n in fl(t))e.push(n);return e}function Go(t){return Cl.call(t)}function Zo(t,e,n){return e=Jl(e===it?t.length-1:e,0),function(){for(var r=arguments,i=-1,o=Jl(r.length-e,0),a=al(o);++i<o;)a[i]=r[e+i];i=-1;for(var u=al(e+1);++i<e;)u[i]=r[i];return u[e]=n(a),s(t,this,u)}}function Yo(t,e){return e.length<2?t:ur(t,li(e,0,-1))}function Qo(t,e){for(var n=t.length,r=Gl(e.length,n),i=Mi(t);r--;){var o=e[r];t[r]=Fo(o,n)?i[o]:it}return t}function ta(t,e,n){var r=e+"";return Rf(t,Lo(r,oa(jo(r),n)))}function ea(t){var e=0,n=0;return function(){var r=Zl(),i=Ot-(r-n);if(n=r,i>0){if(++e>=St)return arguments[0]}else e=0;return t.apply(it,arguments)}}function na(t,e){var n=-1,r=t.length,i=r-1;for(e=e===it?r:e;++n<e;){var o=ni(n,i),a=t[o];t[o]=t[n],t[n]=a}return t.length=e,t}function ra(t){if("string"==typeof t||_u(t))return t;var e=t+"";return"0"==e&&1/t==-It?"-0":e}function ia(t){if(null!=t){try{return bl.call(t)}catch(t){}try{return t+""}catch(t){}}return""}function oa(t,e){return c(Ht,function(n){var r="_."+n[0];e&n[1]&&!d(t,r)&&t.push(r)}),t.sort()}function aa(t){if(t instanceof _)return t.clone();var e=new i(t.__wrapped__,t.__chain__);return e.__actions__=Mi(t.__actions__),e.__index__=t.__index__,e.__values__=t.__values__,e}function sa(t,e,n){e=(n?qo(t,e,n):e===it)?1:Jl(ku(e),0);var r=null==t?0:t.length;if(!r||e<1)return[];for(var i=0,o=0,a=al(Bl(r/e));i<r;)a[o++]=li(t,i,i+=e);return a}function ua(t){for(var e=-1,n=null==t?0:t.length,r=0,i=[];++e<n;){var o=t[e];o&&(i[r++]=o)}return i}function ca(){var t=arguments.length;if(!t)return[];for(var e=al(t-1),n=arguments[0],r=t;r--;)e[r-1]=arguments[r];return g(wp(n)?Mi(n):[n],er(e,1))}function la(t,e,n){var r=null==t?0:t.length;return r?(e=n||e===it?1:ku(e),li(t,e<0?0:e,r)):[]}function fa(t,e,n){var r=null==t?0:t.length;return r?(e=n||e===it?1:ku(e),e=r-e,li(t,0,e<0?0:e)):[]}function pa(t,e){return t&&t.length?_i(t,$o(e,3),!0,!0):[]}function da(t,e){return t&&t.length?_i(t,$o(e,3),!0):[]}function ha(t,e,n,r){var i=null==t?0:t.length;return i?(n&&"number"!=typeof n&&qo(t,e,n)&&(n=0,r=i),Qn(t,e,n,r)):[]}function va(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=null==n?0:ku(n);return i<0&&(i=Jl(r+i,0)),C(t,$o(e,3),i)}function ga(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=r-1;return n!==it&&(i=ku(n),i=n<0?Jl(r+i,0):Gl(i,r-1)),C(t,$o(e,3),i,!0)}function ma(t){var e=null==t?0:t.length;return e?er(t,1):[]}function ya(t){var e=null==t?0:t.length;return e?er(t,It):[]}function ba(t,e){var n=null==t?0:t.length;return n?(e=e===it?1:ku(e),er(t,e)):[]}function _a(t){for(var e=-1,n=null==t?0:t.length,r={};++e<n;){var i=t[e];r[i[0]]=i[1]}return r}function wa(t){return t&&t.length?t[0]:it}function xa(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=null==n?0:ku(n);return i<0&&(i=Jl(r+i,0)),T(t,e,i)}function Ca(t){var e=null==t?0:t.length;return e?li(t,0,-1):[]}function Ta(t,e){return null==t?"":Xl.call(t,e)}function $a(t){var e=null==t?0:t.length;return e?t[e-1]:it}function ka(t,e,n){var r=null==t?0:t.length;if(!r)return-1;var i=r;return n!==it&&(i=ku(n),i=i<0?Jl(r+i,0):Gl(i,r-1)),e===e?Y(t,e,i):C(t,k,i,!0)}function Aa(t,e){return t&&t.length?Jr(t,ku(e)):it}function Ea(t,e){return t&&t.length&&e&&e.length?ti(t,e):t}function Sa(t,e,n){return t&&t.length&&e&&e.length?ti(t,e,$o(n,2)):t}function Oa(t,e,n){return t&&t.length&&e&&e.length?ti(t,e,it,n):t}function ja(t,e){var n=[];if(!t||!t.length)return n;var r=-1,i=[],o=t.length;for(e=$o(e,3);++r<o;){var a=t[r];e(a,r,t)&&(n.push(a),i.push(r))}return ei(t,i),n}function Na(t){return null==t?t:tf.call(t)}function Da(t,e,n){var r=null==t?0:t.length;return r?(n&&"number"!=typeof n&&qo(t,e,n)?(e=0,n=r):(e=null==e?0:ku(e),n=n===it?r:ku(n)),li(t,e,n)):[]}function Ia(t,e){return pi(t,e)}function Ra(t,e,n){return di(t,e,$o(n,2))}function La(t,e){var n=null==t?0:t.length;if(n){var r=pi(t,e);if(r<n&&Js(t[r],e))return r}return-1}function Pa(t,e){return pi(t,e,!0)}function Fa(t,e,n){return di(t,e,$o(n,2),!0)}function qa(t,e){var n=null==t?0:t.length;if(n){var r=pi(t,e,!0)-1;if(Js(t[r],e))return r}return-1}function Ma(t){return t&&t.length?hi(t):[]}function Ha(t,e){return t&&t.length?hi(t,$o(e,2)):[]}function Ba(t){var e=null==t?0:t.length;return e?li(t,1,e):[]}function Ua(t,e,n){return t&&t.length?(e=n||e===it?1:ku(e),li(t,0,e<0?0:e)):[]}function Wa(t,e,n){var r=null==t?0:t.length;return r?(e=n||e===it?1:ku(e),e=r-e,li(t,e<0?0:e,r)):[]}function za(t,e){return t&&t.length?_i(t,$o(e,3),!1,!0):[]}function Va(t,e){return t&&t.length?_i(t,$o(e,3)):[]}function Xa(t){return t&&t.length?mi(t):[]}function Ka(t,e){return t&&t.length?mi(t,$o(e,2)):[]}function Ja(t,e){return e="function"==typeof e?e:it,t&&t.length?mi(t,it,e):[]}function Ga(t){if(!t||!t.length)return[];var e=0;return t=p(t,function(t){if(Zs(t))return e=Jl(t.length,e),!0}),D(e,function(e){return v(t,E(e))})}function Za(t,e){if(!t||!t.length)return[];var n=Ga(t);return null==e?n:v(n,function(t){return s(e,it,t)})}function Ya(t,e){return Ci(t||[],e||[],Nn)}function Qa(t,e){return Ci(t||[],e||[],ui)}function ts(t){var e=n(t);return e.__chain__=!0,e}function es(t,e){return e(t),t}function ns(t,e){return e(t)}function rs(){return ts(this)}function is(){return new i(this.value(),this.__chain__)}function os(){this.__values__===it&&(this.__values__=Tu(this.value()));var t=this.__index__>=this.__values__.length,e=t?it:this.__values__[this.__index__++];return{done:t,value:e}}function as(){return this}function ss(t){for(var e,n=this;n instanceof r;){var i=aa(n);i.__index__=0,i.__values__=it,e?o.__wrapped__=i:e=i;var o=i;n=n.__wrapped__}return o.__wrapped__=t,e}function us(){var t=this.__wrapped__;if(t instanceof _){var e=t;return this.__actions__.length&&(e=new _(this)),e=e.reverse(),e.__actions__.push({func:ns,args:[Na],thisArg:it}),new i(e,this.__chain__)}return this.thru(Na)}function cs(){return wi(this.__wrapped__,this.__actions__)}function ls(t,e,n){var r=wp(t)?f:Xn;return n&&qo(t,e,n)&&(e=it),r(t,$o(e,3))}function fs(t,e){var n=wp(t)?p:tr;return n(t,$o(e,3))}function ps(t,e){return er(ys(t,e),1)}function ds(t,e){return er(ys(t,e),It)}function hs(t,e,n){return n=n===it?1:ku(n),er(ys(t,e),n)}function vs(t,e){var n=wp(t)?c:bf;return n(t,$o(e,3))}function gs(t,e){var n=wp(t)?l:_f;return n(t,$o(e,3))}function ms(t,e,n,r){t=Gs(t)?t:rc(t),n=n&&!r?ku(n):0;var i=t.length;return n<0&&(n=Jl(i+n,0)),bu(t)?n<=i&&t.indexOf(e,n)>-1:!!i&&T(t,e,n)>-1}function ys(t,e){var n=wp(t)?v:Wr;return n(t,$o(e,3))}function bs(t,e,n,r){return null==t?[]:(wp(e)||(e=null==e?[]:[e]),n=r?it:n,wp(n)||(n=null==n?[]:[n]),Gr(t,e,n))}function _s(t,e,n){var r=wp(t)?m:O,i=arguments.length<3;return r(t,$o(e,4),n,i,bf)}function ws(t,e,n){var r=wp(t)?y:O,i=arguments.length<3;return r(t,$o(e,4),n,i,_f)}function xs(t,e){var n=wp(t)?p:tr;return n(t,Ls($o(e,3)))}function Cs(t){var e=wp(t)?En:ai;return e(t)}function Ts(t,e,n){e=(n?qo(t,e,n):e===it)?1:ku(e);var r=wp(t)?Sn:si;return r(t,e)}function $s(t){var e=wp(t)?On:ci;return e(t)}function ks(t){if(null==t)return 0;if(Gs(t))return bu(t)?Q(t):t.length;var e=jf(t);return e==Zt||e==ie?t.size:Hr(t).length}function As(t,e,n){var r=wp(t)?b:fi;return n&&qo(t,e,n)&&(e=it),r(t,$o(e,3))}function Es(t,e){if("function"!=typeof e)throw new hl(ut);return t=ku(t),function(){if(--t<1)return e.apply(this,arguments)}}function Ss(t,e,n){return e=n?it:e,e=t&&null==e?t.length:e,po(t,Tt,it,it,it,it,e)}function Os(t,e){var n;if("function"!=typeof e)throw new hl(ut);return t=ku(t),function(){return--t>0&&(n=e.apply(this,arguments)),t<=1&&(e=it),n}}function js(t,e,n){e=n?it:e;var r=po(t,_t,it,it,it,it,it,e);return r.placeholder=js.placeholder,r}function Ns(t,e,n){e=n?it:e;var r=po(t,wt,it,it,it,it,it,e);return r.placeholder=Ns.placeholder,r}function Ds(t,e,n){function r(e){var n=p,r=d;return p=d=it,y=e,v=t.apply(r,n)}function i(t){return y=t,g=If(s,e),b?r(t):v}function o(t){var n=t-m,r=t-y,i=e-n;return _?Gl(i,h-r):i}function a(t){var n=t-m,r=t-y;return m===it||n>=e||n<0||_&&r>=h}function s(){var t=cp();return a(t)?u(t):void(g=If(s,o(t)))}function u(t){return g=it,w&&p?r(t):(p=d=it,v)}function c(){g!==it&&kf(g),y=0,p=m=d=g=it}function l(){return g===it?v:u(cp())}function f(){var t=cp(),n=a(t);if(p=arguments,d=this,m=t,n){if(g===it)return i(m);if(_)return g=If(s,e),r(m)}return g===it&&(g=If(s,e)),v}var p,d,h,v,g,m,y=0,b=!1,_=!1,w=!0;if("function"!=typeof t)throw new hl(ut);return e=Eu(e)||0,uu(n)&&(b=!!n.leading,_="maxWait"in n,h=_?Jl(Eu(n.maxWait)||0,e):h,w="trailing"in n?!!n.trailing:w),f.cancel=c,f.flush=l,f}function Is(t){return po(t,kt)}function Rs(t,e){if("function"!=typeof t||null!=e&&"function"!=typeof e)throw new hl(ut);var n=function(){var r=arguments,i=e?e.apply(this,r):r[0],o=n.cache;if(o.has(i))return o.get(i);var a=t.apply(this,r);return n.cache=o.set(i,a)||o,a};return n.cache=new(Rs.Cache||pn),n}function Ls(t){if("function"!=typeof t)throw new hl(ut);return function(){var e=arguments;switch(e.length){case 0:return!t.call(this);case 1:return!t.call(this,e[0]);case 2:return!t.call(this,e[0],e[1]);case 3:return!t.call(this,e[0],e[1],e[2])}return!t.apply(this,e)}}function Ps(t){return Os(2,t)}function Fs(t,e){if("function"!=typeof t)throw new hl(ut);return e=e===it?e:ku(e),oi(t,e)}function qs(t,e){if("function"!=typeof t)throw new hl(ut);return e=null==e?0:Jl(ku(e),0),oi(function(n){var r=n[e],i=Ai(n,0,e);return r&&g(i,r),s(t,this,i)})}function Ms(t,e,n){var r=!0,i=!0;if("function"!=typeof t)throw new hl(ut);return uu(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),Ds(t,e,{leading:r,maxWait:e,trailing:i})}function Hs(t){return Ss(t,1)}function Bs(t,e){return vp($i(e),t)}function Us(){if(!arguments.length)return[];var t=arguments[0];return wp(t)?t:[t]}function Ws(t){return Mn(t,ht)}function zs(t,e){return e="function"==typeof e?e:it,Mn(t,ht,e)}function Vs(t){return Mn(t,pt|ht)}function Xs(t,e){return e="function"==typeof e?e:it,Mn(t,pt|ht,e)}function Ks(t,e){return null==e||Bn(t,e,Wu(e))}function Js(t,e){return t===e||t!==t&&e!==e}function Gs(t){return null!=t&&su(t.length)&&!ou(t)}function Zs(t){return cu(t)&&Gs(t)}function Ys(t){return t===!0||t===!1||cu(t)&&fr(t)==zt}function Qs(t){return cu(t)&&1===t.nodeType&&!mu(t)}function tu(t){if(null==t)return!0;if(Gs(t)&&(wp(t)||"string"==typeof t||"function"==typeof t.splice||Cp(t)||Ep(t)||_p(t)))return!t.length;var e=jf(t);if(e==Zt||e==ie)return!t.size;if(Wo(t))return!Hr(t).length;for(var n in t)if(_l.call(t,n))return!1;return!0}function eu(t,e){return Nr(t,e)}function nu(t,e,n){n="function"==typeof n?n:it;var r=n?n(t,e):it;return r===it?Nr(t,e,it,n):!!r}function ru(t){if(!cu(t))return!1;var e=fr(t);return e==Kt||e==Xt||"string"==typeof t.message&&"string"==typeof t.name&&!mu(t)}function iu(t){return"number"==typeof t&&Vl(t)}function ou(t){if(!uu(t))return!1;var e=fr(t);return e==Jt||e==Gt||e==Wt||e==ne}function au(t){return"number"==typeof t&&t==ku(t)}function su(t){return"number"==typeof t&&t>-1&&t%1==0&&t<=Rt}function uu(t){var e=typeof t;return null!=t&&("object"==e||"function"==e)}function cu(t){return null!=t&&"object"==typeof t}function lu(t,e){return t===e||Rr(t,e,Ao(e))}function fu(t,e,n){return n="function"==typeof n?n:it,Rr(t,e,Ao(e),n)}function pu(t){return gu(t)&&t!=+t}function du(t){if(Nf(t))throw new ul(st);return Lr(t)}function hu(t){return null===t}function vu(t){return null==t}function gu(t){return"number"==typeof t||cu(t)&&fr(t)==Yt}function mu(t){if(!cu(t)||fr(t)!=te)return!1;var e=jl(t);if(null===e)return!0;var n=_l.call(e,"constructor")&&e.constructor;return"function"==typeof n&&n instanceof n&&bl.call(n)==Tl}function yu(t){return au(t)&&t>=-Rt&&t<=Rt}function bu(t){return"string"==typeof t||!wp(t)&&cu(t)&&fr(t)==oe}function _u(t){return"symbol"==typeof t||cu(t)&&fr(t)==ae}function wu(t){return t===it}function xu(t){return cu(t)&&jf(t)==ue}function Cu(t){return cu(t)&&fr(t)==ce}function Tu(t){if(!t)return[];if(Gs(t))return bu(t)?tt(t):Mi(t);if(Ll&&t[Ll])return z(t[Ll]());var e=jf(t),n=e==Zt?V:e==ie?J:rc;return n(t)}function $u(t){if(!t)return 0===t?t:0;if(t=Eu(t),t===It||t===-It){var e=t<0?-1:1;return e*Lt}return t===t?t:0}function ku(t){var e=$u(t),n=e%1;return e===e?n?e-n:e:0}function Au(t){return t?qn(ku(t),0,Ft):0}function Eu(t){if("number"==typeof t)return t;if(_u(t))return Pt;if(uu(t)){var e="function"==typeof t.valueOf?t.valueOf():t;t=uu(e)?e+"":e}if("string"!=typeof t)return 0===t?t:+t;t=t.replace(Pe,"");var n=Ke.test(t);return n||Ge.test(t)?ir(t.slice(2),n?2:8):Xe.test(t)?Pt:+t}function Su(t){return Hi(t,zu(t))}function Ou(t){return t?qn(ku(t),-Rt,Rt):0===t?t:0}function ju(t){return null==t?"":gi(t)}function Nu(t,e){var n=yf(t);return null==e?n:Rn(n,e)}function Du(t,e){return x(t,$o(e,3),nr)}function Iu(t,e){return x(t,$o(e,3),or)}function Ru(t,e){return null==t?t:wf(t,$o(e,3),zu)}function Lu(t,e){return null==t?t:xf(t,$o(e,3),zu)}function Pu(t,e){return t&&nr(t,$o(e,3))}function Fu(t,e){return t&&or(t,$o(e,3))}function qu(t){return null==t?[]:ar(t,Wu(t))}function Mu(t){return null==t?[]:ar(t,zu(t))}function Hu(t,e,n){var r=null==t?it:ur(t,e);return r===it?n:r}function Bu(t,e){return null!=t&&No(t,e,br)}function Uu(t,e){return null!=t&&No(t,e,Cr)}function Wu(t){return Gs(t)?An(t):Hr(t)}function zu(t){return Gs(t)?An(t,!0):Br(t)}function Vu(t,e){var n={};return e=$o(e,3),nr(t,function(t,r,i){Pn(n,e(t,r,i),t)}),n}function Xu(t,e){var n={};return e=$o(e,3),nr(t,function(t,r,i){Pn(n,r,e(t,r,i))}),n}function Ku(t,e){return Ju(t,Ls($o(e)))}function Ju(t,e){if(null==t)return{};var n=v(xo(t),function(t){return[t]});return e=$o(e),Yr(t,n,function(t,n){return e(t,n[0])})}function Gu(t,e,n){e=ki(e,t);var r=-1,i=e.length;for(i||(i=1,t=it);++r<i;){var o=null==t?it:t[ra(e[r])];o===it&&(r=i,o=n),t=ou(o)?o.call(t):o}return t}function Zu(t,e,n){return null==t?t:ui(t,e,n)}function Yu(t,e,n,r){return r="function"==typeof r?r:it,null==t?t:ui(t,e,n,r)}function Qu(t,e,n){var r=wp(t),i=r||Cp(t)||Ep(t);if(e=$o(e,4),null==n){var o=t&&t.constructor;n=i?r?new o:[]:uu(t)&&ou(o)?yf(jl(t)):{}}return(i?c:nr)(t,function(t,r,i){return e(n,t,r,i)}),n}function tc(t,e){return null==t||yi(t,e)}function ec(t,e,n){return null==t?t:bi(t,e,$i(n))}function nc(t,e,n,r){return r="function"==typeof r?r:it,null==t?t:bi(t,e,$i(n),r)}function rc(t){return null==t?[]:L(t,Wu(t))}function ic(t){return null==t?[]:L(t,zu(t))}function oc(t,e,n){return n===it&&(n=e,e=it),n!==it&&(n=Eu(n),n=n===n?n:0),e!==it&&(e=Eu(e),e=e===e?e:0),qn(Eu(t),e,n)}function ac(t,e,n){return e=$u(e),n===it?(n=e,e=0):n=$u(n),t=Eu(t),$r(t,e,n)}function sc(t,e,n){if(n&&"boolean"!=typeof n&&qo(t,e,n)&&(e=n=it),n===it&&("boolean"==typeof e?(n=e,e=it):"boolean"==typeof t&&(n=t,t=it)),t===it&&e===it?(t=0,e=1):(t=$u(t),e===it?(e=t,t=0):e=$u(e)),t>e){var r=t;t=e,e=r}if(n||t%1||e%1){var i=Ql();return Gl(t+i*(e-t+rr("1e-"+((i+"").length-1))),e)}return ni(t,e)}function uc(t){return td(ju(t).toLowerCase())}function cc(t){return t=ju(t),t&&t.replace(Ye,_r).replace(Wn,"")}function lc(t,e,n){t=ju(t),e=gi(e);var r=t.length;n=n===it?r:qn(ku(n),0,r);var i=n;return n-=e.length,n>=0&&t.slice(n,i)==e}function fc(t){return t=ju(t),t&&Ae.test(t)?t.replace($e,wr):t}function pc(t){return t=ju(t),t&&Le.test(t)?t.replace(Re,"\\$&"):t}function dc(t,e,n){t=ju(t),e=ku(e);var r=e?Q(t):0;if(!e||r>=e)return t;var i=(e-r)/2;return oo(Ul(i),n)+t+oo(Bl(i),n)}function hc(t,e,n){t=ju(t),e=ku(e);var r=e?Q(t):0;return e&&r<e?t+oo(e-r,n):t}function vc(t,e,n){t=ju(t),e=ku(e);var r=e?Q(t):0;return e&&r<e?oo(e-r,n)+t:t}function gc(t,e,n){return n||null==e?e=0:e&&(e=+e),Yl(ju(t).replace(Fe,""),e||0)}function mc(t,e,n){return e=(n?qo(t,e,n):e===it)?1:ku(e),ii(ju(t),e)}function yc(){var t=arguments,e=ju(t[0]);return t.length<3?e:e.replace(t[1],t[2])}function bc(t,e,n){return n&&"number"!=typeof n&&qo(t,e,n)&&(e=n=it),(n=n===it?Ft:n>>>0)?(t=ju(t),t&&("string"==typeof e||null!=e&&!kp(e))&&(e=gi(e),!e&&U(t))?Ai(tt(t),0,n):t.split(e,n)):[]}function _c(t,e,n){return t=ju(t),n=null==n?0:qn(ku(n),0,t.length),e=gi(e),t.slice(n,n+e.length)==e}function wc(t,e,r){var i=n.templateSettings;r&&qo(t,e,r)&&(e=it),t=ju(t),e=Dp({},e,i,ho);var o,a,s=Dp({},e.imports,i.imports,ho),u=Wu(s),c=L(s,u),l=0,f=e.interpolate||Qe,p="__p += '",d=pl((e.escape||Qe).source+"|"+f.source+"|"+(f===Oe?ze:Qe).source+"|"+(e.evaluate||Qe).source+"|$","g"),h="//# sourceURL="+("sourceURL"in e?e.sourceURL:"lodash.templateSources["+ ++Gn+"]")+"\n";t.replace(d,function(e,n,r,i,s,u){return r||(r=i),p+=t.slice(l,u).replace(tn,H),n&&(o=!0,p+="' +\n__e("+n+") +\n'"),s&&(a=!0,p+="';\n"+s+";\n__p += '"),r&&(p+="' +\n((__t = ("+r+")) == null ? '' : __t) +\n'"),l=u+e.length,e}),p+="';\n";var v=e.variable;v||(p="with (obj) {\n"+p+"\n}\n"),p=(a?p.replace(we,""):p).replace(xe,"$1").replace(Ce,"$1;"),p="function("+(v||"obj")+") {\n"+(v?"":"obj || (obj = {});\n")+"var __t, __p = ''"+(o?", __e = _.escape":"")+(a?", __j = Array.prototype.join;\nfunction print() { __p += __j.call(arguments, '') }\n":";\n")+p+"return __p\n}";var g=ed(function(){return cl(u,h+"return "+p).apply(it,c)});if(g.source=p,ru(g))throw g;return g}function xc(t){return ju(t).toLowerCase()}function Cc(t){return ju(t).toUpperCase()}function Tc(t,e,n){if(t=ju(t),t&&(n||e===it))return t.replace(Pe,"");if(!t||!(e=gi(e)))return t;var r=tt(t),i=tt(e),o=F(r,i),a=q(r,i)+1;return Ai(r,o,a).join("")}function $c(t,e,n){if(t=ju(t),t&&(n||e===it))return t.replace(qe,"");if(!t||!(e=gi(e)))return t;var r=tt(t),i=q(r,tt(e))+1;return Ai(r,0,i).join("")}function kc(t,e,n){if(t=ju(t),t&&(n||e===it))return t.replace(Fe,"");if(!t||!(e=gi(e)))return t;var r=tt(t),i=F(r,tt(e));return Ai(r,i).join("")}function Ac(t,e){var n=At,r=Et;if(uu(e)){var i="separator"in e?e.separator:i;n="length"in e?ku(e.length):n,r="omission"in e?gi(e.omission):r}t=ju(t);var o=t.length;if(U(t)){var a=tt(t);o=a.length}if(n>=o)return t;var s=n-Q(r);if(s<1)return r;var u=a?Ai(a,0,s).join(""):t.slice(0,s);if(i===it)return u+r;if(a&&(s+=u.length-s),kp(i)){if(t.slice(s).search(i)){var c,l=u;for(i.global||(i=pl(i.source,ju(Ve.exec(i))+"g")),i.lastIndex=0;c=i.exec(l);)var f=c.index;u=u.slice(0,f===it?s:f)}}else if(t.indexOf(gi(i),s)!=s){var p=u.lastIndexOf(i);p>-1&&(u=u.slice(0,p))}return u+r}function Ec(t){return t=ju(t),t&&ke.test(t)?t.replace(Te,xr):t}function Sc(t,e,n){return t=ju(t),e=n?it:e,e===it?W(t)?rt(t):w(t):t.match(e)||[]}function Oc(t){var e=null==t?0:t.length,n=$o();return t=e?v(t,function(t){if("function"!=typeof t[1])throw new hl(ut);return[n(t[0]),t[1]]}):[],oi(function(n){for(var r=-1;++r<e;){var i=t[r];if(s(i[0],this,n))return s(i[1],this,n)}})}function jc(t){return Hn(Mn(t,pt))}function Nc(t){return function(){return t}}function Dc(t,e){return null==t||t!==t?e:t}function Ic(t){return t}function Rc(t){return Mr("function"==typeof t?t:Mn(t,pt))}function Lc(t){return zr(Mn(t,pt))}function Pc(t,e){return Vr(t,Mn(e,pt))}function Fc(t,e,n){var r=Wu(e),i=ar(e,r);null!=n||uu(e)&&(i.length||!r.length)||(n=e,e=t,t=this,i=ar(e,Wu(e)));var o=!(uu(n)&&"chain"in n&&!n.chain),a=ou(t);return c(i,function(n){var r=e[n];t[n]=r,a&&(t.prototype[n]=function(){var e=this.__chain__;if(o||e){var n=t(this.__wrapped__),i=n.__actions__=Mi(this.__actions__);return i.push({func:r,args:arguments,thisArg:t}),n.__chain__=e,n}return r.apply(t,g([this.value()],arguments))})}),t}function qc(){return sr._===this&&(sr._=$l),this}function Mc(){}function Hc(t){return t=ku(t),oi(function(e){return Jr(e,t)})}function Bc(t){return Mo(t)?E(ra(t)):Qr(t)}function Uc(t){return function(e){return null==t?it:ur(t,e)}}function Wc(){return[]}function zc(){return!1}function Vc(){return{}}function Xc(){return""}function Kc(){return!0}function Jc(t,e){if(t=ku(t),t<1||t>Rt)return[];var n=Ft,r=Gl(t,Ft);e=$o(e),t-=Ft;for(var i=D(r,e);++n<t;)e(n);return i}function Gc(t){return wp(t)?v(t,ra):_u(t)?[t]:Mi(Lf(ju(t)))}function Zc(t){var e=++wl;return ju(t)+e}function Yc(t){return t&&t.length?Kn(t,Ic,pr):it}function Qc(t,e){return t&&t.length?Kn(t,$o(e,2),pr):it}function tl(t){return A(t,Ic)}function el(t,e){return A(t,$o(e,2))}function nl(t){return t&&t.length?Kn(t,Ic,Ur):it}function rl(t,e){return t&&t.length?Kn(t,$o(e,2),Ur):it}function il(t){return t&&t.length?N(t,Ic):0}function ol(t,e){return t&&t.length?N(t,$o(e,2)):0}e=null==e?sr:Tr.defaults(sr.Object(),e,Tr.pick(sr,Jn));var al=e.Array,sl=e.Date,ul=e.Error,cl=e.Function,ll=e.Math,fl=e.Object,pl=e.RegExp,dl=e.String,hl=e.TypeError,vl=al.prototype,gl=cl.prototype,ml=fl.prototype,yl=e["__core-js_shared__"],bl=gl.toString,_l=ml.hasOwnProperty,wl=0,xl=function(){var t=/[^.]+$/.exec(yl&&yl.keys&&yl.keys.IE_PROTO||"");return t?"Symbol(src)_1."+t:""}(),Cl=ml.toString,Tl=bl.call(fl),$l=sr._,kl=pl("^"+bl.call(_l).replace(Re,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$"),Al=lr?e.Buffer:it,El=e.Symbol,Sl=e.Uint8Array,Ol=Al?Al.allocUnsafe:it,jl=X(fl.getPrototypeOf,fl),Nl=fl.create,Dl=ml.propertyIsEnumerable,Il=vl.splice,Rl=El?El.isConcatSpreadable:it,Ll=El?El.iterator:it,Pl=El?El.toStringTag:it,Fl=function(){try{var t=Eo(fl,"defineProperty");return t({},"",{}),t}catch(t){}}(),ql=e.clearTimeout!==sr.clearTimeout&&e.clearTimeout,Ml=sl&&sl.now!==sr.Date.now&&sl.now,Hl=e.setTimeout!==sr.setTimeout&&e.setTimeout,Bl=ll.ceil,Ul=ll.floor,Wl=fl.getOwnPropertySymbols,zl=Al?Al.isBuffer:it,Vl=e.isFinite,Xl=vl.join,Kl=X(fl.keys,fl),Jl=ll.max,Gl=ll.min,Zl=sl.now,Yl=e.parseInt,Ql=ll.random,tf=vl.reverse,ef=Eo(e,"DataView"),nf=Eo(e,"Map"),rf=Eo(e,"Promise"),of=Eo(e,"Set"),af=Eo(e,"WeakMap"),sf=Eo(fl,"create"),uf=af&&new af,cf={},lf=ia(ef),ff=ia(nf),pf=ia(rf),df=ia(of),hf=ia(af),vf=El?El.prototype:it,gf=vf?vf.valueOf:it,mf=vf?vf.toString:it,yf=function(){function t(){}return function(e){if(!uu(e))return{};if(Nl)return Nl(e);t.prototype=e;var n=new t;return t.prototype=it,n}}();n.templateSettings={escape:Ee,evaluate:Se,interpolate:Oe,variable:"",imports:{_:n}},n.prototype=r.prototype,n.prototype.constructor=n,i.prototype=yf(r.prototype),i.prototype.constructor=i,_.prototype=yf(r.prototype),_.prototype.constructor=_,nt.prototype.clear=Ue,nt.prototype.delete=en,nt.prototype.get=nn,nt.prototype.has=rn,nt.prototype.set=on,an.prototype.clear=sn,an.prototype.delete=un,an.prototype.get=cn,an.prototype.has=ln,an.prototype.set=fn,pn.prototype.clear=dn,pn.prototype.delete=hn,pn.prototype.get=vn,pn.prototype.has=gn,pn.prototype.set=mn,yn.prototype.add=yn.prototype.push=bn,yn.prototype.has=_n,wn.prototype.clear=xn,wn.prototype.delete=Cn,wn.prototype.get=Tn,wn.prototype.has=$n,wn.prototype.set=kn;var bf=Vi(nr),_f=Vi(or,!0),wf=Xi(),xf=Xi(!0),Cf=uf?function(t,e){return uf.set(t,e),t}:Ic,Tf=Fl?function(t,e){return Fl(t,"toString",{configurable:!0,enumerable:!1,value:Nc(e),writable:!0})}:Ic,$f=oi,kf=ql||function(t){return sr.clearTimeout(t)},Af=of&&1/J(new of([,-0]))[1]==It?function(t){return new of(t)}:Mc,Ef=uf?function(t){return uf.get(t)}:Mc,Sf=Wl?function(t){return null==t?[]:(t=fl(t),p(Wl(t),function(e){return Dl.call(t,e)}))}:Wc,Of=Wl?function(t){for(var e=[];t;)g(e,Sf(t)),t=jl(t);return e}:Wc,jf=fr;(ef&&jf(new ef(new ArrayBuffer(1)))!=fe||nf&&jf(new nf)!=Zt||rf&&jf(rf.resolve())!=ee||of&&jf(new of)!=ie||af&&jf(new af)!=ue)&&(jf=function(t){var e=fr(t),n=e==te?t.constructor:it,r=n?ia(n):"";if(r)switch(r){case lf:return fe;case ff:return Zt;case pf:return ee;case df:return ie;case hf:return ue}return e});var Nf=yl?ou:zc,Df=ea(Cf),If=Hl||function(t,e){return sr.setTimeout(t,e)},Rf=ea(Tf),Lf=Xo(function(t){var e=[];return De.test(t)&&e.push(""),t.replace(Ie,function(t,n,r,i){e.push(r?i.replace(We,"$1"):n||t)}),e}),Pf=oi(function(t,e){return Zs(t)?Vn(t,er(e,1,Zs,!0)):[]; }),Ff=oi(function(t,e){var n=$a(e);return Zs(n)&&(n=it),Zs(t)?Vn(t,er(e,1,Zs,!0),$o(n,2)):[]}),qf=oi(function(t,e){var n=$a(e);return Zs(n)&&(n=it),Zs(t)?Vn(t,er(e,1,Zs,!0),it,n):[]}),Mf=oi(function(t){var e=v(t,Ti);return e.length&&e[0]===t[0]?kr(e):[]}),Hf=oi(function(t){var e=$a(t),n=v(t,Ti);return e===$a(n)?e=it:n.pop(),n.length&&n[0]===t[0]?kr(n,$o(e,2)):[]}),Bf=oi(function(t){var e=$a(t),n=v(t,Ti);return e="function"==typeof e?e:it,e&&n.pop(),n.length&&n[0]===t[0]?kr(n,it,e):[]}),Uf=oi(Ea),Wf=_o(function(t,e){var n=null==t?0:t.length,r=Fn(t,e);return ei(t,v(e,function(t){return Fo(t,n)?+t:t}).sort(Li)),r}),zf=oi(function(t){return mi(er(t,1,Zs,!0))}),Vf=oi(function(t){var e=$a(t);return Zs(e)&&(e=it),mi(er(t,1,Zs,!0),$o(e,2))}),Xf=oi(function(t){var e=$a(t);return e="function"==typeof e?e:it,mi(er(t,1,Zs,!0),it,e)}),Kf=oi(function(t,e){return Zs(t)?Vn(t,e):[]}),Jf=oi(function(t){return xi(p(t,Zs))}),Gf=oi(function(t){var e=$a(t);return Zs(e)&&(e=it),xi(p(t,Zs),$o(e,2))}),Zf=oi(function(t){var e=$a(t);return e="function"==typeof e?e:it,xi(p(t,Zs),it,e)}),Yf=oi(Ga),Qf=oi(function(t){var e=t.length,n=e>1?t[e-1]:it;return n="function"==typeof n?(t.pop(),n):it,Za(t,n)}),tp=_o(function(t){var e=t.length,n=e?t[0]:0,r=this.__wrapped__,o=function(e){return Fn(e,t)};return!(e>1||this.__actions__.length)&&r instanceof _&&Fo(n)?(r=r.slice(n,+n+(e?1:0)),r.__actions__.push({func:ns,args:[o],thisArg:it}),new i(r,this.__chain__).thru(function(t){return e&&!t.length&&t.push(it),t})):this.thru(o)}),ep=Wi(function(t,e,n){_l.call(t,n)?++t[n]:Pn(t,n,1)}),np=Qi(va),rp=Qi(ga),ip=Wi(function(t,e,n){_l.call(t,n)?t[n].push(e):Pn(t,n,[e])}),op=oi(function(t,e,n){var r=-1,i="function"==typeof e,o=Gs(t)?al(t.length):[];return bf(t,function(t){o[++r]=i?s(e,t,n):Er(t,e,n)}),o}),ap=Wi(function(t,e,n){Pn(t,n,e)}),sp=Wi(function(t,e,n){t[n?0:1].push(e)},function(){return[[],[]]}),up=oi(function(t,e){if(null==t)return[];var n=e.length;return n>1&&qo(t,e[0],e[1])?e=[]:n>2&&qo(e[0],e[1],e[2])&&(e=[e[0]]),Gr(t,er(e,1),[])}),cp=Ml||function(){return sr.Date.now()},lp=oi(function(t,e,n){var r=mt;if(n.length){var i=K(n,To(lp));r|=xt}return po(t,r,e,n,i)}),fp=oi(function(t,e,n){var r=mt|yt;if(n.length){var i=K(n,To(fp));r|=xt}return po(e,r,t,n,i)}),pp=oi(function(t,e){return zn(t,1,e)}),dp=oi(function(t,e,n){return zn(t,Eu(e)||0,n)});Rs.Cache=pn;var hp=$f(function(t,e){e=1==e.length&&wp(e[0])?v(e[0],R($o())):v(er(e,1),R($o()));var n=e.length;return oi(function(r){for(var i=-1,o=Gl(r.length,n);++i<o;)r[i]=e[i].call(this,r[i]);return s(t,this,r)})}),vp=oi(function(t,e){var n=K(e,To(vp));return po(t,xt,it,e,n)}),gp=oi(function(t,e){var n=K(e,To(gp));return po(t,Ct,it,e,n)}),mp=_o(function(t,e){return po(t,$t,it,it,it,e)}),yp=uo(pr),bp=uo(function(t,e){return t>=e}),_p=Sr(function(){return arguments}())?Sr:function(t){return cu(t)&&_l.call(t,"callee")&&!Dl.call(t,"callee")},wp=al.isArray,xp=dr?R(dr):Or,Cp=zl||zc,Tp=hr?R(hr):jr,$p=vr?R(vr):Ir,kp=gr?R(gr):Pr,Ap=mr?R(mr):Fr,Ep=yr?R(yr):qr,Sp=uo(Ur),Op=uo(function(t,e){return t<=e}),jp=zi(function(t,e){if(Wo(e)||Gs(e))return void Hi(e,Wu(e),t);for(var n in e)_l.call(e,n)&&Nn(t,n,e[n])}),Np=zi(function(t,e){Hi(e,zu(e),t)}),Dp=zi(function(t,e,n,r){Hi(e,zu(e),t,r)}),Ip=zi(function(t,e,n,r){Hi(e,Wu(e),t,r)}),Rp=_o(Fn),Lp=oi(function(t){return t.push(it,ho),s(Dp,it,t)}),Pp=oi(function(t){return t.push(it,vo),s(Bp,it,t)}),Fp=no(function(t,e,n){t[e]=n},Nc(Ic)),qp=no(function(t,e,n){_l.call(t,e)?t[e].push(n):t[e]=[n]},$o),Mp=oi(Er),Hp=zi(function(t,e,n){Xr(t,e,n)}),Bp=zi(function(t,e,n,r){Xr(t,e,n,r)}),Up=_o(function(t,e){var n={};if(null==t)return n;var r=!1;e=v(e,function(e){return e=ki(e,t),r||(r=e.length>1),e}),Hi(t,xo(t),n),r&&(n=Mn(n,pt|dt|ht,go));for(var i=e.length;i--;)yi(n,e[i]);return n}),Wp=_o(function(t,e){return null==t?{}:Zr(t,e)}),zp=fo(Wu),Vp=fo(zu),Xp=Gi(function(t,e,n){return e=e.toLowerCase(),t+(n?uc(e):e)}),Kp=Gi(function(t,e,n){return t+(n?"-":"")+e.toLowerCase()}),Jp=Gi(function(t,e,n){return t+(n?" ":"")+e.toLowerCase()}),Gp=Ji("toLowerCase"),Zp=Gi(function(t,e,n){return t+(n?"_":"")+e.toLowerCase()}),Yp=Gi(function(t,e,n){return t+(n?" ":"")+td(e)}),Qp=Gi(function(t,e,n){return t+(n?" ":"")+e.toUpperCase()}),td=Ji("toUpperCase"),ed=oi(function(t,e){try{return s(t,it,e)}catch(t){return ru(t)?t:new ul(t)}}),nd=_o(function(t,e){return c(e,function(e){e=ra(e),Pn(t,e,lp(t[e],t))}),t}),rd=to(),id=to(!0),od=oi(function(t,e){return function(n){return Er(n,t,e)}}),ad=oi(function(t,e){return function(n){return Er(t,n,e)}}),sd=io(v),ud=io(f),cd=io(b),ld=so(),fd=so(!0),pd=ro(function(t,e){return t+e},0),dd=lo("ceil"),hd=ro(function(t,e){return t/e},1),vd=lo("floor"),gd=ro(function(t,e){return t*e},1),md=lo("round"),yd=ro(function(t,e){return t-e},0);return n.after=Es,n.ary=Ss,n.assign=jp,n.assignIn=Np,n.assignInWith=Dp,n.assignWith=Ip,n.at=Rp,n.before=Os,n.bind=lp,n.bindAll=nd,n.bindKey=fp,n.castArray=Us,n.chain=ts,n.chunk=sa,n.compact=ua,n.concat=ca,n.cond=Oc,n.conforms=jc,n.constant=Nc,n.countBy=ep,n.create=Nu,n.curry=js,n.curryRight=Ns,n.debounce=Ds,n.defaults=Lp,n.defaultsDeep=Pp,n.defer=pp,n.delay=dp,n.difference=Pf,n.differenceBy=Ff,n.differenceWith=qf,n.drop=la,n.dropRight=fa,n.dropRightWhile=pa,n.dropWhile=da,n.fill=ha,n.filter=fs,n.flatMap=ps,n.flatMapDeep=ds,n.flatMapDepth=hs,n.flatten=ma,n.flattenDeep=ya,n.flattenDepth=ba,n.flip=Is,n.flow=rd,n.flowRight=id,n.fromPairs=_a,n.functions=qu,n.functionsIn=Mu,n.groupBy=ip,n.initial=Ca,n.intersection=Mf,n.intersectionBy=Hf,n.intersectionWith=Bf,n.invert=Fp,n.invertBy=qp,n.invokeMap=op,n.iteratee=Rc,n.keyBy=ap,n.keys=Wu,n.keysIn=zu,n.map=ys,n.mapKeys=Vu,n.mapValues=Xu,n.matches=Lc,n.matchesProperty=Pc,n.memoize=Rs,n.merge=Hp,n.mergeWith=Bp,n.method=od,n.methodOf=ad,n.mixin=Fc,n.negate=Ls,n.nthArg=Hc,n.omit=Up,n.omitBy=Ku,n.once=Ps,n.orderBy=bs,n.over=sd,n.overArgs=hp,n.overEvery=ud,n.overSome=cd,n.partial=vp,n.partialRight=gp,n.partition=sp,n.pick=Wp,n.pickBy=Ju,n.property=Bc,n.propertyOf=Uc,n.pull=Uf,n.pullAll=Ea,n.pullAllBy=Sa,n.pullAllWith=Oa,n.pullAt=Wf,n.range=ld,n.rangeRight=fd,n.rearg=mp,n.reject=xs,n.remove=ja,n.rest=Fs,n.reverse=Na,n.sampleSize=Ts,n.set=Zu,n.setWith=Yu,n.shuffle=$s,n.slice=Da,n.sortBy=up,n.sortedUniq=Ma,n.sortedUniqBy=Ha,n.split=bc,n.spread=qs,n.tail=Ba,n.take=Ua,n.takeRight=Wa,n.takeRightWhile=za,n.takeWhile=Va,n.tap=es,n.throttle=Ms,n.thru=ns,n.toArray=Tu,n.toPairs=zp,n.toPairsIn=Vp,n.toPath=Gc,n.toPlainObject=Su,n.transform=Qu,n.unary=Hs,n.union=zf,n.unionBy=Vf,n.unionWith=Xf,n.uniq=Xa,n.uniqBy=Ka,n.uniqWith=Ja,n.unset=tc,n.unzip=Ga,n.unzipWith=Za,n.update=ec,n.updateWith=nc,n.values=rc,n.valuesIn=ic,n.without=Kf,n.words=Sc,n.wrap=Bs,n.xor=Jf,n.xorBy=Gf,n.xorWith=Zf,n.zip=Yf,n.zipObject=Ya,n.zipObjectDeep=Qa,n.zipWith=Qf,n.entries=zp,n.entriesIn=Vp,n.extend=Np,n.extendWith=Dp,Fc(n,n),n.add=pd,n.attempt=ed,n.camelCase=Xp,n.capitalize=uc,n.ceil=dd,n.clamp=oc,n.clone=Ws,n.cloneDeep=Vs,n.cloneDeepWith=Xs,n.cloneWith=zs,n.conformsTo=Ks,n.deburr=cc,n.defaultTo=Dc,n.divide=hd,n.endsWith=lc,n.eq=Js,n.escape=fc,n.escapeRegExp=pc,n.every=ls,n.find=np,n.findIndex=va,n.findKey=Du,n.findLast=rp,n.findLastIndex=ga,n.findLastKey=Iu,n.floor=vd,n.forEach=vs,n.forEachRight=gs,n.forIn=Ru,n.forInRight=Lu,n.forOwn=Pu,n.forOwnRight=Fu,n.get=Hu,n.gt=yp,n.gte=bp,n.has=Bu,n.hasIn=Uu,n.head=wa,n.identity=Ic,n.includes=ms,n.indexOf=xa,n.inRange=ac,n.invoke=Mp,n.isArguments=_p,n.isArray=wp,n.isArrayBuffer=xp,n.isArrayLike=Gs,n.isArrayLikeObject=Zs,n.isBoolean=Ys,n.isBuffer=Cp,n.isDate=Tp,n.isElement=Qs,n.isEmpty=tu,n.isEqual=eu,n.isEqualWith=nu,n.isError=ru,n.isFinite=iu,n.isFunction=ou,n.isInteger=au,n.isLength=su,n.isMap=$p,n.isMatch=lu,n.isMatchWith=fu,n.isNaN=pu,n.isNative=du,n.isNil=vu,n.isNull=hu,n.isNumber=gu,n.isObject=uu,n.isObjectLike=cu,n.isPlainObject=mu,n.isRegExp=kp,n.isSafeInteger=yu,n.isSet=Ap,n.isString=bu,n.isSymbol=_u,n.isTypedArray=Ep,n.isUndefined=wu,n.isWeakMap=xu,n.isWeakSet=Cu,n.join=Ta,n.kebabCase=Kp,n.last=$a,n.lastIndexOf=ka,n.lowerCase=Jp,n.lowerFirst=Gp,n.lt=Sp,n.lte=Op,n.max=Yc,n.maxBy=Qc,n.mean=tl,n.meanBy=el,n.min=nl,n.minBy=rl,n.stubArray=Wc,n.stubFalse=zc,n.stubObject=Vc,n.stubString=Xc,n.stubTrue=Kc,n.multiply=gd,n.nth=Aa,n.noConflict=qc,n.noop=Mc,n.now=cp,n.pad=dc,n.padEnd=hc,n.padStart=vc,n.parseInt=gc,n.random=sc,n.reduce=_s,n.reduceRight=ws,n.repeat=mc,n.replace=yc,n.result=Gu,n.round=md,n.runInContext=t,n.sample=Cs,n.size=ks,n.snakeCase=Zp,n.some=As,n.sortedIndex=Ia,n.sortedIndexBy=Ra,n.sortedIndexOf=La,n.sortedLastIndex=Pa,n.sortedLastIndexBy=Fa,n.sortedLastIndexOf=qa,n.startCase=Yp,n.startsWith=_c,n.subtract=yd,n.sum=il,n.sumBy=ol,n.template=wc,n.times=Jc,n.toFinite=$u,n.toInteger=ku,n.toLength=Au,n.toLower=xc,n.toNumber=Eu,n.toSafeInteger=Ou,n.toString=ju,n.toUpper=Cc,n.trim=Tc,n.trimEnd=$c,n.trimStart=kc,n.truncate=Ac,n.unescape=Ec,n.uniqueId=Zc,n.upperCase=Qp,n.upperFirst=td,n.each=vs,n.eachRight=gs,n.first=wa,Fc(n,function(){var t={};return nr(n,function(e,r){_l.call(n.prototype,r)||(t[r]=e)}),t}(),{chain:!1}),n.VERSION=ot,c(["bind","bindKey","curry","curryRight","partial","partialRight"],function(t){n[t].placeholder=n}),c(["drop","take"],function(t,e){_.prototype[t]=function(n){n=n===it?1:Jl(ku(n),0);var r=this.__filtered__&&!e?new _(this):this.clone();return r.__filtered__?r.__takeCount__=Gl(n,r.__takeCount__):r.__views__.push({size:Gl(n,Ft),type:t+(r.__dir__<0?"Right":"")}),r},_.prototype[t+"Right"]=function(e){return this.reverse()[t](e).reverse()}}),c(["filter","map","takeWhile"],function(t,e){var n=e+1,r=n==jt||n==Dt;_.prototype[t]=function(t){var e=this.clone();return e.__iteratees__.push({iteratee:$o(t,3),type:n}),e.__filtered__=e.__filtered__||r,e}}),c(["head","last"],function(t,e){var n="take"+(e?"Right":"");_.prototype[t]=function(){return this[n](1).value()[0]}}),c(["initial","tail"],function(t,e){var n="drop"+(e?"":"Right");_.prototype[t]=function(){return this.__filtered__?new _(this):this[n](1)}}),_.prototype.compact=function(){return this.filter(Ic)},_.prototype.find=function(t){return this.filter(t).head()},_.prototype.findLast=function(t){return this.reverse().find(t)},_.prototype.invokeMap=oi(function(t,e){return"function"==typeof t?new _(this):this.map(function(n){return Er(n,t,e)})}),_.prototype.reject=function(t){return this.filter(Ls($o(t)))},_.prototype.slice=function(t,e){t=ku(t);var n=this;return n.__filtered__&&(t>0||e<0)?new _(n):(t<0?n=n.takeRight(-t):t&&(n=n.drop(t)),e!==it&&(e=ku(e),n=e<0?n.dropRight(-e):n.take(e-t)),n)},_.prototype.takeRightWhile=function(t){return this.reverse().takeWhile(t).reverse()},_.prototype.toArray=function(){return this.take(Ft)},nr(_.prototype,function(t,e){var r=/^(?:filter|find|map|reject)|While$/.test(e),o=/^(?:head|last)$/.test(e),a=n[o?"take"+("last"==e?"Right":""):e],s=o||/^find/.test(e);a&&(n.prototype[e]=function(){var e=this.__wrapped__,u=o?[1]:arguments,c=e instanceof _,l=u[0],f=c||wp(e),p=function(t){var e=a.apply(n,g([t],u));return o&&d?e[0]:e};f&&r&&"function"==typeof l&&1!=l.length&&(c=f=!1);var d=this.__chain__,h=!!this.__actions__.length,v=s&&!d,m=c&&!h;if(!s&&f){e=m?e:new _(this);var y=t.apply(e,u);return y.__actions__.push({func:ns,args:[p],thisArg:it}),new i(y,d)}return v&&m?t.apply(this,u):(y=this.thru(p),v?o?y.value()[0]:y.value():y)})}),c(["pop","push","shift","sort","splice","unshift"],function(t){var e=vl[t],r=/^(?:push|sort|unshift)$/.test(t)?"tap":"thru",i=/^(?:pop|shift)$/.test(t);n.prototype[t]=function(){var t=arguments;if(i&&!this.__chain__){var n=this.value();return e.apply(wp(n)?n:[],t)}return this[r](function(n){return e.apply(wp(n)?n:[],t)})}}),nr(_.prototype,function(t,e){var r=n[e];if(r){var i=r.name+"",o=cf[i]||(cf[i]=[]);o.push({name:e,func:r})}}),cf[eo(it,yt).name]=[{name:"wrapper",func:it}],_.prototype.clone=S,_.prototype.reverse=Z,_.prototype.value=et,n.prototype.at=tp,n.prototype.chain=rs,n.prototype.commit=is,n.prototype.next=os,n.prototype.plant=ss,n.prototype.reverse=us,n.prototype.toJSON=n.prototype.valueOf=n.prototype.value=cs,n.prototype.first=n.prototype.head,Ll&&(n.prototype[Ll]=as),n},Tr=Cr();sr._=Tr,i=function(){return Tr}.call(e,n,e,r),!(i!==it&&(r.exports=i))}).call(this)}).call(e,n(8),n(37)(t))},function(t,e){function n(){throw new Error("setTimeout has not been defined")}function r(){throw new Error("clearTimeout has not been defined")}function i(t){if(l===setTimeout)return setTimeout(t,0);if((l===n||!l)&&setTimeout)return l=setTimeout,setTimeout(t,0);try{return l(t,0)}catch(e){try{return l.call(null,t,0)}catch(e){return l.call(this,t,0)}}}function o(t){if(f===clearTimeout)return clearTimeout(t);if((f===r||!f)&&clearTimeout)return f=clearTimeout,clearTimeout(t);try{return f(t)}catch(e){try{return f.call(null,t)}catch(e){return f.call(this,t)}}}function a(){v&&d&&(v=!1,d.length?h=d.concat(h):g=-1,h.length&&s())}function s(){if(!v){var t=i(a);v=!0;for(var e=h.length;e;){for(d=h,h=[];++g<e;)d&&d[g].run();g=-1,e=h.length}d=null,v=!1,o(t)}}function u(t,e){this.fun=t,this.array=e}function c(){}var l,f,p=t.exports={};!function(){try{l="function"==typeof setTimeout?setTimeout:n}catch(t){l=n}try{f="function"==typeof clearTimeout?clearTimeout:r}catch(t){f=r}}();var d,h=[],v=!1,g=-1;p.nextTick=function(t){var e=new Array(arguments.length-1);if(arguments.length>1)for(var n=1;n<arguments.length;n++)e[n-1]=arguments[n];h.push(new u(t,e)),1!==h.length||v||i(s)},u.prototype.run=function(){this.fun.apply(null,this.array)},p.title="browser",p.browser=!0,p.env={},p.argv=[],p.version="",p.versions={},p.on=c,p.addListener=c,p.once=c,p.off=c,p.removeListener=c,p.removeAllListeners=c,p.emit=c,p.binding=function(t){throw new Error("process.binding is not supported")},p.cwd=function(){return"/"},p.chdir=function(t){throw new Error("process.chdir is not supported")},p.umask=function(){return 0}},function(t,e,n){var r,i;r=n(29);var o=n(35);i=r=r||{},"object"!=typeof r.default&&"function"!=typeof r.default||(i=r=r.default),"function"==typeof i&&(i=i.options),i.render=o.render,i.staticRenderFns=o.staticRenderFns,t.exports=r},function(t,e){t.exports={render:function(){var t=this,e=t.$createElement;t._self._c||e;return t._m(0)},staticRenderFns:[function(){var t=this,e=t.$createElement,n=t._self._c||e;return n("div",{staticClass:"container"},[n("div",{staticClass:"row"},[n("div",{staticClass:"col-md-8 col-md-offset-2"},[n("div",{staticClass:"panel panel-default"},[n("div",{staticClass:"panel-heading"},[t._v("Example Component")]),t._v(" "),n("div",{staticClass:"panel-body"},[t._v("\n I'm an example component!\n ")])])])])])}]}},function(t,e,n){"use strict";(function(e){/*! * Vue.js v2.1.10 * (c) 2014-2017 Evan You * Released under the MIT License. */ function n(t){return null==t?"":"object"==typeof t?JSON.stringify(t,null,2):String(t)}function r(t){var e=parseFloat(t);return isNaN(e)?t:e}function i(t,e){for(var n=Object.create(null),r=t.split(","),i=0;i<r.length;i++)n[r[i]]=!0;return e?function(t){return n[t.toLowerCase()]}:function(t){return n[t]}}function o(t,e){if(t.length){var n=t.indexOf(e);if(n>-1)return t.splice(n,1)}}function a(t,e){return ai.call(t,e)}function s(t){return"string"==typeof t||"number"==typeof t}function u(t){var e=Object.create(null);return function(n){var r=e[n];return r||(e[n]=t(n))}}function c(t,e){function n(n){var r=arguments.length;return r?r>1?t.apply(e,arguments):t.call(e,n):t.call(e)}return n._length=t.length,n}function l(t,e){e=e||0;for(var n=t.length-e,r=new Array(n);n--;)r[n]=t[n+e];return r}function f(t,e){for(var n in e)t[n]=e[n];return t}function p(t){return null!==t&&"object"==typeof t}function d(t){return pi.call(t)===di}function h(t){for(var e={},n=0;n<t.length;n++)t[n]&&f(e,t[n]);return e}function v(){}function g(t){return t.reduce(function(t,e){return t.concat(e.staticKeys||[])},[]).join(",")}function m(t,e){var n=p(t),r=p(e);return n&&r?JSON.stringify(t)===JSON.stringify(e):!n&&!r&&String(t)===String(e)}function y(t,e){for(var n=0;n<t.length;n++)if(m(t[n],e))return n;return-1}function b(t){var e=(t+"").charCodeAt(0);return 36===e||95===e}function _(t,e,n,r){Object.defineProperty(t,e,{value:n,enumerable:!!r,writable:!0,configurable:!0})}function w(t){if(!mi.test(t)){var e=t.split(".");return function(t){for(var n=0;n<e.length;n++){if(!t)return;t=t[e[n]]}return t}}}function x(t){return/native code/.test(t.toString())}function C(t){Ni.target&&Di.push(Ni.target),Ni.target=t}function T(){Ni.target=Di.pop()}function $(t,e){t.__proto__=e}function k(t,e,n){for(var r=0,i=n.length;r<i;r++){var o=n[r];_(t,o,e[o])}}function A(t,e){if(p(t)){var n;return a(t,"__ob__")&&t.__ob__ instanceof Fi?n=t.__ob__:Pi.shouldConvert&&!ki()&&(Array.isArray(t)||d(t))&&Object.isExtensible(t)&&!t._isVue&&(n=new Fi(t)),e&&n&&n.vmCount++,n}}function E(t,e,n,r){var i=new Ni,o=Object.getOwnPropertyDescriptor(t,e);if(!o||o.configurable!==!1){var a=o&&o.get,s=o&&o.set,u=A(n);Object.defineProperty(t,e,{enumerable:!0,configurable:!0,get:function(){var e=a?a.call(t):n;return Ni.target&&(i.depend(),u&&u.dep.depend(),Array.isArray(e)&&j(e)),e},set:function(e){var r=a?a.call(t):n;e===r||e!==e&&r!==r||(s?s.call(t,e):n=e,u=A(e),i.notify())}})}}function S(t,e,n){if(Array.isArray(t))return t.length=Math.max(t.length,e),t.splice(e,1,n),n;if(a(t,e))return void(t[e]=n);var r=t.__ob__;if(!(t._isVue||r&&r.vmCount))return r?(E(r.value,e,n),r.dep.notify(),n):void(t[e]=n)}function O(t,e){var n=t.__ob__;t._isVue||n&&n.vmCount||a(t,e)&&(delete t[e],n&&n.dep.notify())}function j(t){for(var e=void 0,n=0,r=t.length;n<r;n++)e=t[n],e&&e.__ob__&&e.__ob__.dep.depend(),Array.isArray(e)&&j(e)}function N(t,e){if(!e)return t;for(var n,r,i,o=Object.keys(e),s=0;s<o.length;s++)n=o[s],r=t[n],i=e[n],a(t,n)?d(r)&&d(i)&&N(r,i):S(t,n,i);return t}function D(t,e){return e?t?t.concat(e):Array.isArray(e)?e:[e]:t}function I(t,e){var n=Object.create(t||null);return e?f(n,e):n}function R(t){var e=t.props;if(e){var n,r,i,o={};if(Array.isArray(e))for(n=e.length;n--;)r=e[n],"string"==typeof r&&(i=ui(r),o[i]={type:null});else if(d(e))for(var a in e)r=e[a],i=ui(a),o[i]=d(r)?r:{type:r};t.props=o}}function L(t){var e=t.directives;if(e)for(var n in e){var r=e[n];"function"==typeof r&&(e[n]={bind:r,update:r})}}function P(t,e,n){function r(r){var i=qi[r]||Mi;l[r]=i(t[r],e[r],n,r)}R(e),L(e);var i=e.extends;if(i&&(t="function"==typeof i?P(t,i.options,n):P(t,i,n)),e.mixins)for(var o=0,s=e.mixins.length;o<s;o++){var u=e.mixins[o];u.prototype instanceof Ut&&(u=u.options),t=P(t,u,n)}var c,l={};for(c in t)r(c);for(c in e)a(t,c)||r(c);return l}function F(t,e,n,r){if("string"==typeof n){var i=t[e];if(a(i,n))return i[n];var o=ui(n);if(a(i,o))return i[o];var s=ci(o);if(a(i,s))return i[s];var u=i[n]||i[o]||i[s];return u}}function q(t,e,n,r){var i=e[t],o=!a(n,t),s=n[t];if(B(Boolean,i.type)&&(o&&!a(i,"default")?s=!1:B(String,i.type)||""!==s&&s!==fi(t)||(s=!0)),void 0===s){s=M(r,i,t);var u=Pi.shouldConvert;Pi.shouldConvert=!0,A(s),Pi.shouldConvert=u}return s}function M(t,e,n){if(a(e,"default")){var r=e.default;return p(r),t&&t.$options.propsData&&void 0===t.$options.propsData[n]&&void 0!==t[n]?t[n]:"function"==typeof r&&e.type!==Function?r.call(t):r}}function H(t){var e=t&&t.toString().match(/^\s*function (\w+)/);return e&&e[1]}function B(t,e){if(!Array.isArray(e))return H(e)===H(t);for(var n=0,r=e.length;n<r;n++)if(H(e[n])===H(t))return!0;return!1}function U(t){return new Bi(void 0,void 0,void 0,String(t))}function W(t){var e=new Bi(t.tag,t.data,t.children,t.text,t.elm,t.context,t.componentOptions);return e.ns=t.ns,e.isStatic=t.isStatic,e.key=t.key,e.isCloned=!0,e}function z(t){for(var e=new Array(t.length),n=0;n<t.length;n++)e[n]=W(t[n]);return e}function V(t,e,n,r,i){if(t){var o=n.$options._base;if(p(t)&&(t=o.extend(t)),"function"==typeof t){if(!t.cid)if(t.resolved)t=t.resolved;else if(t=Q(t,o,function(){n.$forceUpdate()}),!t)return;Bt(t),e=e||{};var a=tt(e,t);if(t.options.functional)return X(t,a,e,n,r);var s=e.on;e.on=e.nativeOn,t.options.abstract&&(e={}),nt(e);var u=t.options.name||i,c=new Bi("vue-component-"+t.cid+(u?"-"+u:""),e,void 0,void 0,void 0,n,{Ctor:t,propsData:a,listeners:s,tag:i,children:r});return c}}}function X(t,e,n,r,i){var o={},a=t.options.props;if(a)for(var s in a)o[s]=q(s,a,e);var u=Object.create(r),c=function(t,e,n,r){return ft(u,t,e,n,r,!0)},l=t.options.render.call(null,c,{props:o,data:n,parent:r,children:i,slots:function(){return gt(i,r)}});return l instanceof Bi&&(l.functionalContext=r,n.slot&&((l.data||(l.data={})).slot=n.slot)),l}function K(t,e,n,r){var i=t.componentOptions,o={_isComponent:!0,parent:e,propsData:i.propsData,_componentTag:i.tag,_parentVnode:t,_parentListeners:i.listeners,_renderChildren:i.children,_parentElm:n||null,_refElm:r||null},a=t.data.inlineTemplate;return a&&(o.render=a.render,o.staticRenderFns=a.staticRenderFns),new i.Ctor(o)}function J(t,e,n,r){if(!t.componentInstance||t.componentInstance._isDestroyed){var i=t.componentInstance=K(t,Zi,n,r);i.$mount(e?t.elm:void 0,e)}else if(t.data.keepAlive){var o=t;G(o,o)}}function G(t,e){var n=e.componentOptions,r=e.componentInstance=t.componentInstance;r._updateFromParent(n.propsData,n.listeners,e,n.children)}function Z(t){t.componentInstance._isMounted||(t.componentInstance._isMounted=!0,Tt(t.componentInstance,"mounted")),t.data.keepAlive&&(t.componentInstance._inactive=!1,Tt(t.componentInstance,"activated"))}function Y(t){t.componentInstance._isDestroyed||(t.data.keepAlive?(t.componentInstance._inactive=!0,Tt(t.componentInstance,"deactivated")):t.componentInstance.$destroy())}function Q(t,e,n){if(!t.requested){t.requested=!0;var r=t.pendingCallbacks=[n],i=!0,o=function(n){if(p(n)&&(n=e.extend(n)),t.resolved=n,!i)for(var o=0,a=r.length;o<a;o++)r[o](n)},a=function(t){},s=t(o,a);return s&&"function"==typeof s.then&&!t.resolved&&s.then(o,a),i=!1,t.resolved}t.pendingCallbacks.push(n)}function tt(t,e){var n=e.options.props;if(n){var r={},i=t.attrs,o=t.props,a=t.domProps;if(i||o||a)for(var s in n){var u=fi(s);et(r,o,s,u,!0)||et(r,i,s,u)||et(r,a,s,u)}return r}}function et(t,e,n,r,i){if(e){if(a(e,n))return t[n]=e[n],i||delete e[n],!0;if(a(e,r))return t[n]=e[r],i||delete e[r],!0}return!1}function nt(t){t.hook||(t.hook={});for(var e=0;e<Xi.length;e++){var n=Xi[e],r=t.hook[n],i=Vi[n];t.hook[n]=r?rt(i,r):i}}function rt(t,e){return function(n,r,i,o){t(n,r,i,o),e(n,r,i,o)}}function it(t,e,n,r){r+=e;var i=t.__injected||(t.__injected={});if(!i[r]){i[r]=!0;var o=t[e];o?t[e]=function(){o.apply(this,arguments),n.apply(this,arguments)}:t[e]=n}}function ot(t){var e={fn:t,invoker:function(){var t=arguments,n=e.fn;if(Array.isArray(n))for(var r=0;r<n.length;r++)n[r].apply(null,t);else n.apply(null,arguments)}};return e}function at(t,e,n,r,i){var o,a,s,u;for(o in t)a=t[o],s=e[o],u=Ki(o),a&&(s?a!==s&&(s.fn=a,t[o]=s):(a.invoker||(a=t[o]=ot(a)),n(u.name,a.invoker,u.once,u.capture)));for(o in e)t[o]||(u=Ki(o),r(u.name,e[o].invoker,u.capture))}function st(t){for(var e=0;e<t.length;e++)if(Array.isArray(t[e]))return Array.prototype.concat.apply([],t);return t}function ut(t){return s(t)?[U(t)]:Array.isArray(t)?ct(t):void 0}function ct(t,e){var n,r,i,o=[];for(n=0;n<t.length;n++)r=t[n],null!=r&&"boolean"!=typeof r&&(i=o[o.length-1],Array.isArray(r)?o.push.apply(o,ct(r,(e||"")+"_"+n)):s(r)?i&&i.text?i.text+=String(r):""!==r&&o.push(U(r)):r.text&&i&&i.text?o[o.length-1]=U(i.text+r.text):(r.tag&&null==r.key&&null!=e&&(r.key="__vlist"+e+"_"+n+"__"),o.push(r)));return o}function lt(t){return t&&t.filter(function(t){return t&&t.componentOptions})[0]}function ft(t,e,n,r,i,o){return(Array.isArray(n)||s(n))&&(i=r,r=n,n=void 0),o&&(i=Gi),pt(t,e,n,r,i)}function pt(t,e,n,r,i){if(n&&n.__ob__)return zi();if(!e)return zi();Array.isArray(r)&&"function"==typeof r[0]&&(n=n||{},n.scopedSlots={default:r[0]},r.length=0),i===Gi?r=ut(r):i===Ji&&(r=st(r));var o,a;if("string"==typeof e){var s;a=gi.getTagNamespace(e),o=gi.isReservedTag(e)?new Bi(gi.parsePlatformTagName(e),n,r,void 0,void 0,t):(s=F(t.$options,"components",e))?V(s,n,t,r,e):new Bi(e,n,r,void 0,void 0,t)}else o=V(e,n,t,r);return o?(a&&dt(o,a),o):zi()}function dt(t,e){if(t.ns=e,"foreignObject"!==t.tag&&t.children)for(var n=0,r=t.children.length;n<r;n++){var i=t.children[n];i.tag&&!i.ns&&dt(i,e)}}function ht(t){t.$vnode=null,t._vnode=null,t._staticTrees=null;var e=t.$options._parentVnode,n=e&&e.context;t.$slots=gt(t.$options._renderChildren,n),t.$scopedSlots={},t._c=function(e,n,r,i){return ft(t,e,n,r,i,!1)},t.$createElement=function(e,n,r,i){return ft(t,e,n,r,i,!0)}}function vt(t){function e(t,e,n){if(Array.isArray(t))for(var r=0;r<t.length;r++)t[r]&&"string"!=typeof t[r]&&i(t[r],e+"_"+r,n);else i(t,e,n)}function i(t,e,n){t.isStatic=!0,t.key=e,t.isOnce=n}t.prototype.$nextTick=function(t){return Ei(t,this)},t.prototype._render=function(){var t=this,e=t.$options,n=e.render,r=e.staticRenderFns,i=e._parentVnode;if(t._isMounted)for(var o in t.$slots)t.$slots[o]=z(t.$slots[o]);i&&i.data.scopedSlots&&(t.$scopedSlots=i.data.scopedSlots),r&&!t._staticTrees&&(t._staticTrees=[]),t.$vnode=i;var a;try{a=n.call(t._renderProxy,t.$createElement)}catch(e){if(!gi.errorHandler)throw e;gi.errorHandler.call(null,e,t),a=t._vnode}return a instanceof Bi||(a=zi()),a.parent=i,a},t.prototype._s=n,t.prototype._v=U,t.prototype._n=r,t.prototype._e=zi,t.prototype._q=m,t.prototype._i=y,t.prototype._m=function(t,n){var r=this._staticTrees[t];return r&&!n?Array.isArray(r)?z(r):W(r):(r=this._staticTrees[t]=this.$options.staticRenderFns[t].call(this._renderProxy),e(r,"__static__"+t,!1),r)},t.prototype._o=function(t,n,r){return e(t,"__once__"+n+(r?"_"+r:""),!0),t},t.prototype._f=function(t){return F(this.$options,"filters",t,!0)||vi},t.prototype._l=function(t,e){var n,r,i,o,a;if(Array.isArray(t)||"string"==typeof t)for(n=new Array(t.length),r=0,i=t.length;r<i;r++)n[r]=e(t[r],r);else if("number"==typeof t)for(n=new Array(t),r=0;r<t;r++)n[r]=e(r+1,r);else if(p(t))for(o=Object.keys(t),n=new Array(o.length),r=0,i=o.length;r<i;r++)a=o[r],n[r]=e(t[a],a,r);return n},t.prototype._t=function(t,e,n,r){var i=this.$scopedSlots[t];if(i)return n=n||{},r&&f(n,r),i(n)||e;var o=this.$slots[t];return o||e},t.prototype._b=function(t,e,n,r){if(n)if(p(n)){Array.isArray(n)&&(n=h(n));for(var i in n)if("class"===i||"style"===i)t[i]=n[i];else{var o=t.attrs&&t.attrs.type,a=r||gi.mustUseProp(e,o,i)?t.domProps||(t.domProps={}):t.attrs||(t.attrs={});a[i]=n[i]}}else;return t},t.prototype._k=function(t,e,n){var r=gi.keyCodes[e]||n;return Array.isArray(r)?r.indexOf(t)===-1:r!==t}}function gt(t,e){var n={};if(!t)return n;for(var r,i,o=[],a=0,s=t.length;a<s;a++)if(i=t[a],(i.context===e||i.functionalContext===e)&&i.data&&(r=i.data.slot)){var u=n[r]||(n[r]=[]);"template"===i.tag?u.push.apply(u,i.children):u.push(i)}else o.push(i);return o.length&&(1!==o.length||" "!==o[0].text&&!o[0].isComment)&&(n.default=o),n}function mt(t){t._events=Object.create(null),t._hasHookEvent=!1;var e=t.$options._parentListeners;e&&_t(t,e)}function yt(t,e,n){n?Wi.$once(t,e):Wi.$on(t,e)}function bt(t,e){Wi.$off(t,e)}function _t(t,e,n){Wi=t,at(e,n||{},yt,bt,t)}function wt(t){var e=/^hook:/;t.prototype.$on=function(t,n){var r=this;return(r._events[t]||(r._events[t]=[])).push(n),e.test(t)&&(r._hasHookEvent=!0),r},t.prototype.$once=function(t,e){function n(){r.$off(t,n),e.apply(r,arguments)}var r=this;return n.fn=e,r.$on(t,n),r},t.prototype.$off=function(t,e){var n=this;if(!arguments.length)return n._events=Object.create(null),n;var r=n._events[t];if(!r)return n;if(1===arguments.length)return n._events[t]=null,n;for(var i,o=r.length;o--;)if(i=r[o],i===e||i.fn===e){r.splice(o,1);break}return n},t.prototype.$emit=function(t){var e=this,n=e._events[t];if(n){n=n.length>1?l(n):n;for(var r=l(arguments,1),i=0,o=n.length;i<o;i++)n[i].apply(e,r)}return e}}function xt(t){var e=t.$options,n=e.parent;if(n&&!e.abstract){for(;n.$options.abstract&&n.$parent;)n=n.$parent;n.$children.push(t)}t.$parent=n,t.$root=n?n.$root:t,t.$children=[],t.$refs={},t._watcher=null,t._inactive=!1,t._isMounted=!1,t._isDestroyed=!1,t._isBeingDestroyed=!1}function Ct(t){t.prototype._mount=function(t,e){var n=this;return n.$el=t,n.$options.render||(n.$options.render=zi),Tt(n,"beforeMount"),n._watcher=new io(n,function(){n._update(n._render(),e)},v),e=!1,null==n.$vnode&&(n._isMounted=!0,Tt(n,"mounted")),n},t.prototype._update=function(t,e){var n=this;n._isMounted&&Tt(n,"beforeUpdate");var r=n.$el,i=n._vnode,o=Zi;Zi=n,n._vnode=t,i?n.$el=n.__patch__(i,t):n.$el=n.__patch__(n.$el,t,e,!1,n.$options._parentElm,n.$options._refElm),Zi=o,r&&(r.__vue__=null),n.$el&&(n.$el.__vue__=n),n.$vnode&&n.$parent&&n.$vnode===n.$parent._vnode&&(n.$parent.$el=n.$el)},t.prototype._updateFromParent=function(t,e,n,r){var i=this,o=!(!i.$options._renderChildren&&!r);if(i.$options._parentVnode=n,i.$vnode=n,i._vnode&&(i._vnode.parent=n),i.$options._renderChildren=r,t&&i.$options.props){Pi.shouldConvert=!1;for(var a=i.$options._propKeys||[],s=0;s<a.length;s++){var u=a[s];i[u]=q(u,i.$options.props,t,i)}Pi.shouldConvert=!0,i.$options.propsData=t}if(e){var c=i.$options._parentListeners;i.$options._parentListeners=e,_t(i,e,c)}o&&(i.$slots=gt(r,n.context),i.$forceUpdate())},t.prototype.$forceUpdate=function(){var t=this;t._watcher&&t._watcher.update()},t.prototype.$destroy=function(){var t=this;if(!t._isBeingDestroyed){Tt(t,"beforeDestroy"),t._isBeingDestroyed=!0;var e=t.$parent;!e||e._isBeingDestroyed||t.$options.abstract||o(e.$children,t),t._watcher&&t._watcher.teardown();for(var n=t._watchers.length;n--;)t._watchers[n].teardown();t._data.__ob__&&t._data.__ob__.vmCount--,t._isDestroyed=!0,Tt(t,"destroyed"),t.$off(),t.$el&&(t.$el.__vue__=null),t.__patch__(t._vnode,null)}}}function Tt(t,e){var n=t.$options[e];if(n)for(var r=0,i=n.length;r<i;r++)n[r].call(t);t._hasHookEvent&&t.$emit("hook:"+e)}function $t(){Yi.length=0,Qi={},to=eo=!1}function kt(){eo=!0;var t,e,n;for(Yi.sort(function(t,e){return t.id-e.id}),no=0;no<Yi.length;no++)t=Yi[no],e=t.id,Qi[e]=null,t.run();for(no=Yi.length;no--;)t=Yi[no],n=t.vm,n._watcher===t&&n._isMounted&&Tt(n,"updated");Ai&&gi.devtools&&Ai.emit("flush"),$t()}function At(t){var e=t.id;if(null==Qi[e]){if(Qi[e]=!0,eo){for(var n=Yi.length-1;n>=0&&Yi[n].id>t.id;)n--;Yi.splice(Math.max(n,no)+1,0,t)}else Yi.push(t);to||(to=!0,Ei(kt))}}function Et(t){oo.clear(),St(t,oo)}function St(t,e){var n,r,i=Array.isArray(t);if((i||p(t))&&Object.isExtensible(t)){if(t.__ob__){var o=t.__ob__.dep.id;if(e.has(o))return;e.add(o)}if(i)for(n=t.length;n--;)St(t[n],e);else for(r=Object.keys(t),n=r.length;n--;)St(t[r[n]],e)}}function Ot(t){t._watchers=[];var e=t.$options;e.props&&jt(t,e.props),e.methods&&Rt(t,e.methods),e.data?Nt(t):A(t._data={},!0),e.computed&&Dt(t,e.computed),e.watch&&Lt(t,e.watch)}function jt(t,e){var n=t.$options.propsData||{},r=t.$options._propKeys=Object.keys(e),i=!t.$parent;Pi.shouldConvert=i;for(var o=function(i){var o=r[i];E(t,o,q(o,e,n,t))},a=0;a<r.length;a++)o(a);Pi.shouldConvert=!0}function Nt(t){var e=t.$options.data;e=t._data="function"==typeof e?e.call(t):e||{},d(e)||(e={});for(var n=Object.keys(e),r=t.$options.props,i=n.length;i--;)r&&a(r,n[i])||qt(t,n[i]);A(e,!0)}function Dt(t,e){for(var n in e){var r=e[n];"function"==typeof r?(ao.get=It(r,t),ao.set=v):(ao.get=r.get?r.cache!==!1?It(r.get,t):c(r.get,t):v,ao.set=r.set?c(r.set,t):v),Object.defineProperty(t,n,ao)}}function It(t,e){var n=new io(e,t,v,{lazy:!0});return function(){return n.dirty&&n.evaluate(),Ni.target&&n.depend(),n.value}}function Rt(t,e){for(var n in e)t[n]=null==e[n]?v:c(e[n],t)}function Lt(t,e){for(var n in e){var r=e[n];if(Array.isArray(r))for(var i=0;i<r.length;i++)Pt(t,n,r[i]);else Pt(t,n,r)}}function Pt(t,e,n){var r;d(n)&&(r=n,n=n.handler),"string"==typeof n&&(n=t[n]),t.$watch(e,n,r)}function Ft(t){var e={};e.get=function(){return this._data},Object.defineProperty(t.prototype,"$data",e),t.prototype.$set=S,t.prototype.$delete=O,t.prototype.$watch=function(t,e,n){var r=this;n=n||{},n.user=!0;var i=new io(r,t,e,n);return n.immediate&&e.call(r,i.value),function(){i.teardown()}}}function qt(t,e){b(e)||Object.defineProperty(t,e,{configurable:!0,enumerable:!0,get:function(){return t._data[e]},set:function(n){t._data[e]=n}})}function Mt(t){t.prototype._init=function(t){var e=this;e._uid=so++,e._isVue=!0,t&&t._isComponent?Ht(e,t):e.$options=P(Bt(e.constructor),t||{},e),e._renderProxy=e,e._self=e,xt(e),mt(e),ht(e),Tt(e,"beforeCreate"),Ot(e),Tt(e,"created"),e.$options.el&&e.$mount(e.$options.el)}}function Ht(t,e){var n=t.$options=Object.create(t.constructor.options);n.parent=e.parent,n.propsData=e.propsData,n._parentVnode=e._parentVnode,n._parentListeners=e._parentListeners,n._renderChildren=e._renderChildren,n._componentTag=e._componentTag,n._parentElm=e._parentElm,n._refElm=e._refElm,e.render&&(n.render=e.render,n.staticRenderFns=e.staticRenderFns)}function Bt(t){var e=t.options;if(t.super){var n=t.super.options,r=t.superOptions,i=t.extendOptions;n!==r&&(t.superOptions=n,i.render=e.render,i.staticRenderFns=e.staticRenderFns,i._scopeId=e._scopeId,e=t.options=P(n,i),e.name&&(e.components[e.name]=t))}return e}function Ut(t){this._init(t)}function Wt(t){t.use=function(t){if(!t.installed){var e=l(arguments,1);return e.unshift(this),"function"==typeof t.install?t.install.apply(t,e):t.apply(null,e),t.installed=!0,this}}}function zt(t){t.mixin=function(t){this.options=P(this.options,t)}}function Vt(t){t.cid=0;var e=1;t.extend=function(t){t=t||{};var n=this,r=n.cid,i=t._Ctor||(t._Ctor={});if(i[r])return i[r];var o=t.name||n.options.name,a=function(t){this._init(t)};return a.prototype=Object.create(n.prototype),a.prototype.constructor=a,a.cid=e++,a.options=P(n.options,t),a.super=n,a.extend=n.extend,a.mixin=n.mixin,a.use=n.use,gi._assetTypes.forEach(function(t){a[t]=n[t]}),o&&(a.options.components[o]=a),a.superOptions=n.options,a.extendOptions=t,i[r]=a,a}}function Xt(t){gi._assetTypes.forEach(function(e){t[e]=function(t,n){return n?("component"===e&&d(n)&&(n.name=n.name||t,n=this.options._base.extend(n)),"directive"===e&&"function"==typeof n&&(n={bind:n,update:n}),this.options[e+"s"][t]=n,n):this.options[e+"s"][t]}})}function Kt(t){return t&&(t.Ctor.options.name||t.tag)}function Jt(t,e){return"string"==typeof t?t.split(",").indexOf(e)>-1:t.test(e)}function Gt(t,e){for(var n in t){var r=t[n];if(r){var i=Kt(r.componentOptions);i&&!e(i)&&(Zt(r),t[n]=null)}}}function Zt(t){t&&(t.componentInstance._inactive||Tt(t.componentInstance,"deactivated"),t.componentInstance.$destroy())}function Yt(t){var e={};e.get=function(){return gi},Object.defineProperty(t,"config",e),t.util=Hi,t.set=S,t.delete=O,t.nextTick=Ei,t.options=Object.create(null),gi._assetTypes.forEach(function(e){t.options[e+"s"]=Object.create(null)}),t.options._base=t,f(t.options.components,lo),Wt(t),zt(t),Vt(t),Xt(t)}function Qt(t){for(var e=t.data,n=t,r=t;r.componentInstance;)r=r.componentInstance._vnode,r.data&&(e=te(r.data,e));for(;n=n.parent;)n.data&&(e=te(e,n.data));return ee(e)}function te(t,e){return{staticClass:ne(t.staticClass,e.staticClass),class:t.class?[t.class,e.class]:e.class}}function ee(t){var e=t.class,n=t.staticClass;return n||e?ne(n,re(e)):""}function ne(t,e){return t?e?t+" "+e:t:e||""}function re(t){var e="";if(!t)return e;if("string"==typeof t)return t;if(Array.isArray(t)){for(var n,r=0,i=t.length;r<i;r++)t[r]&&(n=re(t[r]))&&(e+=n+" ");return e.slice(0,-1)}if(p(t)){for(var o in t)t[o]&&(e+=o+" ");return e.slice(0,-1)}return e}function ie(t){return To(t)?"svg":"math"===t?"math":void 0}function oe(t){if(!bi)return!0;if(ko(t))return!1;if(t=t.toLowerCase(),null!=Ao[t])return Ao[t];var e=document.createElement(t);return t.indexOf("-")>-1?Ao[t]=e.constructor===window.HTMLUnknownElement||e.constructor===window.HTMLElement:Ao[t]=/HTMLUnknownElement/.test(e.toString())}function ae(t){if("string"==typeof t){if(t=document.querySelector(t),!t)return document.createElement("div")}return t}function se(t,e){var n=document.createElement(t);return"select"!==t?n:(e.data&&e.data.attrs&&"multiple"in e.data.attrs&&n.setAttribute("multiple","multiple"),n)}function ue(t,e){return document.createElementNS(xo[t],e)}function ce(t){return document.createTextNode(t)}function le(t){return document.createComment(t)}function fe(t,e,n){t.insertBefore(e,n)}function pe(t,e){t.removeChild(e)}function de(t,e){t.appendChild(e)}function he(t){return t.parentNode}function ve(t){return t.nextSibling}function ge(t){return t.tagName}function me(t,e){t.textContent=e}function ye(t,e,n){t.setAttribute(e,n)}function be(t,e){var n=t.data.ref;if(n){var r=t.context,i=t.componentInstance||t.elm,a=r.$refs;e?Array.isArray(a[n])?o(a[n],i):a[n]===i&&(a[n]=void 0):t.data.refInFor?Array.isArray(a[n])&&a[n].indexOf(i)<0?a[n].push(i):a[n]=[i]:a[n]=i}}function _e(t){return null==t}function we(t){return null!=t}function xe(t,e){return t.key===e.key&&t.tag===e.tag&&t.isComment===e.isComment&&!t.data==!e.data}function Ce(t,e,n){var r,i,o={};for(r=e;r<=n;++r)i=t[r].key,we(i)&&(o[i]=r);return o}function Te(t){function e(t){return new Bi(A.tagName(t).toLowerCase(),{},[],void 0,t)}function n(t,e){function n(){0===--n.listeners&&r(t)}return n.listeners=e,n}function r(t){var e=A.parentNode(t);e&&A.removeChild(e,t)}function o(t,e,n,r,i){if(t.isRootInsert=!i,!a(t,e,n,r)){var o=t.data,s=t.children,u=t.tag;we(u)?(t.elm=t.ns?A.createElementNS(t.ns,u):A.createElement(u,t),h(t),f(t,s,e),we(o)&&d(t,e),l(n,t.elm,r)):t.isComment?(t.elm=A.createComment(t.text),l(n,t.elm,r)):(t.elm=A.createTextNode(t.text),l(n,t.elm,r))}}function a(t,e,n,r){var i=t.data;if(we(i)){var o=we(t.componentInstance)&&i.keepAlive;if(we(i=i.hook)&&we(i=i.init)&&i(t,!1,n,r),we(t.componentInstance))return u(t,e),o&&c(t,e,n,r),!0}}function u(t,e){t.data.pendingInsert&&e.push.apply(e,t.data.pendingInsert),t.elm=t.componentInstance.$el,p(t)?(d(t,e),h(t)):(be(t),e.push(t))}function c(t,e,n,r){for(var i,o=t;o.componentInstance;)if(o=o.componentInstance._vnode,we(i=o.data)&&we(i=i.transition)){for(i=0;i<$.activate.length;++i)$.activate[i](Oo,o);e.push(o);break}l(n,t.elm,r)}function l(t,e,n){t&&(n?A.insertBefore(t,e,n):A.appendChild(t,e))}function f(t,e,n){if(Array.isArray(e))for(var r=0;r<e.length;++r)o(e[r],n,t.elm,null,!0);else s(t.text)&&A.appendChild(t.elm,A.createTextNode(t.text))}function p(t){for(;t.componentInstance;)t=t.componentInstance._vnode;return we(t.tag)}function d(t,e){for(var n=0;n<$.create.length;++n)$.create[n](Oo,t);C=t.data.hook,we(C)&&(C.create&&C.create(Oo,t),C.insert&&e.push(t))}function h(t){var e;we(e=t.context)&&we(e=e.$options._scopeId)&&A.setAttribute(t.elm,e,""),we(e=Zi)&&e!==t.context&&we(e=e.$options._scopeId)&&A.setAttribute(t.elm,e,"")}function v(t,e,n,r,i,a){for(;r<=i;++r)o(n[r],a,t,e)}function g(t){var e,n,r=t.data;if(we(r))for(we(e=r.hook)&&we(e=e.destroy)&&e(t),e=0;e<$.destroy.length;++e)$.destroy[e](t);if(we(e=t.children))for(n=0;n<t.children.length;++n)g(t.children[n])}function m(t,e,n,i){for(;n<=i;++n){var o=e[n];we(o)&&(we(o.tag)?(y(o),g(o)):r(o.elm))}}function y(t,e){if(e||we(t.data)){var i=$.remove.length+1;for(e?e.listeners+=i:e=n(t.elm,i),we(C=t.componentInstance)&&we(C=C._vnode)&&we(C.data)&&y(C,e),C=0;C<$.remove.length;++C)$.remove[C](t,e);we(C=t.data.hook)&&we(C=C.remove)?C(t,e):e()}else r(t.elm)}function b(t,e,n,r,i){for(var a,s,u,c,l=0,f=0,p=e.length-1,d=e[0],h=e[p],g=n.length-1,y=n[0],b=n[g],w=!i;l<=p&&f<=g;)_e(d)?d=e[++l]:_e(h)?h=e[--p]:xe(d,y)?(_(d,y,r),d=e[++l],y=n[++f]):xe(h,b)?(_(h,b,r),h=e[--p],b=n[--g]):xe(d,b)?(_(d,b,r),w&&A.insertBefore(t,d.elm,A.nextSibling(h.elm)),d=e[++l],b=n[--g]):xe(h,y)?(_(h,y,r),w&&A.insertBefore(t,h.elm,d.elm),h=e[--p],y=n[++f]):(_e(a)&&(a=Ce(e,l,p)),s=we(y.key)?a[y.key]:null,_e(s)?(o(y,r,t,d.elm),y=n[++f]):(u=e[s],xe(u,y)?(_(u,y,r),e[s]=void 0,w&&A.insertBefore(t,y.elm,d.elm),y=n[++f]):(o(y,r,t,d.elm),y=n[++f])));l>p?(c=_e(n[g+1])?null:n[g+1].elm,v(t,c,n,f,g,r)):f>g&&m(t,e,l,p)}function _(t,e,n,r){if(t!==e){if(e.isStatic&&t.isStatic&&e.key===t.key&&(e.isCloned||e.isOnce))return e.elm=t.elm,void(e.componentInstance=t.componentInstance);var i,o=e.data,a=we(o);a&&we(i=o.hook)&&we(i=i.prepatch)&&i(t,e);var s=e.elm=t.elm,u=t.children,c=e.children;if(a&&p(e)){for(i=0;i<$.update.length;++i)$.update[i](t,e);we(i=o.hook)&&we(i=i.update)&&i(t,e)}_e(e.text)?we(u)&&we(c)?u!==c&&b(s,u,c,n,r):we(c)?(we(t.text)&&A.setTextContent(s,""),v(s,null,c,0,c.length-1,n)):we(u)?m(s,u,0,u.length-1):we(t.text)&&A.setTextContent(s,""):t.text!==e.text&&A.setTextContent(s,e.text),a&&we(i=o.hook)&&we(i=i.postpatch)&&i(t,e)}}function w(t,e,n){if(n&&t.parent)t.parent.data.pendingInsert=e;else for(var r=0;r<e.length;++r)e[r].data.hook.insert(e[r])}function x(t,e,n){e.elm=t;var r=e.tag,i=e.data,o=e.children;if(we(i)&&(we(C=i.hook)&&we(C=C.init)&&C(e,!0),we(C=e.componentInstance)))return u(e,n),!0;if(we(r)){if(we(o))if(t.hasChildNodes()){for(var a=!0,s=t.firstChild,c=0;c<o.length;c++){if(!s||!x(s,o[c],n)){a=!1;break}s=s.nextSibling}if(!a||s)return!1}else f(e,o,n);if(we(i))for(var l in i)if(!E(l)){d(e,n);break}}else t.data!==e.text&&(t.data=e.text);return!0}var C,T,$={},k=t.modules,A=t.nodeOps;for(C=0;C<jo.length;++C)for($[jo[C]]=[],T=0;T<k.length;++T)void 0!==k[T][jo[C]]&&$[jo[C]].push(k[T][jo[C]]);var E=i("attrs,style,class,staticClass,staticStyle,key");return function(t,n,r,i,a,s){if(!n)return void(t&&g(t));var u=!1,c=[];if(t){var l=we(t.nodeType);if(!l&&xe(t,n))_(t,n,c,i);else{if(l){if(1===t.nodeType&&t.hasAttribute("server-rendered")&&(t.removeAttribute("server-rendered"),r=!0),r&&x(t,n,c))return w(n,c,!0),t;t=e(t)}var f=t.elm,d=A.parentNode(f);if(o(n,c,f._leaveCb?null:d,A.nextSibling(f)),n.parent){for(var h=n.parent;h;)h.elm=n.elm,h=h.parent;if(p(n))for(var v=0;v<$.create.length;++v)$.create[v](Oo,n.parent)}null!==d?m(d,[t],0,0):we(t.tag)&&g(t)}}else u=!0,o(n,c,a,s);return w(n,c,u),n.elm}}function $e(t,e){(t.data.directives||e.data.directives)&&ke(t,e)}function ke(t,e){var n,r,i,o=t===Oo,a=e===Oo,s=Ae(t.data.directives,t.context),u=Ae(e.data.directives,e.context),c=[],l=[];for(n in u)r=s[n],i=u[n],r?(i.oldValue=r.value,Se(i,"update",e,t),i.def&&i.def.componentUpdated&&l.push(i)):(Se(i,"bind",e,t),i.def&&i.def.inserted&&c.push(i));if(c.length){var f=function(){for(var n=0;n<c.length;n++)Se(c[n],"inserted",e,t)};o?it(e.data.hook||(e.data.hook={}),"insert",f,"dir-insert"):f()}if(l.length&&it(e.data.hook||(e.data.hook={}),"postpatch",function(){for(var n=0;n<l.length;n++)Se(l[n],"componentUpdated",e,t)},"dir-postpatch"),!o)for(n in s)u[n]||Se(s[n],"unbind",t,t,a)}function Ae(t,e){var n=Object.create(null);if(!t)return n;var r,i;for(r=0;r<t.length;r++)i=t[r],i.modifiers||(i.modifiers=Do),n[Ee(i)]=i,i.def=F(e.$options,"directives",i.name,!0);return n}function Ee(t){return t.rawName||t.name+"."+Object.keys(t.modifiers||{}).join(".")}function Se(t,e,n,r,i){var o=t.def&&t.def[e];o&&o(n.elm,t,n,r,i)}function Oe(t,e){if(t.data.attrs||e.data.attrs){var n,r,i,o=e.elm,a=t.data.attrs||{},s=e.data.attrs||{};s.__ob__&&(s=e.data.attrs=f({},s));for(n in s)r=s[n],i=a[n],i!==r&&je(o,n,r);xi&&s.value!==a.value&&je(o,"value",s.value);for(n in a)null==s[n]&&(bo(n)?o.removeAttributeNS(yo,_o(n)):go(n)||o.removeAttribute(n))}}function je(t,e,n){mo(e)?wo(n)?t.removeAttribute(e):t.setAttribute(e,e):go(e)?t.setAttribute(e,wo(n)||"false"===n?"false":"true"):bo(e)?wo(n)?t.removeAttributeNS(yo,_o(e)):t.setAttributeNS(yo,e,n):wo(n)?t.removeAttribute(e):t.setAttribute(e,n)}function Ne(t,e){var n=e.elm,r=e.data,i=t.data;if(r.staticClass||r.class||i&&(i.staticClass||i.class)){var o=Qt(e),a=n._transitionClasses;a&&(o=ne(o,re(a))),o!==n._prevClass&&(n.setAttribute("class",o),n._prevClass=o)}}function De(t,e,n,r){if(n){var i=e,o=fo;e=function(n){Ie(t,e,r,o),1===arguments.length?i(n):i.apply(null,arguments)}}fo.addEventListener(t,e,r)}function Ie(t,e,n,r){(r||fo).removeEventListener(t,e,n)}function Re(t,e){if(t.data.on||e.data.on){var n=e.data.on||{},r=t.data.on||{};fo=e.elm,at(n,r,De,Ie,e.context)}}function Le(t,e){if(t.data.domProps||e.data.domProps){var n,r,i=e.elm,o=t.data.domProps||{},a=e.data.domProps||{};a.__ob__&&(a=e.data.domProps=f({},a));for(n in o)null==a[n]&&(i[n]="");for(n in a)if(r=a[n],"textContent"!==n&&"innerHTML"!==n||(e.children&&(e.children.length=0),r!==o[n]))if("value"===n){i._value=r;var s=null==r?"":String(r);Pe(i,e,s)&&(i.value=s)}else i[n]=r}}function Pe(t,e,n){return!t.composing&&("option"===e.tag||Fe(t,n)||qe(e,n))}function Fe(t,e){return document.activeElement!==t&&t.value!==e}function qe(t,e){var n=t.elm.value,i=t.elm._vModifiers;return i&&i.number||"number"===t.elm.type?r(n)!==r(e):i&&i.trim?n.trim()!==e.trim():n!==e}function Me(t){var e=He(t.style);return t.staticStyle?f(t.staticStyle,e):e}function He(t){return Array.isArray(t)?h(t):"string"==typeof t?qo(t):t}function Be(t,e){var n,r={};if(e)for(var i=t;i.componentInstance;)i=i.componentInstance._vnode,i.data&&(n=Me(i.data))&&f(r,n);(n=Me(t.data))&&f(r,n);for(var o=t;o=o.parent;)o.data&&(n=Me(o.data))&&f(r,n);return r}function Ue(t,e){var n=e.data,r=t.data;if(n.staticStyle||n.style||r.staticStyle||r.style){var i,o,a=e.elm,s=t.data.staticStyle,u=t.data.style||{},c=s||u,l=He(e.data.style)||{};e.data.style=l.__ob__?f({},l):l;var p=Be(e,!0);for(o in c)null==p[o]&&Bo(a,o,"");for(o in p)i=p[o],i!==c[o]&&Bo(a,o,null==i?"":i)}}function We(t,e){if(e&&e.trim())if(t.classList)e.indexOf(" ")>-1?e.split(/\s+/).forEach(function(e){return t.classList.add(e)}):t.classList.add(e);else{var n=" "+t.getAttribute("class")+" ";n.indexOf(" "+e+" ")<0&&t.setAttribute("class",(n+e).trim())}}function ze(t,e){if(e&&e.trim())if(t.classList)e.indexOf(" ")>-1?e.split(/\s+/).forEach(function(e){return t.classList.remove(e)}):t.classList.remove(e);else{for(var n=" "+t.getAttribute("class")+" ",r=" "+e+" ";n.indexOf(r)>=0;)n=n.replace(r," ");t.setAttribute("class",n.trim())}}function Ve(t){Qo(function(){Qo(t)})}function Xe(t,e){(t._transitionClasses||(t._transitionClasses=[])).push(e),We(t,e)}function Ke(t,e){t._transitionClasses&&o(t._transitionClasses,e),ze(t,e)}function Je(t,e,n){var r=Ge(t,e),i=r.type,o=r.timeout,a=r.propCount;if(!i)return n();var s=i===Xo?Go:Yo,u=0,c=function(){t.removeEventListener(s,l),n()},l=function(e){e.target===t&&++u>=a&&c()};setTimeout(function(){u<a&&c()},o+1),t.addEventListener(s,l)}function Ge(t,e){var n,r=window.getComputedStyle(t),i=r[Jo+"Delay"].split(", "),o=r[Jo+"Duration"].split(", "),a=Ze(i,o),s=r[Zo+"Delay"].split(", "),u=r[Zo+"Duration"].split(", "),c=Ze(s,u),l=0,f=0;e===Xo?a>0&&(n=Xo,l=a,f=o.length):e===Ko?c>0&&(n=Ko,l=c,f=u.length):(l=Math.max(a,c),n=l>0?a>c?Xo:Ko:null,f=n?n===Xo?o.length:u.length:0);var p=n===Xo&&ta.test(r[Jo+"Property"]);return{type:n,timeout:l,propCount:f,hasTransform:p}}function Ze(t,e){for(;t.length<e.length;)t=t.concat(t);return Math.max.apply(null,e.map(function(e,n){return Ye(e)+Ye(t[n])}))}function Ye(t){return 1e3*Number(t.slice(0,-1))}function Qe(t,e){var n=t.elm;n._leaveCb&&(n._leaveCb.cancelled=!0, n._leaveCb());var r=en(t.data.transition);if(r&&!n._enterCb&&1===n.nodeType){for(var i=r.css,o=r.type,a=r.enterClass,s=r.enterToClass,u=r.enterActiveClass,c=r.appearClass,l=r.appearToClass,f=r.appearActiveClass,p=r.beforeEnter,d=r.enter,h=r.afterEnter,v=r.enterCancelled,g=r.beforeAppear,m=r.appear,y=r.afterAppear,b=r.appearCancelled,_=Zi,w=Zi.$vnode;w&&w.parent;)w=w.parent,_=w.context;var x=!_._isMounted||!t.isRootInsert;if(!x||m||""===m){var C=x?c:a,T=x?f:u,$=x?l:s,k=x?g||p:p,A=x&&"function"==typeof m?m:d,E=x?y||h:h,S=x?b||v:v,O=i!==!1&&!xi,j=A&&(A._length||A.length)>1,N=n._enterCb=nn(function(){O&&(Ke(n,$),Ke(n,T)),N.cancelled?(O&&Ke(n,C),S&&S(n)):E&&E(n),n._enterCb=null});t.data.show||it(t.data.hook||(t.data.hook={}),"insert",function(){var e=n.parentNode,r=e&&e._pending&&e._pending[t.key];r&&r.tag===t.tag&&r.elm._leaveCb&&r.elm._leaveCb(),A&&A(n,N)},"transition-insert"),k&&k(n),O&&(Xe(n,C),Xe(n,T),Ve(function(){Xe(n,$),Ke(n,C),N.cancelled||j||Je(n,o,N)})),t.data.show&&(e&&e(),A&&A(n,N)),O||j||N()}}}function tn(t,e){function n(){m.cancelled||(t.data.show||((r.parentNode._pending||(r.parentNode._pending={}))[t.key]=t),l&&l(r),v&&(Xe(r,s),Xe(r,c),Ve(function(){Xe(r,u),Ke(r,s),m.cancelled||g||Je(r,a,m)})),f&&f(r,m),v||g||m())}var r=t.elm;r._enterCb&&(r._enterCb.cancelled=!0,r._enterCb());var i=en(t.data.transition);if(!i)return e();if(!r._leaveCb&&1===r.nodeType){var o=i.css,a=i.type,s=i.leaveClass,u=i.leaveToClass,c=i.leaveActiveClass,l=i.beforeLeave,f=i.leave,p=i.afterLeave,d=i.leaveCancelled,h=i.delayLeave,v=o!==!1&&!xi,g=f&&(f._length||f.length)>1,m=r._leaveCb=nn(function(){r.parentNode&&r.parentNode._pending&&(r.parentNode._pending[t.key]=null),v&&(Ke(r,u),Ke(r,c)),m.cancelled?(v&&Ke(r,s),d&&d(r)):(e(),p&&p(r)),r._leaveCb=null});h?h(n):n()}}function en(t){if(t){if("object"==typeof t){var e={};return t.css!==!1&&f(e,ea(t.name||"v")),f(e,t),e}return"string"==typeof t?ea(t):void 0}}function nn(t){var e=!1;return function(){e||(e=!0,t())}}function rn(t,e){e.data.show||Qe(e)}function on(t,e,n){var r=e.value,i=t.multiple;if(!i||Array.isArray(r)){for(var o,a,s=0,u=t.options.length;s<u;s++)if(a=t.options[s],i)o=y(r,sn(a))>-1,a.selected!==o&&(a.selected=o);else if(m(sn(a),r))return void(t.selectedIndex!==s&&(t.selectedIndex=s));i||(t.selectedIndex=-1)}}function an(t,e){for(var n=0,r=e.length;n<r;n++)if(m(sn(e[n]),t))return!1;return!0}function sn(t){return"_value"in t?t._value:t.value}function un(t){t.target.composing=!0}function cn(t){t.target.composing=!1,ln(t.target,"input")}function ln(t,e){var n=document.createEvent("HTMLEvents");n.initEvent(e,!0,!0),t.dispatchEvent(n)}function fn(t){return!t.componentInstance||t.data&&t.data.transition?t:fn(t.componentInstance._vnode)}function pn(t){var e=t&&t.componentOptions;return e&&e.Ctor.options.abstract?pn(lt(e.children)):t}function dn(t){var e={},n=t.$options;for(var r in n.propsData)e[r]=t[r];var i=n._parentListeners;for(var o in i)e[ui(o)]=i[o].fn;return e}function hn(t,e){return/\d-keep-alive$/.test(e.tag)?t("keep-alive"):null}function vn(t){for(;t=t.parent;)if(t.data.transition)return!0}function gn(t,e){return e.key===t.key&&e.tag===t.tag}function mn(t){t.elm._moveCb&&t.elm._moveCb(),t.elm._enterCb&&t.elm._enterCb()}function yn(t){t.data.newPos=t.elm.getBoundingClientRect()}function bn(t){var e=t.data.pos,n=t.data.newPos,r=e.left-n.left,i=e.top-n.top;if(r||i){t.data.moved=!0;var o=t.elm.style;o.transform=o.WebkitTransform="translate("+r+"px,"+i+"px)",o.transitionDuration="0s"}}function _n(t,e){var n=document.createElement("div");return n.innerHTML='<div a="'+t+'">',n.innerHTML.indexOf(e)>0}function wn(t){return ha=ha||document.createElement("div"),ha.innerHTML=t,ha.textContent}function xn(t,e){return e&&(t=t.replace(ss,"\n")),t.replace(os,"<").replace(as,">").replace(us,"&").replace(cs,'"')}function Cn(t,e){function n(e){f+=e,t=t.substring(e)}function r(){var e=t.match($a);if(e){var r={tagName:e[1],attrs:[],start:f};n(e[0].length);for(var i,o;!(i=t.match(ka))&&(o=t.match(xa));)n(o[0].length),r.attrs.push(o);if(i)return r.unarySlash=i[1],n(i[0].length),r.end=f,r}}function i(t){var n=t.tagName,r=t.unarySlash;c&&("p"===s&&ya(n)&&o(s),ma(n)&&s===n&&o(n));for(var i=l(n)||"html"===n&&"head"===s||!!r,a=t.attrs.length,f=new Array(a),p=0;p<a;p++){var d=t.attrs[p];ja&&d[0].indexOf('""')===-1&&(""===d[3]&&delete d[3],""===d[4]&&delete d[4],""===d[5]&&delete d[5]);var h=d[3]||d[4]||d[5]||"";f[p]={name:d[1],value:xn(h,e.shouldDecodeNewlines)}}i||(u.push({tag:n,lowerCasedTag:n.toLowerCase(),attrs:f}),s=n,r=""),e.start&&e.start(n,f,i,t.start,t.end)}function o(t,n,r){var i,o;if(null==n&&(n=f),null==r&&(r=f),t&&(o=t.toLowerCase()),t)for(i=u.length-1;i>=0&&u[i].lowerCasedTag!==o;i--);else i=0;if(i>=0){for(var a=u.length-1;a>=i;a--)e.end&&e.end(u[a].tag,n,r);u.length=i,s=i&&u[i-1].tag}else"br"===o?e.start&&e.start(t,[],!0,n,r):"p"===o&&(e.start&&e.start(t,[],!1,n,r),e.end&&e.end(t,n,r))}for(var a,s,u=[],c=e.expectHTML,l=e.isUnaryTag||hi,f=0;t;){if(a=t,s&&rs(s)){var p=s.toLowerCase(),d=is[p]||(is[p]=new RegExp("([\\s\\S]*?)(</"+p+"[^>]*>)","i")),h=0,v=t.replace(d,function(t,n,r){return h=r.length,"script"!==p&&"style"!==p&&"noscript"!==p&&(n=n.replace(/<!--([\s\S]*?)-->/g,"$1").replace(/<!\[CDATA\[([\s\S]*?)]]>/g,"$1")),e.chars&&e.chars(n),""});f+=t.length-v.length,t=v,o(p,f-h,f)}else{var g=t.indexOf("<");if(0===g){if(Sa.test(t)){var m=t.indexOf("-->");if(m>=0){n(m+3);continue}}if(Oa.test(t)){var y=t.indexOf("]>");if(y>=0){n(y+2);continue}}var b=t.match(Ea);if(b){n(b[0].length);continue}var _=t.match(Aa);if(_){var w=f;n(_[0].length),o(_[1],w,f);continue}var x=r();if(x){i(x);continue}}var C=void 0,T=void 0,$=void 0;if(g>0){for(T=t.slice(g);!(Aa.test(T)||$a.test(T)||Sa.test(T)||Oa.test(T)||($=T.indexOf("<",1),$<0));)g+=$,T=t.slice(g);C=t.substring(0,g),n(g)}g<0&&(C=t,t=""),e.chars&&C&&e.chars(C)}if(t===a&&e.chars){e.chars(t);break}}o()}function Tn(t){function e(){(a||(a=[])).push(t.slice(h,i).trim()),h=i+1}var n,r,i,o,a,s=!1,u=!1,c=!1,l=!1,f=0,p=0,d=0,h=0;for(i=0;i<t.length;i++)if(r=n,n=t.charCodeAt(i),s)39===n&&92!==r&&(s=!1);else if(u)34===n&&92!==r&&(u=!1);else if(c)96===n&&92!==r&&(c=!1);else if(l)47===n&&92!==r&&(l=!1);else if(124!==n||124===t.charCodeAt(i+1)||124===t.charCodeAt(i-1)||f||p||d){switch(n){case 34:u=!0;break;case 39:s=!0;break;case 96:c=!0;break;case 40:d++;break;case 41:d--;break;case 91:p++;break;case 93:p--;break;case 123:f++;break;case 125:f--}if(47===n){for(var v=i-1,g=void 0;v>=0&&(g=t.charAt(v)," "===g);v--);g&&/[\w$]/.test(g)||(l=!0)}}else void 0===o?(h=i+1,o=t.slice(0,i).trim()):e();if(void 0===o?o=t.slice(0,i).trim():0!==h&&e(),a)for(i=0;i<a.length;i++)o=$n(o,a[i]);return o}function $n(t,e){var n=e.indexOf("(");if(n<0)return'_f("'+e+'")('+t+")";var r=e.slice(0,n),i=e.slice(n+1);return'_f("'+r+'")('+t+","+i}function kn(t,e){var n=e?ps(e):ls;if(n.test(t)){for(var r,i,o=[],a=n.lastIndex=0;r=n.exec(t);){i=r.index,i>a&&o.push(JSON.stringify(t.slice(a,i)));var s=Tn(r[1].trim());o.push("_s("+s+")"),a=i+r[0].length}return a<t.length&&o.push(JSON.stringify(t.slice(a))),o.join("+")}}function An(t){console.error("[Vue parser]: "+t)}function En(t,e){return t?t.map(function(t){return t[e]}).filter(function(t){return t}):[]}function Sn(t,e,n){(t.props||(t.props=[])).push({name:e,value:n})}function On(t,e,n){(t.attrs||(t.attrs=[])).push({name:e,value:n})}function jn(t,e,n,r,i,o){(t.directives||(t.directives=[])).push({name:e,rawName:n,value:r,arg:i,modifiers:o})}function Nn(t,e,n,r,i){r&&r.capture&&(delete r.capture,e="!"+e),r&&r.once&&(delete r.once,e="~"+e);var o;r&&r.native?(delete r.native,o=t.nativeEvents||(t.nativeEvents={})):o=t.events||(t.events={});var a={value:n,modifiers:r},s=o[e];Array.isArray(s)?i?s.unshift(a):s.push(a):s?o[e]=i?[a,s]:[s,a]:o[e]=a}function Dn(t,e,n){var r=In(t,":"+e)||In(t,"v-bind:"+e);if(null!=r)return Tn(r);if(n!==!1){var i=In(t,e);if(null!=i)return JSON.stringify(i)}}function In(t,e){var n;if(null!=(n=t.attrsMap[e]))for(var r=t.attrsList,i=0,o=r.length;i<o;i++)if(r[i].name===e){r.splice(i,1);break}return n}function Rn(t){if(Da=t,Na=Da.length,Ra=La=Pa=0,t.indexOf("[")<0||t.lastIndexOf("]")<Na-1)return{exp:t,idx:null};for(;!Pn();)Ia=Ln(),Fn(Ia)?Mn(Ia):91===Ia&&qn(Ia);return{exp:t.substring(0,La),idx:t.substring(La+1,Pa)}}function Ln(){return Da.charCodeAt(++Ra)}function Pn(){return Ra>=Na}function Fn(t){return 34===t||39===t}function qn(t){var e=1;for(La=Ra;!Pn();)if(t=Ln(),Fn(t))Mn(t);else if(91===t&&e++,93===t&&e--,0===e){Pa=Ra;break}}function Mn(t){for(var e=t;!Pn()&&(t=Ln(),t!==e););}function Hn(t,e){Fa=e.warn||An,qa=e.getTagNamespace||hi,Ma=e.mustUseProp||hi,Ha=e.isPreTag||hi,Ba=En(e.modules,"preTransformNode"),Ua=En(e.modules,"transformNode"),Wa=En(e.modules,"postTransformNode"),za=e.delimiters;var n,r,i=[],o=e.preserveWhitespace!==!1,a=!1,s=!1;return Cn(t,{expectHTML:e.expectHTML,isUnaryTag:e.isUnaryTag,shouldDecodeNewlines:e.shouldDecodeNewlines,start:function(t,o,u){function c(t){}var l=r&&r.ns||qa(t);wi&&"svg"===l&&(o=or(o));var f={type:1,tag:t,attrsList:o,attrsMap:rr(o),parent:r,children:[]};l&&(f.ns=l),ir(f)&&!ki()&&(f.forbidden=!0);for(var p=0;p<Ba.length;p++)Ba[p](f,e);if(a||(Bn(f),f.pre&&(a=!0)),Ha(f.tag)&&(s=!0),a)Un(f);else{Vn(f),Xn(f),Zn(f),Wn(f),f.plain=!f.key&&!o.length,zn(f),Yn(f),Qn(f);for(var d=0;d<Ua.length;d++)Ua[d](f,e);tr(f)}if(n?i.length||n.if&&(f.elseif||f.else)&&(c(f),Gn(n,{exp:f.elseif,block:f})):(n=f,c(n)),r&&!f.forbidden)if(f.elseif||f.else)Kn(f,r);else if(f.slotScope){r.plain=!1;var h=f.slotTarget||"default";(r.scopedSlots||(r.scopedSlots={}))[h]=f}else r.children.push(f),f.parent=r;u||(r=f,i.push(f));for(var v=0;v<Wa.length;v++)Wa[v](f,e)},end:function(){var t=i[i.length-1],e=t.children[t.children.length-1];e&&3===e.type&&" "===e.text&&t.children.pop(),i.length-=1,r=i[i.length-1],t.pre&&(a=!1),Ha(t.tag)&&(s=!1)},chars:function(t){if(r&&(!wi||"textarea"!==r.tag||r.attrsMap.placeholder!==t)){var e=r.children;if(t=s||t.trim()?_s(t):o&&e.length?" ":""){var n;!a&&" "!==t&&(n=kn(t,za))?e.push({type:2,expression:n,text:t}):" "===t&&" "===e[e.length-1].text||r.children.push({type:3,text:t})}}}}),n}function Bn(t){null!=In(t,"v-pre")&&(t.pre=!0)}function Un(t){var e=t.attrsList.length;if(e)for(var n=t.attrs=new Array(e),r=0;r<e;r++)n[r]={name:t.attrsList[r].name,value:JSON.stringify(t.attrsList[r].value)};else t.pre||(t.plain=!0)}function Wn(t){var e=Dn(t,"key");e&&(t.key=e)}function zn(t){var e=Dn(t,"ref");e&&(t.ref=e,t.refInFor=er(t))}function Vn(t){var e;if(e=In(t,"v-for")){var n=e.match(hs);if(!n)return;t.for=n[2].trim();var r=n[1].trim(),i=r.match(vs);i?(t.alias=i[1].trim(),t.iterator1=i[2].trim(),i[3]&&(t.iterator2=i[3].trim())):t.alias=r}}function Xn(t){var e=In(t,"v-if");if(e)t.if=e,Gn(t,{exp:e,block:t});else{null!=In(t,"v-else")&&(t.else=!0);var n=In(t,"v-else-if");n&&(t.elseif=n)}}function Kn(t,e){var n=Jn(e.children);n&&n.if&&Gn(n,{exp:t.elseif,block:t})}function Jn(t){for(var e=t.length;e--;){if(1===t[e].type)return t[e];t.pop()}}function Gn(t,e){t.ifConditions||(t.ifConditions=[]),t.ifConditions.push(e)}function Zn(t){var e=In(t,"v-once");null!=e&&(t.once=!0)}function Yn(t){if("slot"===t.tag)t.slotName=Dn(t,"name");else{var e=Dn(t,"slot");e&&(t.slotTarget='""'===e?'"default"':e),"template"===t.tag&&(t.slotScope=In(t,"scope"))}}function Qn(t){var e;(e=Dn(t,"is"))&&(t.component=e),null!=In(t,"inline-template")&&(t.inlineTemplate=!0)}function tr(t){var e,n,r,i,o,a,s,u,c=t.attrsList;for(e=0,n=c.length;e<n;e++)if(r=i=c[e].name,o=c[e].value,ds.test(r))if(t.hasBindings=!0,s=nr(r),s&&(r=r.replace(bs,"")),gs.test(r))r=r.replace(gs,""),o=Tn(o),u=!1,s&&(s.prop&&(u=!0,r=ui(r),"innerHtml"===r&&(r="innerHTML")),s.camel&&(r=ui(r))),u||Ma(t.tag,t.attrsMap.type,r)?Sn(t,r,o):On(t,r,o);else if(ms.test(r))r=r.replace(ms,""),Nn(t,r,o,s);else{r=r.replace(ds,"");var l=r.match(ys);l&&(a=l[1])&&(r=r.slice(0,-(a.length+1))),jn(t,r,i,o,a,s)}else{On(t,r,JSON.stringify(o))}}function er(t){for(var e=t;e;){if(void 0!==e.for)return!0;e=e.parent}return!1}function nr(t){var e=t.match(bs);if(e){var n={};return e.forEach(function(t){n[t.slice(1)]=!0}),n}}function rr(t){for(var e={},n=0,r=t.length;n<r;n++)e[t[n].name]=t[n].value;return e}function ir(t){return"style"===t.tag||"script"===t.tag&&(!t.attrsMap.type||"text/javascript"===t.attrsMap.type)}function or(t){for(var e=[],n=0;n<t.length;n++){var r=t[n];ws.test(r.name)||(r.name=r.name.replace(xs,""),e.push(r))}return e}function ar(t,e){t&&(Va=Cs(e.staticKeys||""),Xa=e.isReservedTag||hi,ur(t),cr(t,!1))}function sr(t){return i("type,tag,attrsList,attrsMap,plain,parent,children,attrs"+(t?","+t:""))}function ur(t){if(t.static=fr(t),1===t.type){if(!Xa(t.tag)&&"slot"!==t.tag&&null==t.attrsMap["inline-template"])return;for(var e=0,n=t.children.length;e<n;e++){var r=t.children[e];ur(r),r.static||(t.static=!1)}}}function cr(t,e){if(1===t.type){if((t.static||t.once)&&(t.staticInFor=e),t.static&&t.children.length&&(1!==t.children.length||3!==t.children[0].type))return void(t.staticRoot=!0);if(t.staticRoot=!1,t.children)for(var n=0,r=t.children.length;n<r;n++)cr(t.children[n],e||!!t.for);t.ifConditions&&lr(t.ifConditions,e)}}function lr(t,e){for(var n=1,r=t.length;n<r;n++)cr(t[n].block,e)}function fr(t){return 2!==t.type&&(3===t.type||!(!t.pre&&(t.hasBindings||t.if||t.for||oi(t.tag)||!Xa(t.tag)||pr(t)||!Object.keys(t).every(Va))))}function pr(t){for(;t.parent;){if(t=t.parent,"template"!==t.tag)return!1;if(t.for)return!0}return!1}function dr(t,e){var n=e?"nativeOn:{":"on:{";for(var r in t)n+='"'+r+'":'+hr(r,t[r])+",";return n.slice(0,-1)+"}"}function hr(t,e){if(e){if(Array.isArray(e))return"["+e.map(function(e){return hr(t,e)}).join(",")+"]";if(e.modifiers){var n="",r=[];for(var i in e.modifiers)As[i]?n+=As[i]:r.push(i);r.length&&(n=vr(r)+n);var o=$s.test(e.value)?e.value+"($event)":e.value;return"function($event){"+n+o+"}"}return Ts.test(e.value)||$s.test(e.value)?e.value:"function($event){"+e.value+"}"}return"function(){}"}function vr(t){return"if("+t.map(gr).join("&&")+")return;"}function gr(t){var e=parseInt(t,10);if(e)return"$event.keyCode!=="+e;var n=ks[t];return"_k($event.keyCode,"+JSON.stringify(t)+(n?","+JSON.stringify(n):"")+")"}function mr(t,e){t.wrapData=function(n){return"_b("+n+",'"+t.tag+"',"+e.value+(e.modifiers&&e.modifiers.prop?",true":"")+")"}}function yr(t,e){var n=Qa,r=Qa=[],i=ts;ts=0,es=e,Ka=e.warn||An,Ja=En(e.modules,"transformCode"),Ga=En(e.modules,"genData"),Za=e.directives||{},Ya=e.isReservedTag||hi;var o=t?br(t):'_c("div")';return Qa=n,ts=i,{render:"with(this){return "+o+"}",staticRenderFns:r}}function br(t){if(t.staticRoot&&!t.staticProcessed)return _r(t);if(t.once&&!t.onceProcessed)return wr(t);if(t.for&&!t.forProcessed)return Tr(t);if(t.if&&!t.ifProcessed)return xr(t);if("template"!==t.tag||t.slotTarget){if("slot"===t.tag)return Lr(t);var e;if(t.component)e=Pr(t.component,t);else{var n=t.plain?void 0:$r(t),r=t.inlineTemplate?null:Or(t,!0);e="_c('"+t.tag+"'"+(n?","+n:"")+(r?","+r:"")+")"}for(var i=0;i<Ja.length;i++)e=Ja[i](t,e);return e}return Or(t)||"void 0"}function _r(t){return t.staticProcessed=!0,Qa.push("with(this){return "+br(t)+"}"),"_m("+(Qa.length-1)+(t.staticInFor?",true":"")+")"}function wr(t){if(t.onceProcessed=!0,t.if&&!t.ifProcessed)return xr(t);if(t.staticInFor){for(var e="",n=t.parent;n;){if(n.for){e=n.key;break}n=n.parent}return e?"_o("+br(t)+","+ts++ +(e?","+e:"")+")":br(t)}return _r(t)}function xr(t){return t.ifProcessed=!0,Cr(t.ifConditions.slice())}function Cr(t){function e(t){return t.once?wr(t):br(t)}if(!t.length)return"_e()";var n=t.shift();return n.exp?"("+n.exp+")?"+e(n.block)+":"+Cr(t):""+e(n.block)}function Tr(t){var e=t.for,n=t.alias,r=t.iterator1?","+t.iterator1:"",i=t.iterator2?","+t.iterator2:"";return t.forProcessed=!0,"_l(("+e+"),function("+n+r+i+"){return "+br(t)+"})"}function $r(t){var e="{",n=kr(t);n&&(e+=n+","),t.key&&(e+="key:"+t.key+","),t.ref&&(e+="ref:"+t.ref+","),t.refInFor&&(e+="refInFor:true,"),t.pre&&(e+="pre:true,"),t.component&&(e+='tag:"'+t.tag+'",');for(var r=0;r<Ga.length;r++)e+=Ga[r](t);if(t.attrs&&(e+="attrs:{"+Fr(t.attrs)+"},"),t.props&&(e+="domProps:{"+Fr(t.props)+"},"),t.events&&(e+=dr(t.events)+","),t.nativeEvents&&(e+=dr(t.nativeEvents,!0)+","),t.slotTarget&&(e+="slot:"+t.slotTarget+","),t.scopedSlots&&(e+=Er(t.scopedSlots)+","),t.inlineTemplate){var i=Ar(t);i&&(e+=i+",")}return e=e.replace(/,$/,"")+"}",t.wrapData&&(e=t.wrapData(e)),e}function kr(t){var e=t.directives;if(e){var n,r,i,o,a="directives:[",s=!1;for(n=0,r=e.length;n<r;n++){i=e[n],o=!0;var u=Za[i.name]||Es[i.name];u&&(o=!!u(t,i,Ka)),o&&(s=!0,a+='{name:"'+i.name+'",rawName:"'+i.rawName+'"'+(i.value?",value:("+i.value+"),expression:"+JSON.stringify(i.value):"")+(i.arg?',arg:"'+i.arg+'"':"")+(i.modifiers?",modifiers:"+JSON.stringify(i.modifiers):"")+"},")}return s?a.slice(0,-1)+"]":void 0}}function Ar(t){var e=t.children[0];if(1===e.type){var n=yr(e,es);return"inlineTemplate:{render:function(){"+n.render+"},staticRenderFns:["+n.staticRenderFns.map(function(t){return"function(){"+t+"}"}).join(",")+"]}"}}function Er(t){return"scopedSlots:{"+Object.keys(t).map(function(e){return Sr(e,t[e])}).join(",")+"}"}function Sr(t,e){return t+":function("+String(e.attrsMap.scope)+"){return "+("template"===e.tag?Or(e)||"void 0":br(e))+"}"}function Or(t,e){var n=t.children;if(n.length){var r=n[0];if(1===n.length&&r.for&&"template"!==r.tag&&"slot"!==r.tag)return br(r);var i=jr(n);return"["+n.map(Ir).join(",")+"]"+(e&&i?","+i:"")}}function jr(t){for(var e=0,n=0;n<t.length;n++){var r=t[n];if(1===r.type){if(Nr(r)||r.ifConditions&&r.ifConditions.some(function(t){return Nr(t.block)})){e=2;break}(Dr(r)||r.ifConditions&&r.ifConditions.some(function(t){return Dr(t.block)}))&&(e=1)}}return e}function Nr(t){return void 0!==t.for||"template"===t.tag||"slot"===t.tag}function Dr(t){return!Ya(t.tag)}function Ir(t){return 1===t.type?br(t):Rr(t)}function Rr(t){return"_v("+(2===t.type?t.expression:qr(JSON.stringify(t.text)))+")"}function Lr(t){var e=t.slotName||'"default"',n=Or(t),r="_t("+e+(n?","+n:""),i=t.attrs&&"{"+t.attrs.map(function(t){return ui(t.name)+":"+t.value}).join(",")+"}",o=t.attrsMap["v-bind"];return!i&&!o||n||(r+=",null"),i&&(r+=","+i),o&&(r+=(i?"":",null")+","+o),r+")"}function Pr(t,e){var n=e.inlineTemplate?null:Or(e,!0);return"_c("+t+","+$r(e)+(n?","+n:"")+")"}function Fr(t){for(var e="",n=0;n<t.length;n++){var r=t[n];e+='"'+r.name+'":'+qr(r.value)+","}return e.slice(0,-1)}function qr(t){return t.replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function Mr(t,e){var n=Hn(t.trim(),e);ar(n,e);var r=yr(n,e);return{ast:n,render:r.render,staticRenderFns:r.staticRenderFns}}function Hr(t,e){var n=(e.warn||An,In(t,"class"));n&&(t.staticClass=JSON.stringify(n));var r=Dn(t,"class",!1);r&&(t.classBinding=r)}function Br(t){var e="";return t.staticClass&&(e+="staticClass:"+t.staticClass+","),t.classBinding&&(e+="class:"+t.classBinding+","),e}function Ur(t,e){var n=(e.warn||An,In(t,"style"));if(n){t.staticStyle=JSON.stringify(qo(n))}var r=Dn(t,"style",!1);r&&(t.styleBinding=r)}function Wr(t){var e="";return t.staticStyle&&(e+="staticStyle:"+t.staticStyle+","),t.styleBinding&&(e+="style:("+t.styleBinding+"),"),e}function zr(t,e,n){ns=n;var r=e.value,i=e.modifiers,o=t.tag,a=t.attrsMap.type;return"select"===o?Jr(t,r,i):"input"===o&&"checkbox"===a?Vr(t,r,i):"input"===o&&"radio"===a?Xr(t,r,i):Kr(t,r,i),!0}function Vr(t,e,n){var r=n&&n.number,i=Dn(t,"value")||"null",o=Dn(t,"true-value")||"true",a=Dn(t,"false-value")||"false";Sn(t,"checked","Array.isArray("+e+")?_i("+e+","+i+")>-1"+("true"===o?":("+e+")":":_q("+e+","+o+")")),Nn(t,"click","var $$a="+e+",$$el=$event.target,$$c=$$el.checked?("+o+"):("+a+");if(Array.isArray($$a)){var $$v="+(r?"_n("+i+")":i)+",$$i=_i($$a,$$v);if($$c){$$i<0&&("+e+"=$$a.concat($$v))}else{$$i>-1&&("+e+"=$$a.slice(0,$$i).concat($$a.slice($$i+1)))}}else{"+e+"=$$c}",null,!0)}function Xr(t,e,n){var r=n&&n.number,i=Dn(t,"value")||"null";i=r?"_n("+i+")":i,Sn(t,"checked","_q("+e+","+i+")"),Nn(t,"click",Gr(e,i),null,!0)}function Kr(t,e,n){var r=t.attrsMap.type,i=n||{},o=i.lazy,a=i.number,s=i.trim,u=o||wi&&"range"===r?"change":"input",c=!o&&"range"!==r,l="input"===t.tag||"textarea"===t.tag,f=l?"$event.target.value"+(s?".trim()":""):s?"(typeof $event === 'string' ? $event.trim() : $event)":"$event";f=a||"number"===r?"_n("+f+")":f;var p=Gr(e,f);l&&c&&(p="if($event.target.composing)return;"+p),Sn(t,"value",l?"_s("+e+")":"("+e+")"),Nn(t,u,p,null,!0),(s||a||"number"===r)&&Nn(t,"blur","$forceUpdate()")}function Jr(t,e,n){var r=n&&n.number,i='Array.prototype.filter.call($event.target.options,function(o){return o.selected}).map(function(o){var val = "_value" in o ? o._value : o.value;return '+(r?"_n(val)":"val")+"})"+(null==t.attrsMap.multiple?"[0]":""),o=Gr(e,i);Nn(t,"change",o,null,!0)}function Gr(t,e){var n=Rn(t);return null===n.idx?t+"="+e:"var $$exp = "+n.exp+", $$idx = "+n.idx+";if (!Array.isArray($$exp)){"+t+"="+e+"}else{$$exp.splice($$idx, 1, "+e+")}"}function Zr(t,e){e.value&&Sn(t,"textContent","_s("+e.value+")")}function Yr(t,e){e.value&&Sn(t,"innerHTML","_s("+e.value+")")}function Qr(t,e){return e=e?f(f({},Is),e):Is,Mr(t,e)}function ti(t,e,n){var r=(e&&e.warn||Oi,e&&e.delimiters?String(e.delimiters)+t:t);if(Ds[r])return Ds[r];var i={},o=Qr(t,e);i.render=ei(o.render);var a=o.staticRenderFns.length;i.staticRenderFns=new Array(a);for(var s=0;s<a;s++)i.staticRenderFns[s]=ei(o.staticRenderFns[s]);return Ds[r]=i}function ei(t){try{return new Function(t)}catch(t){return v}}function ni(t){if(t.outerHTML)return t.outerHTML;var e=document.createElement("div");return e.appendChild(t.cloneNode(!0)),e.innerHTML}var ri,ii,oi=i("slot,component",!0),ai=Object.prototype.hasOwnProperty,si=/-(\w)/g,ui=u(function(t){return t.replace(si,function(t,e){return e?e.toUpperCase():""})}),ci=u(function(t){return t.charAt(0).toUpperCase()+t.slice(1)}),li=/([^-])([A-Z])/g,fi=u(function(t){return t.replace(li,"$1-$2").replace(li,"$1-$2").toLowerCase()}),pi=Object.prototype.toString,di="[object Object]",hi=function(){return!1},vi=function(t){return t},gi={optionMergeStrategies:Object.create(null),silent:!1,devtools:!1,errorHandler:null,ignoredElements:[],keyCodes:Object.create(null),isReservedTag:hi,isUnknownElement:hi,getTagNamespace:v,parsePlatformTagName:vi,mustUseProp:hi,_assetTypes:["component","directive","filter"],_lifecycleHooks:["beforeCreate","created","beforeMount","mounted","beforeUpdate","updated","beforeDestroy","destroyed","activated","deactivated"],_maxUpdateCount:100},mi=/[^\w.$]/,yi="__proto__"in{},bi="undefined"!=typeof window,_i=bi&&window.navigator.userAgent.toLowerCase(),wi=_i&&/msie|trident/.test(_i),xi=_i&&_i.indexOf("msie 9.0")>0,Ci=_i&&_i.indexOf("edge/")>0,Ti=_i&&_i.indexOf("android")>0,$i=_i&&/iphone|ipad|ipod|ios/.test(_i),ki=function(){return void 0===ri&&(ri=!bi&&"undefined"!=typeof e&&"server"===e.process.env.VUE_ENV),ri},Ai=bi&&window.__VUE_DEVTOOLS_GLOBAL_HOOK__,Ei=function(){function t(){r=!1;var t=n.slice(0);n.length=0;for(var e=0;e<t.length;e++)t[e]()}var e,n=[],r=!1;if("undefined"!=typeof Promise&&x(Promise)){var i=Promise.resolve(),o=function(t){console.error(t)};e=function(){i.then(t).catch(o),$i&&setTimeout(v)}}else if("undefined"==typeof MutationObserver||!x(MutationObserver)&&"[object MutationObserverConstructor]"!==MutationObserver.toString())e=function(){setTimeout(t,0)};else{var a=1,s=new MutationObserver(t),u=document.createTextNode(String(a));s.observe(u,{characterData:!0}),e=function(){a=(a+1)%2,u.data=String(a)}}return function(t,i){var o;if(n.push(function(){t&&t.call(i),o&&o(i)}),r||(r=!0,e()),!t&&"undefined"!=typeof Promise)return new Promise(function(t){o=t})}}();ii="undefined"!=typeof Set&&x(Set)?Set:function(){function t(){this.set=Object.create(null)}return t.prototype.has=function(t){return this.set[t]===!0},t.prototype.add=function(t){this.set[t]=!0},t.prototype.clear=function(){this.set=Object.create(null)},t}();var Si,Oi=v,ji=0,Ni=function(){this.id=ji++,this.subs=[]};Ni.prototype.addSub=function(t){this.subs.push(t)},Ni.prototype.removeSub=function(t){o(this.subs,t)},Ni.prototype.depend=function(){Ni.target&&Ni.target.addDep(this)},Ni.prototype.notify=function(){for(var t=this.subs.slice(),e=0,n=t.length;e<n;e++)t[e].update()},Ni.target=null;var Di=[],Ii=Array.prototype,Ri=Object.create(Ii);["push","pop","shift","unshift","splice","sort","reverse"].forEach(function(t){var e=Ii[t];_(Ri,t,function(){for(var n=arguments,r=arguments.length,i=new Array(r);r--;)i[r]=n[r];var o,a=e.apply(this,i),s=this.__ob__;switch(t){case"push":o=i;break;case"unshift":o=i;break;case"splice":o=i.slice(2)}return o&&s.observeArray(o),s.dep.notify(),a})});var Li=Object.getOwnPropertyNames(Ri),Pi={shouldConvert:!0,isSettingProps:!1},Fi=function(t){if(this.value=t,this.dep=new Ni,this.vmCount=0,_(t,"__ob__",this),Array.isArray(t)){var e=yi?$:k;e(t,Ri,Li),this.observeArray(t)}else this.walk(t)};Fi.prototype.walk=function(t){for(var e=Object.keys(t),n=0;n<e.length;n++)E(t,e[n],t[e[n]])},Fi.prototype.observeArray=function(t){for(var e=0,n=t.length;e<n;e++)A(t[e])};var qi=gi.optionMergeStrategies;qi.data=function(t,e,n){return n?t||e?function(){var r="function"==typeof e?e.call(n):e,i="function"==typeof t?t.call(n):void 0;return r?N(r,i):i}:void 0:e?"function"!=typeof e?t:t?function(){return N(e.call(this),t.call(this))}:e:t},gi._lifecycleHooks.forEach(function(t){qi[t]=D}),gi._assetTypes.forEach(function(t){qi[t+"s"]=I}),qi.watch=function(t,e){if(!e)return t;if(!t)return e;var n={};f(n,t);for(var r in e){var i=n[r],o=e[r];i&&!Array.isArray(i)&&(i=[i]),n[r]=i?i.concat(o):[o]}return n},qi.props=qi.methods=qi.computed=function(t,e){if(!e)return t;if(!t)return e;var n=Object.create(null);return f(n,t),f(n,e),n};var Mi=function(t,e){return void 0===e?t:e},Hi=Object.freeze({defineReactive:E,_toString:n,toNumber:r,makeMap:i,isBuiltInTag:oi,remove:o,hasOwn:a,isPrimitive:s,cached:u,camelize:ui,capitalize:ci,hyphenate:fi,bind:c,toArray:l,extend:f,isObject:p,isPlainObject:d,toObject:h,noop:v,no:hi,identity:vi,genStaticKeys:g,looseEqual:m,looseIndexOf:y,isReserved:b,def:_,parsePath:w,hasProto:yi,inBrowser:bi,UA:_i,isIE:wi,isIE9:xi,isEdge:Ci,isAndroid:Ti,isIOS:$i,isServerRendering:ki,devtools:Ai,nextTick:Ei,get _Set(){return ii},mergeOptions:P,resolveAsset:F,get warn(){return Oi},get formatComponentName(){return Si},validateProp:q}),Bi=function(t,e,n,r,i,o,a){this.tag=t,this.data=e,this.children=n,this.text=r,this.elm=i,this.ns=void 0,this.context=o,this.functionalContext=void 0,this.key=e&&e.key,this.componentOptions=a,this.componentInstance=void 0,this.parent=void 0,this.raw=!1,this.isStatic=!1,this.isRootInsert=!0,this.isComment=!1,this.isCloned=!1,this.isOnce=!1},Ui={child:{}};Ui.child.get=function(){return this.componentInstance},Object.defineProperties(Bi.prototype,Ui);var Wi,zi=function(){var t=new Bi;return t.text="",t.isComment=!0,t},Vi={init:J,prepatch:G,insert:Z,destroy:Y},Xi=Object.keys(Vi),Ki=u(function(t){var e="~"===t.charAt(0);t=e?t.slice(1):t;var n="!"===t.charAt(0);return t=n?t.slice(1):t,{name:t,once:e,capture:n}}),Ji=1,Gi=2,Zi=null,Yi=[],Qi={},to=!1,eo=!1,no=0,ro=0,io=function(t,e,n,r){this.vm=t,t._watchers.push(this),r?(this.deep=!!r.deep,this.user=!!r.user,this.lazy=!!r.lazy,this.sync=!!r.sync):this.deep=this.user=this.lazy=this.sync=!1,this.cb=n,this.id=++ro,this.active=!0,this.dirty=this.lazy,this.deps=[],this.newDeps=[],this.depIds=new ii,this.newDepIds=new ii,this.expression="","function"==typeof e?this.getter=e:(this.getter=w(e),this.getter||(this.getter=function(){})),this.value=this.lazy?void 0:this.get()};io.prototype.get=function(){C(this);var t=this.getter.call(this.vm,this.vm);return this.deep&&Et(t),T(),this.cleanupDeps(),t},io.prototype.addDep=function(t){var e=t.id;this.newDepIds.has(e)||(this.newDepIds.add(e),this.newDeps.push(t),this.depIds.has(e)||t.addSub(this))},io.prototype.cleanupDeps=function(){for(var t=this,e=this.deps.length;e--;){var n=t.deps[e];t.newDepIds.has(n.id)||n.removeSub(t)}var r=this.depIds;this.depIds=this.newDepIds,this.newDepIds=r,this.newDepIds.clear(),r=this.deps,this.deps=this.newDeps,this.newDeps=r,this.newDeps.length=0},io.prototype.update=function(){this.lazy?this.dirty=!0:this.sync?this.run():At(this)},io.prototype.run=function(){if(this.active){var t=this.get();if(t!==this.value||p(t)||this.deep){var e=this.value;if(this.value=t,this.user)try{this.cb.call(this.vm,t,e)}catch(t){if(!gi.errorHandler)throw t;gi.errorHandler.call(null,t,this.vm)}else this.cb.call(this.vm,t,e)}}},io.prototype.evaluate=function(){this.value=this.get(),this.dirty=!1},io.prototype.depend=function(){for(var t=this,e=this.deps.length;e--;)t.deps[e].depend()},io.prototype.teardown=function(){var t=this;if(this.active){this.vm._isBeingDestroyed||o(this.vm._watchers,this);for(var e=this.deps.length;e--;)t.deps[e].removeSub(t);this.active=!1}};var oo=new ii,ao={enumerable:!0,configurable:!0,get:v,set:v},so=0;Mt(Ut),Ft(Ut),wt(Ut),Ct(Ut),vt(Ut);var uo=[String,RegExp],co={name:"keep-alive",abstract:!0,props:{include:uo,exclude:uo},created:function(){this.cache=Object.create(null)},destroyed:function(){var t=this;for(var e in this.cache)Zt(t.cache[e])},watch:{include:function(t){Gt(this.cache,function(e){return Jt(t,e)})},exclude:function(t){Gt(this.cache,function(e){return!Jt(t,e)})}},render:function(){var t=lt(this.$slots.default),e=t&&t.componentOptions;if(e){var n=Kt(e);if(n&&(this.include&&!Jt(this.include,n)||this.exclude&&Jt(this.exclude,n)))return t;var r=null==t.key?e.Ctor.cid+(e.tag?"::"+e.tag:""):t.key;this.cache[r]?t.componentInstance=this.cache[r].componentInstance:this.cache[r]=t,t.data.keepAlive=!0}return t}},lo={KeepAlive:co};Yt(Ut),Object.defineProperty(Ut.prototype,"$isServer",{get:ki}),Ut.version="2.1.10";var fo,po,ho=i("input,textarea,option,select"),vo=function(t,e,n){return"value"===n&&ho(t)&&"button"!==e||"selected"===n&&"option"===t||"checked"===n&&"input"===t||"muted"===n&&"video"===t},go=i("contenteditable,draggable,spellcheck"),mo=i("allowfullscreen,async,autofocus,autoplay,checked,compact,controls,declare,default,defaultchecked,defaultmuted,defaultselected,defer,disabled,enabled,formnovalidate,hidden,indeterminate,inert,ismap,itemscope,loop,multiple,muted,nohref,noresize,noshade,novalidate,nowrap,open,pauseonexit,readonly,required,reversed,scoped,seamless,selected,sortable,translate,truespeed,typemustmatch,visible"),yo="http://www.w3.org/1999/xlink",bo=function(t){return":"===t.charAt(5)&&"xlink"===t.slice(0,5)},_o=function(t){return bo(t)?t.slice(6,t.length):""},wo=function(t){return null==t||t===!1},xo={svg:"http://www.w3.org/2000/svg",math:"http://www.w3.org/1998/Math/MathML"},Co=i("html,body,base,head,link,meta,style,title,address,article,aside,footer,header,h1,h2,h3,h4,h5,h6,hgroup,nav,section,div,dd,dl,dt,figcaption,figure,hr,img,li,main,ol,p,pre,ul,a,b,abbr,bdi,bdo,br,cite,code,data,dfn,em,i,kbd,mark,q,rp,rt,rtc,ruby,s,samp,small,span,strong,sub,sup,time,u,var,wbr,area,audio,map,track,video,embed,object,param,source,canvas,script,noscript,del,ins,caption,col,colgroup,table,thead,tbody,td,th,tr,button,datalist,fieldset,form,input,label,legend,meter,optgroup,option,output,progress,select,textarea,details,dialog,menu,menuitem,summary,content,element,shadow,template"),To=i("svg,animate,circle,clippath,cursor,defs,desc,ellipse,filter,font-face,g,glyph,image,line,marker,mask,missing-glyph,path,pattern,polygon,polyline,rect,switch,symbol,text,textpath,tspan,use,view",!0),$o=function(t){return"pre"===t},ko=function(t){return Co(t)||To(t)},Ao=Object.create(null),Eo=Object.freeze({createElement:se,createElementNS:ue,createTextNode:ce,createComment:le,insertBefore:fe,removeChild:pe,appendChild:de,parentNode:he,nextSibling:ve,tagName:ge,setTextContent:me,setAttribute:ye}),So={create:function(t,e){be(e)},update:function(t,e){t.data.ref!==e.data.ref&&(be(t,!0),be(e))},destroy:function(t){be(t,!0)}},Oo=new Bi("",{},[]),jo=["create","activate","update","remove","destroy"],No={create:$e,update:$e,destroy:function(t){$e(t,Oo)}},Do=Object.create(null),Io=[So,No],Ro={create:Oe,update:Oe},Lo={create:Ne, update:Ne},Po={create:Re,update:Re},Fo={create:Le,update:Le},qo=u(function(t){var e={},n=/;(?![^(]*\))/g,r=/:(.+)/;return t.split(n).forEach(function(t){if(t){var n=t.split(r);n.length>1&&(e[n[0].trim()]=n[1].trim())}}),e}),Mo=/^--/,Ho=/\s*!important$/,Bo=function(t,e,n){Mo.test(e)?t.style.setProperty(e,n):Ho.test(n)?t.style.setProperty(e,n.replace(Ho,""),"important"):t.style[Wo(e)]=n},Uo=["Webkit","Moz","ms"],Wo=u(function(t){if(po=po||document.createElement("div"),t=ui(t),"filter"!==t&&t in po.style)return t;for(var e=t.charAt(0).toUpperCase()+t.slice(1),n=0;n<Uo.length;n++){var r=Uo[n]+e;if(r in po.style)return r}}),zo={create:Ue,update:Ue},Vo=bi&&!xi,Xo="transition",Ko="animation",Jo="transition",Go="transitionend",Zo="animation",Yo="animationend";Vo&&(void 0===window.ontransitionend&&void 0!==window.onwebkittransitionend&&(Jo="WebkitTransition",Go="webkitTransitionEnd"),void 0===window.onanimationend&&void 0!==window.onwebkitanimationend&&(Zo="WebkitAnimation",Yo="webkitAnimationEnd"));var Qo=bi&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):setTimeout,ta=/\b(transform|all)(,|$)/,ea=u(function(t){return{enterClass:t+"-enter",leaveClass:t+"-leave",appearClass:t+"-enter",enterToClass:t+"-enter-to",leaveToClass:t+"-leave-to",appearToClass:t+"-enter-to",enterActiveClass:t+"-enter-active",leaveActiveClass:t+"-leave-active",appearActiveClass:t+"-enter-active"}}),na=bi?{create:rn,activate:rn,remove:function(t,e){t.data.show?e():tn(t,e)}}:{},ra=[Ro,Lo,Po,Fo,zo,na],ia=ra.concat(Io),oa=Te({nodeOps:Eo,modules:ia});xi&&document.addEventListener("selectionchange",function(){var t=document.activeElement;t&&t.vmodel&&ln(t,"input")});var aa={inserted:function(t,e,n){if("select"===n.tag){var r=function(){on(t,e,n.context)};r(),(wi||Ci)&&setTimeout(r,0)}else"textarea"!==n.tag&&"text"!==t.type||(t._vModifiers=e.modifiers,e.modifiers.lazy||(Ti||(t.addEventListener("compositionstart",un),t.addEventListener("compositionend",cn)),xi&&(t.vmodel=!0)))},componentUpdated:function(t,e,n){if("select"===n.tag){on(t,e,n.context);var r=t.multiple?e.value.some(function(e){return an(e,t.options)}):e.value!==e.oldValue&&an(e.value,t.options);r&&ln(t,"change")}}},sa={bind:function(t,e,n){var r=e.value;n=fn(n);var i=n.data&&n.data.transition,o=t.__vOriginalDisplay="none"===t.style.display?"":t.style.display;r&&i&&!xi?(n.data.show=!0,Qe(n,function(){t.style.display=o})):t.style.display=r?o:"none"},update:function(t,e,n){var r=e.value,i=e.oldValue;if(r!==i){n=fn(n);var o=n.data&&n.data.transition;o&&!xi?(n.data.show=!0,r?Qe(n,function(){t.style.display=t.__vOriginalDisplay}):tn(n,function(){t.style.display="none"})):t.style.display=r?t.__vOriginalDisplay:"none"}},unbind:function(t,e,n,r,i){i||(t.style.display=t.__vOriginalDisplay)}},ua={model:aa,show:sa},ca={name:String,appear:Boolean,css:Boolean,mode:String,type:String,enterClass:String,leaveClass:String,enterToClass:String,leaveToClass:String,enterActiveClass:String,leaveActiveClass:String,appearClass:String,appearActiveClass:String,appearToClass:String},la={name:"transition",props:ca,abstract:!0,render:function(t){var e=this,n=this.$slots.default;if(n&&(n=n.filter(function(t){return t.tag}),n.length)){var r=this.mode,i=n[0];if(vn(this.$vnode))return i;var o=pn(i);if(!o)return i;if(this._leaving)return hn(t,i);var a="__transition-"+this._uid+"-",u=o.key=null==o.key?a+o.tag:s(o.key)?0===String(o.key).indexOf(a)?o.key:a+o.key:o.key,c=(o.data||(o.data={})).transition=dn(this),l=this._vnode,p=pn(l);if(o.data.directives&&o.data.directives.some(function(t){return"show"===t.name})&&(o.data.show=!0),p&&p.data&&!gn(o,p)){var d=p&&(p.data.transition=f({},c));if("out-in"===r)return this._leaving=!0,it(d,"afterLeave",function(){e._leaving=!1,e.$forceUpdate()},u),hn(t,i);if("in-out"===r){var h,v=function(){h()};it(c,"afterEnter",v,u),it(c,"enterCancelled",v,u),it(d,"delayLeave",function(t){h=t},u)}}return i}}},fa=f({tag:String,moveClass:String},ca);delete fa.mode;var pa={props:fa,render:function(t){for(var e=this.tag||this.$vnode.data.tag||"span",n=Object.create(null),r=this.prevChildren=this.children,i=this.$slots.default||[],o=this.children=[],a=dn(this),s=0;s<i.length;s++){var u=i[s];if(u.tag)if(null!=u.key&&0!==String(u.key).indexOf("__vlist"))o.push(u),n[u.key]=u,(u.data||(u.data={})).transition=a;else;}if(r){for(var c=[],l=[],f=0;f<r.length;f++){var p=r[f];p.data.transition=a,p.data.pos=p.elm.getBoundingClientRect(),n[p.key]?c.push(p):l.push(p)}this.kept=t(e,null,c),this.removed=l}return t(e,null,o)},beforeUpdate:function(){this.__patch__(this._vnode,this.kept,!1,!0),this._vnode=this.kept},updated:function(){var t=this.prevChildren,e=this.moveClass||(this.name||"v")+"-move";if(t.length&&this.hasMove(t[0].elm,e)){t.forEach(mn),t.forEach(yn),t.forEach(bn);document.body.offsetHeight;t.forEach(function(t){if(t.data.moved){var n=t.elm,r=n.style;Xe(n,e),r.transform=r.WebkitTransform=r.transitionDuration="",n.addEventListener(Go,n._moveCb=function t(r){r&&!/transform$/.test(r.propertyName)||(n.removeEventListener(Go,t),n._moveCb=null,Ke(n,e))})}})}},methods:{hasMove:function(t,e){if(!Vo)return!1;if(null!=this._hasMove)return this._hasMove;Xe(t,e);var n=Ge(t);return Ke(t,e),this._hasMove=n.hasTransform}}},da={Transition:la,TransitionGroup:pa};Ut.config.isUnknownElement=oe,Ut.config.isReservedTag=ko,Ut.config.getTagNamespace=ie,Ut.config.mustUseProp=vo,f(Ut.options.directives,ua),f(Ut.options.components,da),Ut.prototype.__patch__=bi?oa:v,Ut.prototype.$mount=function(t,e){return t=t&&bi?ae(t):void 0,this._mount(t,e)},setTimeout(function(){gi.devtools&&Ai&&Ai.emit("init",Ut)},0);var ha,va=!!bi&&_n("\n","&#10;"),ga=i("area,base,br,col,embed,frame,hr,img,input,isindex,keygen,link,meta,param,source,track,wbr",!0),ma=i("colgroup,dd,dt,li,options,p,td,tfoot,th,thead,tr,source",!0),ya=i("address,article,aside,base,blockquote,body,caption,col,colgroup,dd,details,dialog,div,dl,dt,fieldset,figcaption,figure,footer,form,h1,h2,h3,h4,h5,h6,head,header,hgroup,hr,html,legend,li,menuitem,meta,optgroup,option,param,rp,rt,source,style,summary,tbody,td,tfoot,th,thead,title,tr,track",!0),ba=/([^\s"'<>\/=]+)/,_a=/(?:=)/,wa=[/"([^"]*)"+/.source,/'([^']*)'+/.source,/([^\s"'=<>`]+)/.source],xa=new RegExp("^\\s*"+ba.source+"(?:\\s*("+_a.source+")\\s*(?:"+wa.join("|")+"))?"),Ca="[a-zA-Z_][\\w\\-\\.]*",Ta="((?:"+Ca+"\\:)?"+Ca+")",$a=new RegExp("^<"+Ta),ka=/^\s*(\/?)>/,Aa=new RegExp("^<\\/"+Ta+"[^>]*>"),Ea=/^<!DOCTYPE [^>]+>/i,Sa=/^<!--/,Oa=/^<!\[/,ja=!1;"x".replace(/x(.)?/g,function(t,e){ja=""===e});var Na,Da,Ia,Ra,La,Pa,Fa,qa,Ma,Ha,Ba,Ua,Wa,za,Va,Xa,Ka,Ja,Ga,Za,Ya,Qa,ts,es,ns,rs=i("script,style",!0),is={},os=/&lt;/g,as=/&gt;/g,ss=/&#10;/g,us=/&amp;/g,cs=/&quot;/g,ls=/\{\{((?:.|\n)+?)\}\}/g,fs=/[-.*+?^${}()|[\]\/\\]/g,ps=u(function(t){var e=t[0].replace(fs,"\\$&"),n=t[1].replace(fs,"\\$&");return new RegExp(e+"((?:.|\\n)+?)"+n,"g")}),ds=/^v-|^@|^:/,hs=/(.*?)\s+(?:in|of)\s+(.*)/,vs=/\((\{[^}]*\}|[^,]*),([^,]*)(?:,([^,]*))?\)/,gs=/^:|^v-bind:/,ms=/^@|^v-on:/,ys=/:(.*)$/,bs=/\.[^.]+/g,_s=u(wn),ws=/^xmlns:NS\d+/,xs=/^NS\d+:/,Cs=u(sr),Ts=/^\s*([\w$_]+|\([^)]*?\))\s*=>|^function\s*\(/,$s=/^\s*[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*|\['.*?']|\[".*?"]|\[\d+]|\[[A-Za-z_$][\w$]*])*\s*$/,ks={esc:27,tab:9,enter:13,space:32,up:38,left:37,right:39,down:40,delete:[8,46]},As={stop:"$event.stopPropagation();",prevent:"$event.preventDefault();",self:"if($event.target !== $event.currentTarget)return;",ctrl:"if(!$event.ctrlKey)return;",shift:"if(!$event.shiftKey)return;",alt:"if(!$event.altKey)return;",meta:"if(!$event.metaKey)return;"},Es={bind:mr,cloak:v},Ss=(new RegExp("\\b"+"do,if,for,let,new,try,var,case,else,with,await,break,catch,class,const,super,throw,while,yield,delete,export,import,return,switch,default,extends,finally,continue,debugger,function,arguments".split(",").join("\\b|\\b")+"\\b"),{staticKeys:["staticClass"],transformNode:Hr,genData:Br}),Os={staticKeys:["staticStyle"],transformNode:Ur,genData:Wr},js=[Ss,Os],Ns={model:zr,text:Zr,html:Yr},Ds=Object.create(null),Is={expectHTML:!0,modules:js,staticKeys:g(js),directives:Ns,isReservedTag:ko,isUnaryTag:ga,mustUseProp:vo,getTagNamespace:ie,isPreTag:$o},Rs=u(function(t){var e=ae(t);return e&&e.innerHTML}),Ls=Ut.prototype.$mount;Ut.prototype.$mount=function(t,e){if(t=t&&ae(t),t===document.body||t===document.documentElement)return this;var n=this.$options;if(!n.render){var r=n.template;if(r)if("string"==typeof r)"#"===r.charAt(0)&&(r=Rs(r));else{if(!r.nodeType)return this;r=r.innerHTML}else t&&(r=ni(t));if(r){var i=ti(r,{warn:Oi,shouldDecodeNewlines:va,delimiters:n.delimiters},this),o=i.render,a=i.staticRenderFns;n.render=o,n.staticRenderFns=a}}return Ls.call(this,t,e)},Ut.compile=ti,t.exports=Ut}).call(e,n(8))},function(t,e){t.exports=function(t){return t.webpackPolyfill||(t.deprecate=function(){},t.paths=[],t.children||(t.children=[]),Object.defineProperty(t,"loaded",{enumerable:!0,get:function(){return t.l}}),Object.defineProperty(t,"id",{enumerable:!0,get:function(){return t.i}}),t.webpackPolyfill=1),t}},function(t,e,n){n(9),t.exports=n(10)}]);
laravel_laravel
2017-01-28
1078776e953d35bd67af0971fe78efa037d8fb83
public/css/app.css
6
@import url(https://fonts.googleapis.com/css?family=Raleway:300,400,600);/*! * Bootstrap v3.3.7 (http://getbootstrap.com) * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) */ /*! normalize.css v3.0.3 | MIT License | github.com/necolas/normalize.css */html{font-family:sans-serif;-ms-text-size-adjust:100%;-webkit-text-size-adjust:100%}body{margin:0}article,aside,details,figcaption,figure,footer,header,hgroup,main,menu,nav,section,summary{display:block}audio,canvas,progress,video{display:inline-block;vertical-align:baseline}audio:not([controls]){display:none;height:0}[hidden],template{display:none}a{background-color:transparent}a:active,a:hover{outline:0}abbr[title]{border-bottom:1px dotted}b,strong{font-weight:700}dfn{font-style:italic}h1{font-size:2em;margin:.67em 0}mark{background:#ff0;color:#000}small{font-size:80%}sub,sup{font-size:75%;line-height:0;position:relative;vertical-align:baseline}sup{top:-.5em}sub{bottom:-.25em}img{border:0}svg:not(:root){overflow:hidden}figure{margin:1em 40px}hr{box-sizing:content-box;height:0}pre{overflow:auto}code,kbd,pre,samp{font-family:monospace,monospace;font-size:1em}button,input,optgroup,select,textarea{color:inherit;font:inherit;margin:0}button{overflow:visible}button,select{text-transform:none}button,html input[type=button],input[type=reset],input[type=submit]{-webkit-appearance:button;cursor:pointer}button[disabled],html input[disabled]{cursor:default}button::-moz-focus-inner,input::-moz-focus-inner{border:0;padding:0}input{line-height:normal}input[type=checkbox],input[type=radio]{box-sizing:border-box;padding:0}input[type=number]::-webkit-inner-spin-button,input[type=number]::-webkit-outer-spin-button{height:auto}input[type=search]{-webkit-appearance:textfield;box-sizing:content-box}input[type=search]::-webkit-search-cancel-button,input[type=search]::-webkit-search-decoration{-webkit-appearance:none}fieldset{border:1px solid silver;margin:0 2px;padding:.35em .625em .75em}legend{border:0;padding:0}textarea{overflow:auto}optgroup{font-weight:700}table{border-collapse:collapse;border-spacing:0}td,th{padding:0} /*! Source: https://github.com/h5bp/html5-boilerplate/blob/master/src/css/main.css */@media print{*,:after,:before{background:transparent!important;color:#000!important;box-shadow:none!important;text-shadow:none!important}a,a:visited{text-decoration:underline}a[href]:after{content:" (" attr(href) ")"}abbr[title]:after{content:" (" attr(title) ")"}a[href^="#"]:after,a[href^="javascript:"]:after{content:""}blockquote,pre{border:1px solid #999;page-break-inside:avoid}thead{display:table-header-group}img,tr{page-break-inside:avoid}img{max-width:100%!important}h2,h3,p{orphans:3;widows:3}h2,h3{page-break-after:avoid}.navbar{display:none}.btn>.caret,.dropup>.btn>.caret{border-top-color:#000!important}.label{border:1px solid #000}.table{border-collapse:collapse!important}.table td,.table th{background-color:#fff!important}.table-bordered td,.table-bordered th{border:1px solid #ddd!important}}@font-face{font-family:Glyphicons Halflings;src:url(.//fonts/glyphicons-halflings-regular.eot?f4769f9bdb7466be65088239c12046d1);src:url(.//fonts/glyphicons-halflings-regular.eot?f4769f9bdb7466be65088239c12046d1) format("embedded-opentype"),url(.//fonts/glyphicons-halflings-regular.woff2?448c34a56d699c29117adc64c43affeb) format("woff2"),url(.//fonts/glyphicons-halflings-regular.woff?fa2772327f55d8198301fdb8bcfc8158) format("woff"),url(.//fonts/glyphicons-halflings-regular.ttf?e18bbf611f2a2e43afc071aa2f4e1512) format("truetype"),url(.//fonts/glyphicons-halflings-regular.svg?89889688147bd7575d6327160d64e760) format("svg")}.glyphicon{position:relative;top:1px;display:inline-block;font-family:Glyphicons Halflings;font-style:normal;font-weight:400;line-height:1;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale}.glyphicon-asterisk:before{content:"*"}.glyphicon-plus:before{content:"+"}.glyphicon-eur:before,.glyphicon-euro:before{content:"\20AC"}.glyphicon-minus:before{content:"\2212"}.glyphicon-cloud:before{content:"\2601"}.glyphicon-envelope:before{content:"\2709"}.glyphicon-pencil:before{content:"\270F"}.glyphicon-glass:before{content:"\E001"}.glyphicon-music:before{content:"\E002"}.glyphicon-search:before{content:"\E003"}.glyphicon-heart:before{content:"\E005"}.glyphicon-star:before{content:"\E006"}.glyphicon-star-empty:before{content:"\E007"}.glyphicon-user:before{content:"\E008"}.glyphicon-film:before{content:"\E009"}.glyphicon-th-large:before{content:"\E010"}.glyphicon-th:before{content:"\E011"}.glyphicon-th-list:before{content:"\E012"}.glyphicon-ok:before{content:"\E013"}.glyphicon-remove:before{content:"\E014"}.glyphicon-zoom-in:before{content:"\E015"}.glyphicon-zoom-out:before{content:"\E016"}.glyphicon-off:before{content:"\E017"}.glyphicon-signal:before{content:"\E018"}.glyphicon-cog:before{content:"\E019"}.glyphicon-trash:before{content:"\E020"}.glyphicon-home:before{content:"\E021"}.glyphicon-file:before{content:"\E022"}.glyphicon-time:before{content:"\E023"}.glyphicon-road:before{content:"\E024"}.glyphicon-download-alt:before{content:"\E025"}.glyphicon-download:before{content:"\E026"}.glyphicon-upload:before{content:"\E027"}.glyphicon-inbox:before{content:"\E028"}.glyphicon-play-circle:before{content:"\E029"}.glyphicon-repeat:before{content:"\E030"}.glyphicon-refresh:before{content:"\E031"}.glyphicon-list-alt:before{content:"\E032"}.glyphicon-lock:before{content:"\E033"}.glyphicon-flag:before{content:"\E034"}.glyphicon-headphones:before{content:"\E035"}.glyphicon-volume-off:before{content:"\E036"}.glyphicon-volume-down:before{content:"\E037"}.glyphicon-volume-up:before{content:"\E038"}.glyphicon-qrcode:before{content:"\E039"}.glyphicon-barcode:before{content:"\E040"}.glyphicon-tag:before{content:"\E041"}.glyphicon-tags:before{content:"\E042"}.glyphicon-book:before{content:"\E043"}.glyphicon-bookmark:before{content:"\E044"}.glyphicon-print:before{content:"\E045"}.glyphicon-camera:before{content:"\E046"}.glyphicon-font:before{content:"\E047"}.glyphicon-bold:before{content:"\E048"}.glyphicon-italic:before{content:"\E049"}.glyphicon-text-height:before{content:"\E050"}.glyphicon-text-width:before{content:"\E051"}.glyphicon-align-left:before{content:"\E052"}.glyphicon-align-center:before{content:"\E053"}.glyphicon-align-right:before{content:"\E054"}.glyphicon-align-justify:before{content:"\E055"}.glyphicon-list:before{content:"\E056"}.glyphicon-indent-left:before{content:"\E057"}.glyphicon-indent-right:before{content:"\E058"}.glyphicon-facetime-video:before{content:"\E059"}.glyphicon-picture:before{content:"\E060"}.glyphicon-map-marker:before{content:"\E062"}.glyphicon-adjust:before{content:"\E063"}.glyphicon-tint:before{content:"\E064"}.glyphicon-edit:before{content:"\E065"}.glyphicon-share:before{content:"\E066"}.glyphicon-check:before{content:"\E067"}.glyphicon-move:before{content:"\E068"}.glyphicon-step-backward:before{content:"\E069"}.glyphicon-fast-backward:before{content:"\E070"}.glyphicon-backward:before{content:"\E071"}.glyphicon-play:before{content:"\E072"}.glyphicon-pause:before{content:"\E073"}.glyphicon-stop:before{content:"\E074"}.glyphicon-forward:before{content:"\E075"}.glyphicon-fast-forward:before{content:"\E076"}.glyphicon-step-forward:before{content:"\E077"}.glyphicon-eject:before{content:"\E078"}.glyphicon-chevron-left:before{content:"\E079"}.glyphicon-chevron-right:before{content:"\E080"}.glyphicon-plus-sign:before{content:"\E081"}.glyphicon-minus-sign:before{content:"\E082"}.glyphicon-remove-sign:before{content:"\E083"}.glyphicon-ok-sign:before{content:"\E084"}.glyphicon-question-sign:before{content:"\E085"}.glyphicon-info-sign:before{content:"\E086"}.glyphicon-screenshot:before{content:"\E087"}.glyphicon-remove-circle:before{content:"\E088"}.glyphicon-ok-circle:before{content:"\E089"}.glyphicon-ban-circle:before{content:"\E090"}.glyphicon-arrow-left:before{content:"\E091"}.glyphicon-arrow-right:before{content:"\E092"}.glyphicon-arrow-up:before{content:"\E093"}.glyphicon-arrow-down:before{content:"\E094"}.glyphicon-share-alt:before{content:"\E095"}.glyphicon-resize-full:before{content:"\E096"}.glyphicon-resize-small:before{content:"\E097"}.glyphicon-exclamation-sign:before{content:"\E101"}.glyphicon-gift:before{content:"\E102"}.glyphicon-leaf:before{content:"\E103"}.glyphicon-fire:before{content:"\E104"}.glyphicon-eye-open:before{content:"\E105"}.glyphicon-eye-close:before{content:"\E106"}.glyphicon-warning-sign:before{content:"\E107"}.glyphicon-plane:before{content:"\E108"}.glyphicon-calendar:before{content:"\E109"}.glyphicon-random:before{content:"\E110"}.glyphicon-comment:before{content:"\E111"}.glyphicon-magnet:before{content:"\E112"}.glyphicon-chevron-up:before{content:"\E113"}.glyphicon-chevron-down:before{content:"\E114"}.glyphicon-retweet:before{content:"\E115"}.glyphicon-shopping-cart:before{content:"\E116"}.glyphicon-folder-close:before{content:"\E117"}.glyphicon-folder-open:before{content:"\E118"}.glyphicon-resize-vertical:before{content:"\E119"}.glyphicon-resize-horizontal:before{content:"\E120"}.glyphicon-hdd:before{content:"\E121"}.glyphicon-bullhorn:before{content:"\E122"}.glyphicon-bell:before{content:"\E123"}.glyphicon-certificate:before{content:"\E124"}.glyphicon-thumbs-up:before{content:"\E125"}.glyphicon-thumbs-down:before{content:"\E126"}.glyphicon-hand-right:before{content:"\E127"}.glyphicon-hand-left:before{content:"\E128"}.glyphicon-hand-up:before{content:"\E129"}.glyphicon-hand-down:before{content:"\E130"}.glyphicon-circle-arrow-right:before{content:"\E131"}.glyphicon-circle-arrow-left:before{content:"\E132"}.glyphicon-circle-arrow-up:before{content:"\E133"}.glyphicon-circle-arrow-down:before{content:"\E134"}.glyphicon-globe:before{content:"\E135"}.glyphicon-wrench:before{content:"\E136"}.glyphicon-tasks:before{content:"\E137"}.glyphicon-filter:before{content:"\E138"}.glyphicon-briefcase:before{content:"\E139"}.glyphicon-fullscreen:before{content:"\E140"}.glyphicon-dashboard:before{content:"\E141"}.glyphicon-paperclip:before{content:"\E142"}.glyphicon-heart-empty:before{content:"\E143"}.glyphicon-link:before{content:"\E144"}.glyphicon-phone:before{content:"\E145"}.glyphicon-pushpin:before{content:"\E146"}.glyphicon-usd:before{content:"\E148"}.glyphicon-gbp:before{content:"\E149"}.glyphicon-sort:before{content:"\E150"}.glyphicon-sort-by-alphabet:before{content:"\E151"}.glyphicon-sort-by-alphabet-alt:before{content:"\E152"}.glyphicon-sort-by-order:before{content:"\E153"}.glyphicon-sort-by-order-alt:before{content:"\E154"}.glyphicon-sort-by-attributes:before{content:"\E155"}.glyphicon-sort-by-attributes-alt:before{content:"\E156"}.glyphicon-unchecked:before{content:"\E157"}.glyphicon-expand:before{content:"\E158"}.glyphicon-collapse-down:before{content:"\E159"}.glyphicon-collapse-up:before{content:"\E160"}.glyphicon-log-in:before{content:"\E161"}.glyphicon-flash:before{content:"\E162"}.glyphicon-log-out:before{content:"\E163"}.glyphicon-new-window:before{content:"\E164"}.glyphicon-record:before{content:"\E165"}.glyphicon-save:before{content:"\E166"}.glyphicon-open:before{content:"\E167"}.glyphicon-saved:before{content:"\E168"}.glyphicon-import:before{content:"\E169"}.glyphicon-export:before{content:"\E170"}.glyphicon-send:before{content:"\E171"}.glyphicon-floppy-disk:before{content:"\E172"}.glyphicon-floppy-saved:before{content:"\E173"}.glyphicon-floppy-remove:before{content:"\E174"}.glyphicon-floppy-save:before{content:"\E175"}.glyphicon-floppy-open:before{content:"\E176"}.glyphicon-credit-card:before{content:"\E177"}.glyphicon-transfer:before{content:"\E178"}.glyphicon-cutlery:before{content:"\E179"}.glyphicon-header:before{content:"\E180"}.glyphicon-compressed:before{content:"\E181"}.glyphicon-earphone:before{content:"\E182"}.glyphicon-phone-alt:before{content:"\E183"}.glyphicon-tower:before{content:"\E184"}.glyphicon-stats:before{content:"\E185"}.glyphicon-sd-video:before{content:"\E186"}.glyphicon-hd-video:before{content:"\E187"}.glyphicon-subtitles:before{content:"\E188"}.glyphicon-sound-stereo:before{content:"\E189"}.glyphicon-sound-dolby:before{content:"\E190"}.glyphicon-sound-5-1:before{content:"\E191"}.glyphicon-sound-6-1:before{content:"\E192"}.glyphicon-sound-7-1:before{content:"\E193"}.glyphicon-copyright-mark:before{content:"\E194"}.glyphicon-registration-mark:before{content:"\E195"}.glyphicon-cloud-download:before{content:"\E197"}.glyphicon-cloud-upload:before{content:"\E198"}.glyphicon-tree-conifer:before{content:"\E199"}.glyphicon-tree-deciduous:before{content:"\E200"}.glyphicon-cd:before{content:"\E201"}.glyphicon-save-file:before{content:"\E202"}.glyphicon-open-file:before{content:"\E203"}.glyphicon-level-up:before{content:"\E204"}.glyphicon-copy:before{content:"\E205"}.glyphicon-paste:before{content:"\E206"}.glyphicon-alert:before{content:"\E209"}.glyphicon-equalizer:before{content:"\E210"}.glyphicon-king:before{content:"\E211"}.glyphicon-queen:before{content:"\E212"}.glyphicon-pawn:before{content:"\E213"}.glyphicon-bishop:before{content:"\E214"}.glyphicon-knight:before{content:"\E215"}.glyphicon-baby-formula:before{content:"\E216"}.glyphicon-tent:before{content:"\26FA"}.glyphicon-blackboard:before{content:"\E218"}.glyphicon-bed:before{content:"\E219"}.glyphicon-apple:before{content:"\F8FF"}.glyphicon-erase:before{content:"\E221"}.glyphicon-hourglass:before{content:"\231B"}.glyphicon-lamp:before{content:"\E223"}.glyphicon-duplicate:before{content:"\E224"}.glyphicon-piggy-bank:before{content:"\E225"}.glyphicon-scissors:before{content:"\E226"}.glyphicon-bitcoin:before,.glyphicon-btc:before,.glyphicon-xbt:before{content:"\E227"}.glyphicon-jpy:before,.glyphicon-yen:before{content:"\A5"}.glyphicon-rub:before,.glyphicon-ruble:before{content:"\20BD"}.glyphicon-scale:before{content:"\E230"}.glyphicon-ice-lolly:before{content:"\E231"}.glyphicon-ice-lolly-tasted:before{content:"\E232"}.glyphicon-education:before{content:"\E233"}.glyphicon-option-horizontal:before{content:"\E234"}.glyphicon-option-vertical:before{content:"\E235"}.glyphicon-menu-hamburger:before{content:"\E236"}.glyphicon-modal-window:before{content:"\E237"}.glyphicon-oil:before{content:"\E238"}.glyphicon-grain:before{content:"\E239"}.glyphicon-sunglasses:before{content:"\E240"}.glyphicon-text-size:before{content:"\E241"}.glyphicon-text-color:before{content:"\E242"}.glyphicon-text-background:before{content:"\E243"}.glyphicon-object-align-top:before{content:"\E244"}.glyphicon-object-align-bottom:before{content:"\E245"}.glyphicon-object-align-horizontal:before{content:"\E246"}.glyphicon-object-align-left:before{content:"\E247"}.glyphicon-object-align-vertical:before{content:"\E248"}.glyphicon-object-align-right:before{content:"\E249"}.glyphicon-triangle-right:before{content:"\E250"}.glyphicon-triangle-left:before{content:"\E251"}.glyphicon-triangle-bottom:before{content:"\E252"}.glyphicon-triangle-top:before{content:"\E253"}.glyphicon-console:before{content:"\E254"}.glyphicon-superscript:before{content:"\E255"}.glyphicon-subscript:before{content:"\E256"}.glyphicon-menu-left:before{content:"\E257"}.glyphicon-menu-right:before{content:"\E258"}.glyphicon-menu-down:before{content:"\E259"}.glyphicon-menu-up:before{content:"\E260"}*,:after,:before{box-sizing:border-box}html{font-size:10px;-webkit-tap-highlight-color:transparent}body{font-family:Raleway,sans-serif;font-size:14px;line-height:1.6;color:#636b6f;background-color:#f5f8fa}button,input,select,textarea{font-family:inherit;font-size:inherit;line-height:inherit}a{color:#3097d1;text-decoration:none}a:focus,a:hover{color:#216a94;text-decoration:underline}a:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}figure{margin:0}img{vertical-align:middle}.img-responsive{display:block;max-width:100%;height:auto}.img-rounded{border-radius:6px}.img-thumbnail{padding:4px;line-height:1.6;background-color:#f5f8fa;border:1px solid #ddd;border-radius:4px;-webkit-transition:all .2s ease-in-out;transition:all .2s ease-in-out;display:inline-block;max-width:100%;height:auto}.img-circle{border-radius:50%}hr{margin-top:22px;margin-bottom:22px;border:0;border-top:1px solid #eee}.sr-only{position:absolute;width:1px;height:1px;margin:-1px;padding:0;overflow:hidden;clip:rect(0,0,0,0);border:0}.sr-only-focusable:active,.sr-only-focusable:focus{position:static;width:auto;height:auto;margin:0;overflow:visible;clip:auto}[role=button]{cursor:pointer}.h1,.h2,.h3,.h4,.h5,.h6,h1,h2,h3,h4,h5,h6{font-family:inherit;font-weight:500;line-height:1.1;color:inherit}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-weight:400;line-height:1;color:#777}.h1,.h2,.h3,h1,h2,h3{margin-top:22px;margin-bottom:11px}.h1 .small,.h1 small,.h2 .small,.h2 small,.h3 .small,.h3 small,h1 .small,h1 small,h2 .small,h2 small,h3 .small,h3 small{font-size:65%}.h4,.h5,.h6,h4,h5,h6{margin-top:11px;margin-bottom:11px}.h4 .small,.h4 small,.h5 .small,.h5 small,.h6 .small,.h6 small,h4 .small,h4 small,h5 .small,h5 small,h6 .small,h6 small{font-size:75%}.h1,h1{font-size:36px}.h2,h2{font-size:30px}.h3,h3{font-size:24px}.h4,h4{font-size:18px}.h5,h5{font-size:14px}.h6,h6{font-size:12px}p{margin:0 0 11px}.lead{margin-bottom:22px;font-size:16px;font-weight:300;line-height:1.4}@media (min-width:768px){.lead{font-size:21px}}.small,small{font-size:85%}.mark,mark{background-color:#fcf8e3;padding:.2em}.text-left{text-align:left}.text-right{text-align:right}.text-center{text-align:center}.text-justify{text-align:justify}.text-nowrap{white-space:nowrap}.text-lowercase{text-transform:lowercase}.initialism,.text-uppercase{text-transform:uppercase}.text-capitalize{text-transform:capitalize}.text-muted{color:#777}.text-primary{color:#3097d1}a.text-primary:focus,a.text-primary:hover{color:#2579a9}.text-success{color:#3c763d}a.text-success:focus,a.text-success:hover{color:#2b542c}.text-info{color:#31708f}a.text-info:focus,a.text-info:hover{color:#245269}.text-warning{color:#8a6d3b}a.text-warning:focus,a.text-warning:hover{color:#66512c}.text-danger{color:#a94442}a.text-danger:focus,a.text-danger:hover{color:#843534}.bg-primary{color:#fff;background-color:#3097d1}a.bg-primary:focus,a.bg-primary:hover{background-color:#2579a9}.bg-success{background-color:#dff0d8}a.bg-success:focus,a.bg-success:hover{background-color:#c1e2b3}.bg-info{background-color:#d9edf7}a.bg-info:focus,a.bg-info:hover{background-color:#afd9ee}.bg-warning{background-color:#fcf8e3}a.bg-warning:focus,a.bg-warning:hover{background-color:#f7ecb5}.bg-danger{background-color:#f2dede}a.bg-danger:focus,a.bg-danger:hover{background-color:#e4b9b9}.page-header{padding-bottom:10px;margin:44px 0 22px;border-bottom:1px solid #eee}ol,ul{margin-top:0;margin-bottom:11px}ol ol,ol ul,ul ol,ul ul{margin-bottom:0}.list-inline,.list-unstyled{padding-left:0;list-style:none}.list-inline{margin-left:-5px}.list-inline>li{display:inline-block;padding-left:5px;padding-right:5px}dl{margin-top:0;margin-bottom:22px}dd,dt{line-height:1.6}dt{font-weight:700}dd{margin-left:0}.dl-horizontal dd:after,.dl-horizontal dd:before{content:" ";display:table}.dl-horizontal dd:after{clear:both}@media (min-width:768px){.dl-horizontal dt{float:left;width:160px;clear:left;text-align:right;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.dl-horizontal dd{margin-left:180px}}abbr[data-original-title],abbr[title]{cursor:help;border-bottom:1px dotted #777}.initialism{font-size:90%}blockquote{padding:11px 22px;margin:0 0 22px;font-size:17.5px;border-left:5px solid #eee}blockquote ol:last-child,blockquote p:last-child,blockquote ul:last-child{margin-bottom:0}blockquote .small,blockquote footer,blockquote small{display:block;font-size:80%;line-height:1.6;color:#777}blockquote .small:before,blockquote footer:before,blockquote small:before{content:"\2014 \A0"}.blockquote-reverse,blockquote.pull-right{padding-right:15px;padding-left:0;border-right:5px solid #eee;border-left:0;text-align:right}.blockquote-reverse .small:before,.blockquote-reverse footer:before,.blockquote-reverse small:before,blockquote.pull-right .small:before,blockquote.pull-right footer:before,blockquote.pull-right small:before{content:""}.blockquote-reverse .small:after,.blockquote-reverse footer:after,.blockquote-reverse small:after,blockquote.pull-right .small:after,blockquote.pull-right footer:after,blockquote.pull-right small:after{content:"\A0 \2014"}address{margin-bottom:22px;font-style:normal;line-height:1.6}code,kbd,pre,samp{font-family:Menlo,Monaco,Consolas,Courier New,monospace}code{color:#c7254e;background-color:#f9f2f4;border-radius:4px}code,kbd{padding:2px 4px;font-size:90%}kbd{color:#fff;background-color:#333;border-radius:3px;box-shadow:inset 0 -1px 0 rgba(0,0,0,.25)}kbd kbd{padding:0;font-size:100%;font-weight:700;box-shadow:none}pre{display:block;padding:10.5px;margin:0 0 11px;font-size:13px;line-height:1.6;word-break:break-all;word-wrap:break-word;color:#333;background-color:#f5f5f5;border:1px solid #ccc;border-radius:4px}pre code{padding:0;font-size:inherit;color:inherit;white-space:pre-wrap;background-color:transparent;border-radius:0}.pre-scrollable{max-height:340px;overflow-y:scroll}.container{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.container:after,.container:before{content:" ";display:table}.container:after{clear:both}@media (min-width:768px){.container{width:750px}}@media (min-width:992px){.container{width:970px}}@media (min-width:1200px){.container{width:1170px}}.container-fluid{margin-right:auto;margin-left:auto;padding-left:15px;padding-right:15px}.container-fluid:after,.container-fluid:before{content:" ";display:table}.container-fluid:after{clear:both}.row{margin-left:-15px;margin-right:-15px}.row:after,.row:before{content:" ";display:table}.row:after{clear:both}.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12,.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12,.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12,.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{position:relative;min-height:1px;padding-left:15px;padding-right:15px}.col-xs-1,.col-xs-2,.col-xs-3,.col-xs-4,.col-xs-5,.col-xs-6,.col-xs-7,.col-xs-8,.col-xs-9,.col-xs-10,.col-xs-11,.col-xs-12{float:left}.col-xs-1{width:8.33333%}.col-xs-2{width:16.66667%}.col-xs-3{width:25%}.col-xs-4{width:33.33333%}.col-xs-5{width:41.66667%}.col-xs-6{width:50%}.col-xs-7{width:58.33333%}.col-xs-8{width:66.66667%}.col-xs-9{width:75%}.col-xs-10{width:83.33333%}.col-xs-11{width:91.66667%}.col-xs-12{width:100%}.col-xs-pull-0{right:auto}.col-xs-pull-1{right:8.33333%}.col-xs-pull-2{right:16.66667%}.col-xs-pull-3{right:25%}.col-xs-pull-4{right:33.33333%}.col-xs-pull-5{right:41.66667%}.col-xs-pull-6{right:50%}.col-xs-pull-7{right:58.33333%}.col-xs-pull-8{right:66.66667%}.col-xs-pull-9{right:75%}.col-xs-pull-10{right:83.33333%}.col-xs-pull-11{right:91.66667%}.col-xs-pull-12{right:100%}.col-xs-push-0{left:auto}.col-xs-push-1{left:8.33333%}.col-xs-push-2{left:16.66667%}.col-xs-push-3{left:25%}.col-xs-push-4{left:33.33333%}.col-xs-push-5{left:41.66667%}.col-xs-push-6{left:50%}.col-xs-push-7{left:58.33333%}.col-xs-push-8{left:66.66667%}.col-xs-push-9{left:75%}.col-xs-push-10{left:83.33333%}.col-xs-push-11{left:91.66667%}.col-xs-push-12{left:100%}.col-xs-offset-0{margin-left:0}.col-xs-offset-1{margin-left:8.33333%}.col-xs-offset-2{margin-left:16.66667%}.col-xs-offset-3{margin-left:25%}.col-xs-offset-4{margin-left:33.33333%}.col-xs-offset-5{margin-left:41.66667%}.col-xs-offset-6{margin-left:50%}.col-xs-offset-7{margin-left:58.33333%}.col-xs-offset-8{margin-left:66.66667%}.col-xs-offset-9{margin-left:75%}.col-xs-offset-10{margin-left:83.33333%}.col-xs-offset-11{margin-left:91.66667%}.col-xs-offset-12{margin-left:100%}@media (min-width:768px){.col-sm-1,.col-sm-2,.col-sm-3,.col-sm-4,.col-sm-5,.col-sm-6,.col-sm-7,.col-sm-8,.col-sm-9,.col-sm-10,.col-sm-11,.col-sm-12{float:left}.col-sm-1{width:8.33333%}.col-sm-2{width:16.66667%}.col-sm-3{width:25%}.col-sm-4{width:33.33333%}.col-sm-5{width:41.66667%}.col-sm-6{width:50%}.col-sm-7{width:58.33333%}.col-sm-8{width:66.66667%}.col-sm-9{width:75%}.col-sm-10{width:83.33333%}.col-sm-11{width:91.66667%}.col-sm-12{width:100%}.col-sm-pull-0{right:auto}.col-sm-pull-1{right:8.33333%}.col-sm-pull-2{right:16.66667%}.col-sm-pull-3{right:25%}.col-sm-pull-4{right:33.33333%}.col-sm-pull-5{right:41.66667%}.col-sm-pull-6{right:50%}.col-sm-pull-7{right:58.33333%}.col-sm-pull-8{right:66.66667%}.col-sm-pull-9{right:75%}.col-sm-pull-10{right:83.33333%}.col-sm-pull-11{right:91.66667%}.col-sm-pull-12{right:100%}.col-sm-push-0{left:auto}.col-sm-push-1{left:8.33333%}.col-sm-push-2{left:16.66667%}.col-sm-push-3{left:25%}.col-sm-push-4{left:33.33333%}.col-sm-push-5{left:41.66667%}.col-sm-push-6{left:50%}.col-sm-push-7{left:58.33333%}.col-sm-push-8{left:66.66667%}.col-sm-push-9{left:75%}.col-sm-push-10{left:83.33333%}.col-sm-push-11{left:91.66667%}.col-sm-push-12{left:100%}.col-sm-offset-0{margin-left:0}.col-sm-offset-1{margin-left:8.33333%}.col-sm-offset-2{margin-left:16.66667%}.col-sm-offset-3{margin-left:25%}.col-sm-offset-4{margin-left:33.33333%}.col-sm-offset-5{margin-left:41.66667%}.col-sm-offset-6{margin-left:50%}.col-sm-offset-7{margin-left:58.33333%}.col-sm-offset-8{margin-left:66.66667%}.col-sm-offset-9{margin-left:75%}.col-sm-offset-10{margin-left:83.33333%}.col-sm-offset-11{margin-left:91.66667%}.col-sm-offset-12{margin-left:100%}}@media (min-width:992px){.col-md-1,.col-md-2,.col-md-3,.col-md-4,.col-md-5,.col-md-6,.col-md-7,.col-md-8,.col-md-9,.col-md-10,.col-md-11,.col-md-12{float:left}.col-md-1{width:8.33333%}.col-md-2{width:16.66667%}.col-md-3{width:25%}.col-md-4{width:33.33333%}.col-md-5{width:41.66667%}.col-md-6{width:50%}.col-md-7{width:58.33333%}.col-md-8{width:66.66667%}.col-md-9{width:75%}.col-md-10{width:83.33333%}.col-md-11{width:91.66667%}.col-md-12{width:100%}.col-md-pull-0{right:auto}.col-md-pull-1{right:8.33333%}.col-md-pull-2{right:16.66667%}.col-md-pull-3{right:25%}.col-md-pull-4{right:33.33333%}.col-md-pull-5{right:41.66667%}.col-md-pull-6{right:50%}.col-md-pull-7{right:58.33333%}.col-md-pull-8{right:66.66667%}.col-md-pull-9{right:75%}.col-md-pull-10{right:83.33333%}.col-md-pull-11{right:91.66667%}.col-md-pull-12{right:100%}.col-md-push-0{left:auto}.col-md-push-1{left:8.33333%}.col-md-push-2{left:16.66667%}.col-md-push-3{left:25%}.col-md-push-4{left:33.33333%}.col-md-push-5{left:41.66667%}.col-md-push-6{left:50%}.col-md-push-7{left:58.33333%}.col-md-push-8{left:66.66667%}.col-md-push-9{left:75%}.col-md-push-10{left:83.33333%}.col-md-push-11{left:91.66667%}.col-md-push-12{left:100%}.col-md-offset-0{margin-left:0}.col-md-offset-1{margin-left:8.33333%}.col-md-offset-2{margin-left:16.66667%}.col-md-offset-3{margin-left:25%}.col-md-offset-4{margin-left:33.33333%}.col-md-offset-5{margin-left:41.66667%}.col-md-offset-6{margin-left:50%}.col-md-offset-7{margin-left:58.33333%}.col-md-offset-8{margin-left:66.66667%}.col-md-offset-9{margin-left:75%}.col-md-offset-10{margin-left:83.33333%}.col-md-offset-11{margin-left:91.66667%}.col-md-offset-12{margin-left:100%}}@media (min-width:1200px){.col-lg-1,.col-lg-2,.col-lg-3,.col-lg-4,.col-lg-5,.col-lg-6,.col-lg-7,.col-lg-8,.col-lg-9,.col-lg-10,.col-lg-11,.col-lg-12{float:left}.col-lg-1{width:8.33333%}.col-lg-2{width:16.66667%}.col-lg-3{width:25%}.col-lg-4{width:33.33333%}.col-lg-5{width:41.66667%}.col-lg-6{width:50%}.col-lg-7{width:58.33333%}.col-lg-8{width:66.66667%}.col-lg-9{width:75%}.col-lg-10{width:83.33333%}.col-lg-11{width:91.66667%}.col-lg-12{width:100%}.col-lg-pull-0{right:auto}.col-lg-pull-1{right:8.33333%}.col-lg-pull-2{right:16.66667%}.col-lg-pull-3{right:25%}.col-lg-pull-4{right:33.33333%}.col-lg-pull-5{right:41.66667%}.col-lg-pull-6{right:50%}.col-lg-pull-7{right:58.33333%}.col-lg-pull-8{right:66.66667%}.col-lg-pull-9{right:75%}.col-lg-pull-10{right:83.33333%}.col-lg-pull-11{right:91.66667%}.col-lg-pull-12{right:100%}.col-lg-push-0{left:auto}.col-lg-push-1{left:8.33333%}.col-lg-push-2{left:16.66667%}.col-lg-push-3{left:25%}.col-lg-push-4{left:33.33333%}.col-lg-push-5{left:41.66667%}.col-lg-push-6{left:50%}.col-lg-push-7{left:58.33333%}.col-lg-push-8{left:66.66667%}.col-lg-push-9{left:75%}.col-lg-push-10{left:83.33333%}.col-lg-push-11{left:91.66667%}.col-lg-push-12{left:100%}.col-lg-offset-0{margin-left:0}.col-lg-offset-1{margin-left:8.33333%}.col-lg-offset-2{margin-left:16.66667%}.col-lg-offset-3{margin-left:25%}.col-lg-offset-4{margin-left:33.33333%}.col-lg-offset-5{margin-left:41.66667%}.col-lg-offset-6{margin-left:50%}.col-lg-offset-7{margin-left:58.33333%}.col-lg-offset-8{margin-left:66.66667%}.col-lg-offset-9{margin-left:75%}.col-lg-offset-10{margin-left:83.33333%}.col-lg-offset-11{margin-left:91.66667%}.col-lg-offset-12{margin-left:100%}}table{background-color:transparent}caption{padding-top:8px;padding-bottom:8px;color:#777}caption,th{text-align:left}.table{width:100%;max-width:100%;margin-bottom:22px}.table>tbody>tr>td,.table>tbody>tr>th,.table>tfoot>tr>td,.table>tfoot>tr>th,.table>thead>tr>td,.table>thead>tr>th{padding:8px;line-height:1.6;vertical-align:top;border-top:1px solid #ddd}.table>thead>tr>th{vertical-align:bottom;border-bottom:2px solid #ddd}.table>caption+thead>tr:first-child>td,.table>caption+thead>tr:first-child>th,.table>colgroup+thead>tr:first-child>td,.table>colgroup+thead>tr:first-child>th,.table>thead:first-child>tr:first-child>td,.table>thead:first-child>tr:first-child>th{border-top:0}.table>tbody+tbody{border-top:2px solid #ddd}.table .table{background-color:#f5f8fa}.table-condensed>tbody>tr>td,.table-condensed>tbody>tr>th,.table-condensed>tfoot>tr>td,.table-condensed>tfoot>tr>th,.table-condensed>thead>tr>td,.table-condensed>thead>tr>th{padding:5px}.table-bordered,.table-bordered>tbody>tr>td,.table-bordered>tbody>tr>th,.table-bordered>tfoot>tr>td,.table-bordered>tfoot>tr>th,.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border:1px solid #ddd}.table-bordered>thead>tr>td,.table-bordered>thead>tr>th{border-bottom-width:2px}.table-striped>tbody>tr:nth-of-type(odd){background-color:#f9f9f9}.table-hover>tbody>tr:hover{background-color:#f5f5f5}table col[class*=col-]{position:static;float:none;display:table-column}table td[class*=col-],table th[class*=col-]{position:static;float:none;display:table-cell}.table>tbody>tr.active>td,.table>tbody>tr.active>th,.table>tbody>tr>td.active,.table>tbody>tr>th.active,.table>tfoot>tr.active>td,.table>tfoot>tr.active>th,.table>tfoot>tr>td.active,.table>tfoot>tr>th.active,.table>thead>tr.active>td,.table>thead>tr.active>th,.table>thead>tr>td.active,.table>thead>tr>th.active{background-color:#f5f5f5}.table-hover>tbody>tr.active:hover>td,.table-hover>tbody>tr.active:hover>th,.table-hover>tbody>tr:hover>.active,.table-hover>tbody>tr>td.active:hover,.table-hover>tbody>tr>th.active:hover{background-color:#e8e8e8}.table>tbody>tr.success>td,.table>tbody>tr.success>th,.table>tbody>tr>td.success,.table>tbody>tr>th.success,.table>tfoot>tr.success>td,.table>tfoot>tr.success>th,.table>tfoot>tr>td.success,.table>tfoot>tr>th.success,.table>thead>tr.success>td,.table>thead>tr.success>th,.table>thead>tr>td.success,.table>thead>tr>th.success{background-color:#dff0d8}.table-hover>tbody>tr.success:hover>td,.table-hover>tbody>tr.success:hover>th,.table-hover>tbody>tr:hover>.success,.table-hover>tbody>tr>td.success:hover,.table-hover>tbody>tr>th.success:hover{background-color:#d0e9c6}.table>tbody>tr.info>td,.table>tbody>tr.info>th,.table>tbody>tr>td.info,.table>tbody>tr>th.info,.table>tfoot>tr.info>td,.table>tfoot>tr.info>th,.table>tfoot>tr>td.info,.table>tfoot>tr>th.info,.table>thead>tr.info>td,.table>thead>tr.info>th,.table>thead>tr>td.info,.table>thead>tr>th.info{background-color:#d9edf7}.table-hover>tbody>tr.info:hover>td,.table-hover>tbody>tr.info:hover>th,.table-hover>tbody>tr:hover>.info,.table-hover>tbody>tr>td.info:hover,.table-hover>tbody>tr>th.info:hover{background-color:#c4e3f3}.table>tbody>tr.warning>td,.table>tbody>tr.warning>th,.table>tbody>tr>td.warning,.table>tbody>tr>th.warning,.table>tfoot>tr.warning>td,.table>tfoot>tr.warning>th,.table>tfoot>tr>td.warning,.table>tfoot>tr>th.warning,.table>thead>tr.warning>td,.table>thead>tr.warning>th,.table>thead>tr>td.warning,.table>thead>tr>th.warning{background-color:#fcf8e3}.table-hover>tbody>tr.warning:hover>td,.table-hover>tbody>tr.warning:hover>th,.table-hover>tbody>tr:hover>.warning,.table-hover>tbody>tr>td.warning:hover,.table-hover>tbody>tr>th.warning:hover{background-color:#faf2cc}.table>tbody>tr.danger>td,.table>tbody>tr.danger>th,.table>tbody>tr>td.danger,.table>tbody>tr>th.danger,.table>tfoot>tr.danger>td,.table>tfoot>tr.danger>th,.table>tfoot>tr>td.danger,.table>tfoot>tr>th.danger,.table>thead>tr.danger>td,.table>thead>tr.danger>th,.table>thead>tr>td.danger,.table>thead>tr>th.danger{background-color:#f2dede}.table-hover>tbody>tr.danger:hover>td,.table-hover>tbody>tr.danger:hover>th,.table-hover>tbody>tr:hover>.danger,.table-hover>tbody>tr>td.danger:hover,.table-hover>tbody>tr>th.danger:hover{background-color:#ebcccc}.table-responsive{overflow-x:auto;min-height:.01%}@media screen and (max-width:767px){.table-responsive{width:100%;margin-bottom:16.5px;overflow-y:hidden;-ms-overflow-style:-ms-autohiding-scrollbar;border:1px solid #ddd}.table-responsive>.table{margin-bottom:0}.table-responsive>.table>tbody>tr>td,.table-responsive>.table>tbody>tr>th,.table-responsive>.table>tfoot>tr>td,.table-responsive>.table>tfoot>tr>th,.table-responsive>.table>thead>tr>td,.table-responsive>.table>thead>tr>th{white-space:nowrap}.table-responsive>.table-bordered{border:0}.table-responsive>.table-bordered>tbody>tr>td:first-child,.table-responsive>.table-bordered>tbody>tr>th:first-child,.table-responsive>.table-bordered>tfoot>tr>td:first-child,.table-responsive>.table-bordered>tfoot>tr>th:first-child,.table-responsive>.table-bordered>thead>tr>td:first-child,.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.table-responsive>.table-bordered>tbody>tr>td:last-child,.table-responsive>.table-bordered>tbody>tr>th:last-child,.table-responsive>.table-bordered>tfoot>tr>td:last-child,.table-responsive>.table-bordered>tfoot>tr>th:last-child,.table-responsive>.table-bordered>thead>tr>td:last-child,.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.table-responsive>.table-bordered>tbody>tr:last-child>td,.table-responsive>.table-bordered>tbody>tr:last-child>th,.table-responsive>.table-bordered>tfoot>tr:last-child>td,.table-responsive>.table-bordered>tfoot>tr:last-child>th{border-bottom:0}}fieldset{margin:0;min-width:0}fieldset,legend{padding:0;border:0}legend{display:block;width:100%;margin-bottom:22px;font-size:21px;line-height:inherit;color:#333;border-bottom:1px solid #e5e5e5}label{display:inline-block;max-width:100%;margin-bottom:5px;font-weight:700}input[type=search]{box-sizing:border-box}input[type=checkbox],input[type=radio]{margin:4px 0 0;margin-top:1px\9;line-height:normal}input[type=file]{display:block}input[type=range]{display:block;width:100%}select[multiple],select[size]{height:auto}input[type=checkbox]:focus,input[type=file]:focus,input[type=radio]:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}output{padding-top:7px}.form-control,output{display:block;font-size:14px;line-height:1.6;color:#555}.form-control{width:100%;height:36px;padding:6px 12px;background-color:#fff;background-image:none;border:1px solid #ccd0d2;border-radius:4px;box-shadow:inset 0 1px 1px rgba(0,0,0,.075);-webkit-transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out;transition:border-color .15s ease-in-out,box-shadow .15s ease-in-out}.form-control:focus{border-color:#98cbe8;outline:0;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgba(152,203,232,.6)}.form-control::-moz-placeholder{color:#b1b7ba;opacity:1}.form-control:-ms-input-placeholder{color:#b1b7ba}.form-control::-webkit-input-placeholder{color:#b1b7ba}.form-control::-ms-expand{border:0;background-color:transparent}.form-control[disabled],.form-control[readonly],fieldset[disabled] .form-control{background-color:#eee;opacity:1}.form-control[disabled],fieldset[disabled] .form-control{cursor:not-allowed}textarea.form-control{height:auto}input[type=search]{-webkit-appearance:none}@media screen and (-webkit-min-device-pixel-ratio:0){input[type=date].form-control,input[type=datetime-local].form-control,input[type=month].form-control,input[type=time].form-control{line-height:36px}.input-group-sm>.input-group-btn>input[type=date].btn,.input-group-sm>.input-group-btn>input[type=datetime-local].btn,.input-group-sm>.input-group-btn>input[type=month].btn,.input-group-sm>.input-group-btn>input[type=time].btn,.input-group-sm>input[type=date].form-control,.input-group-sm>input[type=date].input-group-addon,.input-group-sm>input[type=datetime-local].form-control,.input-group-sm>input[type=datetime-local].input-group-addon,.input-group-sm>input[type=month].form-control,.input-group-sm>input[type=month].input-group-addon,.input-group-sm>input[type=time].form-control,.input-group-sm>input[type=time].input-group-addon,.input-group-sm input[type=date],.input-group-sm input[type=datetime-local],.input-group-sm input[type=month],.input-group-sm input[type=time],input[type=date].input-sm,input[type=datetime-local].input-sm,input[type=month].input-sm,input[type=time].input-sm{line-height:30px}.input-group-lg>.input-group-btn>input[type=date].btn,.input-group-lg>.input-group-btn>input[type=datetime-local].btn,.input-group-lg>.input-group-btn>input[type=month].btn,.input-group-lg>.input-group-btn>input[type=time].btn,.input-group-lg>input[type=date].form-control,.input-group-lg>input[type=date].input-group-addon,.input-group-lg>input[type=datetime-local].form-control,.input-group-lg>input[type=datetime-local].input-group-addon,.input-group-lg>input[type=month].form-control,.input-group-lg>input[type=month].input-group-addon,.input-group-lg>input[type=time].form-control,.input-group-lg>input[type=time].input-group-addon,.input-group-lg input[type=date],.input-group-lg input[type=datetime-local],.input-group-lg input[type=month],.input-group-lg input[type=time],input[type=date].input-lg,input[type=datetime-local].input-lg,input[type=month].input-lg,input[type=time].input-lg{line-height:46px}}.form-group{margin-bottom:15px}.checkbox,.radio{position:relative;display:block;margin-top:10px;margin-bottom:10px}.checkbox label,.radio label{min-height:22px;padding-left:20px;margin-bottom:0;font-weight:400;cursor:pointer}.checkbox-inline input[type=checkbox],.checkbox input[type=checkbox],.radio-inline input[type=radio],.radio input[type=radio]{position:absolute;margin-left:-20px;margin-top:4px\9}.checkbox+.checkbox,.radio+.radio{margin-top:-5px}.checkbox-inline,.radio-inline{position:relative;display:inline-block;padding-left:20px;margin-bottom:0;vertical-align:middle;font-weight:400;cursor:pointer}.checkbox-inline+.checkbox-inline,.radio-inline+.radio-inline{margin-top:0;margin-left:10px}.checkbox-inline.disabled,.checkbox.disabled label,.radio-inline.disabled,.radio.disabled label,fieldset[disabled] .checkbox-inline,fieldset[disabled] .checkbox label,fieldset[disabled] .radio-inline,fieldset[disabled] .radio label,fieldset[disabled] input[type=checkbox],fieldset[disabled] input[type=radio],input[type=checkbox].disabled,input[type=checkbox][disabled],input[type=radio].disabled,input[type=radio][disabled]{cursor:not-allowed}.form-control-static{padding-top:7px;padding-bottom:7px;margin-bottom:0;min-height:36px}.form-control-static.input-lg,.form-control-static.input-sm,.input-group-lg>.form-control-static.form-control,.input-group-lg>.form-control-static.input-group-addon,.input-group-lg>.input-group-btn>.form-control-static.btn,.input-group-sm>.form-control-static.form-control,.input-group-sm>.form-control-static.input-group-addon,.input-group-sm>.input-group-btn>.form-control-static.btn{padding-left:0;padding-right:0}.input-group-sm>.form-control,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.btn,.input-sm{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.input-group-sm>.input-group-btn>select.btn,.input-group-sm>select.form-control,.input-group-sm>select.input-group-addon,select.input-sm{height:30px;line-height:30px}.input-group-sm>.input-group-btn>select[multiple].btn,.input-group-sm>.input-group-btn>textarea.btn,.input-group-sm>select[multiple].form-control,.input-group-sm>select[multiple].input-group-addon,.input-group-sm>textarea.form-control,.input-group-sm>textarea.input-group-addon,select[multiple].input-sm,textarea.input-sm{height:auto}.form-group-sm .form-control{height:30px;padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.form-group-sm select.form-control{height:30px;line-height:30px}.form-group-sm select[multiple].form-control,.form-group-sm textarea.form-control{height:auto}.form-group-sm .form-control-static{height:30px;min-height:34px;padding:6px 10px;font-size:12px;line-height:1.5}.input-group-lg>.form-control,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.btn,.input-lg{height:46px;padding:10px 16px;font-size:18px;line-height:1.33333;border-radius:6px}.input-group-lg>.input-group-btn>select.btn,.input-group-lg>select.form-control,.input-group-lg>select.input-group-addon,select.input-lg{height:46px;line-height:46px}.input-group-lg>.input-group-btn>select[multiple].btn,.input-group-lg>.input-group-btn>textarea.btn,.input-group-lg>select[multiple].form-control,.input-group-lg>select[multiple].input-group-addon,.input-group-lg>textarea.form-control,.input-group-lg>textarea.input-group-addon,select[multiple].input-lg,textarea.input-lg{height:auto}.form-group-lg .form-control{height:46px;padding:10px 16px;font-size:18px;line-height:1.33333;border-radius:6px}.form-group-lg select.form-control{height:46px;line-height:46px}.form-group-lg select[multiple].form-control,.form-group-lg textarea.form-control{height:auto}.form-group-lg .form-control-static{height:46px;min-height:40px;padding:11px 16px;font-size:18px;line-height:1.33333}.has-feedback{position:relative}.has-feedback .form-control{padding-right:45px}.form-control-feedback{position:absolute;top:0;right:0;z-index:2;display:block;width:36px;height:36px;line-height:36px;text-align:center;pointer-events:none}.form-group-lg .form-control+.form-control-feedback,.input-group-lg+.form-control-feedback,.input-group-lg>.form-control+.form-control-feedback,.input-group-lg>.input-group-addon+.form-control-feedback,.input-group-lg>.input-group-btn>.btn+.form-control-feedback,.input-lg+.form-control-feedback{width:46px;height:46px;line-height:46px}.form-group-sm .form-control+.form-control-feedback,.input-group-sm+.form-control-feedback,.input-group-sm>.form-control+.form-control-feedback,.input-group-sm>.input-group-addon+.form-control-feedback,.input-group-sm>.input-group-btn>.btn+.form-control-feedback,.input-sm+.form-control-feedback{width:30px;height:30px;line-height:30px}.has-success .checkbox,.has-success .checkbox-inline,.has-success.checkbox-inline label,.has-success.checkbox label,.has-success .control-label,.has-success .help-block,.has-success .radio,.has-success .radio-inline,.has-success.radio-inline label,.has-success.radio label{color:#3c763d}.has-success .form-control{border-color:#3c763d;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-success .form-control:focus{border-color:#2b542c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #67b168}.has-success .input-group-addon{color:#3c763d;border-color:#3c763d;background-color:#dff0d8}.has-success .form-control-feedback{color:#3c763d}.has-warning .checkbox,.has-warning .checkbox-inline,.has-warning.checkbox-inline label,.has-warning.checkbox label,.has-warning .control-label,.has-warning .help-block,.has-warning .radio,.has-warning .radio-inline,.has-warning.radio-inline label,.has-warning.radio label{color:#8a6d3b}.has-warning .form-control{border-color:#8a6d3b;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-warning .form-control:focus{border-color:#66512c;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #c0a16b}.has-warning .input-group-addon{color:#8a6d3b;border-color:#8a6d3b;background-color:#fcf8e3}.has-warning .form-control-feedback{color:#8a6d3b}.has-error .checkbox,.has-error .checkbox-inline,.has-error.checkbox-inline label,.has-error.checkbox label,.has-error .control-label,.has-error .help-block,.has-error .radio,.has-error .radio-inline,.has-error.radio-inline label,.has-error.radio label{color:#a94442}.has-error .form-control{border-color:#a94442;box-shadow:inset 0 1px 1px rgba(0,0,0,.075)}.has-error .form-control:focus{border-color:#843534;box-shadow:inset 0 1px 1px rgba(0,0,0,.075),0 0 6px #ce8483}.has-error .input-group-addon{color:#a94442;border-color:#a94442;background-color:#f2dede}.has-error .form-control-feedback{color:#a94442}.has-feedback label~.form-control-feedback{top:27px}.has-feedback label.sr-only~.form-control-feedback{top:0}.help-block{display:block;margin-top:5px;margin-bottom:10px;color:#a4aaae}@media (min-width:768px){.form-inline .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.form-inline .form-control{display:inline-block;width:auto;vertical-align:middle}.form-inline .form-control-static{display:inline-block}.form-inline .input-group{display:inline-table;vertical-align:middle}.form-inline .input-group .form-control,.form-inline .input-group .input-group-addon,.form-inline .input-group .input-group-btn{width:auto}.form-inline .input-group>.form-control{width:100%}.form-inline .control-label{margin-bottom:0;vertical-align:middle}.form-inline .checkbox,.form-inline .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.form-inline .checkbox label,.form-inline .radio label{padding-left:0}.form-inline .checkbox input[type=checkbox],.form-inline .radio input[type=radio]{position:relative;margin-left:0}.form-inline .has-feedback .form-control-feedback{top:0}}.form-horizontal .checkbox,.form-horizontal .checkbox-inline,.form-horizontal .radio,.form-horizontal .radio-inline{margin-top:0;margin-bottom:0;padding-top:7px}.form-horizontal .checkbox,.form-horizontal .radio{min-height:29px}.form-horizontal .form-group{margin-left:-15px;margin-right:-15px}.form-horizontal .form-group:after,.form-horizontal .form-group:before{content:" ";display:table}.form-horizontal .form-group:after{clear:both}@media (min-width:768px){.form-horizontal .control-label{text-align:right;margin-bottom:0;padding-top:7px}}.form-horizontal .has-feedback .form-control-feedback{right:15px}@media (min-width:768px){.form-horizontal .form-group-lg .control-label{padding-top:11px;font-size:18px}}@media (min-width:768px){.form-horizontal .form-group-sm .control-label{padding-top:6px;font-size:12px}}.btn{display:inline-block;margin-bottom:0;font-weight:400;text-align:center;vertical-align:middle;-ms-touch-action:manipulation;touch-action:manipulation;cursor:pointer;background-image:none;border:1px solid transparent;white-space:nowrap;padding:6px 12px;font-size:14px;line-height:1.6;border-radius:4px;-webkit-user-select:none;-moz-user-select:none;-ms-user-select:none;user-select:none}.btn.active.focus,.btn.active:focus,.btn.focus,.btn:active.focus,.btn:active:focus,.btn:focus{outline:5px auto -webkit-focus-ring-color;outline-offset:-2px}.btn.focus,.btn:focus,.btn:hover{color:#636b6f;text-decoration:none}.btn.active,.btn:active{outline:0;background-image:none;box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn.disabled,.btn[disabled],fieldset[disabled] .btn{cursor:not-allowed;opacity:.65;filter:alpha(opacity=65);box-shadow:none}a.btn.disabled,fieldset[disabled] a.btn{pointer-events:none}.btn-default{color:#636b6f;background-color:#fff;border-color:#ccc}.btn-default.focus,.btn-default:focus{color:#636b6f;background-color:#e6e6e6;border-color:#8c8c8c}.btn-default.active,.btn-default:active,.btn-default:hover,.open>.btn-default.dropdown-toggle{color:#636b6f;background-color:#e6e6e6;border-color:#adadad}.btn-default.active.focus,.btn-default.active:focus,.btn-default.active:hover,.btn-default:active.focus,.btn-default:active:focus,.btn-default:active:hover,.open>.btn-default.dropdown-toggle.focus,.open>.btn-default.dropdown-toggle:focus,.open>.btn-default.dropdown-toggle:hover{color:#636b6f;background-color:#d4d4d4;border-color:#8c8c8c}.btn-default.active,.btn-default:active,.open>.btn-default.dropdown-toggle{background-image:none}.btn-default.disabled.focus,.btn-default.disabled:focus,.btn-default.disabled:hover,.btn-default[disabled].focus,.btn-default[disabled]:focus,.btn-default[disabled]:hover,fieldset[disabled] .btn-default.focus,fieldset[disabled] .btn-default:focus,fieldset[disabled] .btn-default:hover{background-color:#fff;border-color:#ccc}.btn-default .badge{color:#fff;background-color:#636b6f}.btn-primary{color:#fff;background-color:#3097d1;border-color:#2a88bd}.btn-primary.focus,.btn-primary:focus{color:#fff;background-color:#2579a9;border-color:#133d55}.btn-primary.active,.btn-primary:active,.btn-primary:hover,.open>.btn-primary.dropdown-toggle{color:#fff;background-color:#2579a9;border-color:#1f648b}.btn-primary.active.focus,.btn-primary.active:focus,.btn-primary.active:hover,.btn-primary:active.focus,.btn-primary:active:focus,.btn-primary:active:hover,.open>.btn-primary.dropdown-toggle.focus,.open>.btn-primary.dropdown-toggle:focus,.open>.btn-primary.dropdown-toggle:hover{color:#fff;background-color:#1f648b;border-color:#133d55}.btn-primary.active,.btn-primary:active,.open>.btn-primary.dropdown-toggle{background-image:none}.btn-primary.disabled.focus,.btn-primary.disabled:focus,.btn-primary.disabled:hover,.btn-primary[disabled].focus,.btn-primary[disabled]:focus,.btn-primary[disabled]:hover,fieldset[disabled] .btn-primary.focus,fieldset[disabled] .btn-primary:focus,fieldset[disabled] .btn-primary:hover{background-color:#3097d1;border-color:#2a88bd}.btn-primary .badge{color:#3097d1;background-color:#fff}.btn-success{color:#fff;background-color:#2ab27b;border-color:#259d6d}.btn-success.focus,.btn-success:focus{color:#fff;background-color:#20895e;border-color:#0d3625}.btn-success.active,.btn-success:active,.btn-success:hover,.open>.btn-success.dropdown-toggle{color:#fff;background-color:#20895e;border-color:#196c4b}.btn-success.active.focus,.btn-success.active:focus,.btn-success.active:hover,.btn-success:active.focus,.btn-success:active:focus,.btn-success:active:hover,.open>.btn-success.dropdown-toggle.focus,.open>.btn-success.dropdown-toggle:focus,.open>.btn-success.dropdown-toggle:hover{color:#fff;background-color:#196c4b;border-color:#0d3625}.btn-success.active,.btn-success:active,.open>.btn-success.dropdown-toggle{background-image:none}.btn-success.disabled.focus,.btn-success.disabled:focus,.btn-success.disabled:hover,.btn-success[disabled].focus,.btn-success[disabled]:focus,.btn-success[disabled]:hover,fieldset[disabled] .btn-success.focus,fieldset[disabled] .btn-success:focus,fieldset[disabled] .btn-success:hover{background-color:#2ab27b;border-color:#259d6d}.btn-success .badge{color:#2ab27b;background-color:#fff}.btn-info{color:#fff;background-color:#8eb4cb;border-color:#7da8c3}.btn-info.focus,.btn-info:focus{color:#fff;background-color:#6b9dbb;border-color:#3d6983}.btn-info.active,.btn-info:active,.btn-info:hover,.open>.btn-info.dropdown-toggle{color:#fff;background-color:#6b9dbb;border-color:#538db0}.btn-info.active.focus,.btn-info.active:focus,.btn-info.active:hover,.btn-info:active.focus,.btn-info:active:focus,.btn-info:active:hover,.open>.btn-info.dropdown-toggle.focus,.open>.btn-info.dropdown-toggle:focus,.open>.btn-info.dropdown-toggle:hover{color:#fff;background-color:#538db0;border-color:#3d6983}.btn-info.active,.btn-info:active,.open>.btn-info.dropdown-toggle{background-image:none}.btn-info.disabled.focus,.btn-info.disabled:focus,.btn-info.disabled:hover,.btn-info[disabled].focus,.btn-info[disabled]:focus,.btn-info[disabled]:hover,fieldset[disabled] .btn-info.focus,fieldset[disabled] .btn-info:focus,fieldset[disabled] .btn-info:hover{background-color:#8eb4cb;border-color:#7da8c3}.btn-info .badge{color:#8eb4cb;background-color:#fff}.btn-warning{color:#fff;background-color:#cbb956;border-color:#c5b143}.btn-warning.focus,.btn-warning:focus{color:#fff;background-color:#b6a338;border-color:#685d20}.btn-warning.active,.btn-warning:active,.btn-warning:hover,.open>.btn-warning.dropdown-toggle{color:#fff;background-color:#b6a338;border-color:#9b8a30}.btn-warning.active.focus,.btn-warning.active:focus,.btn-warning.active:hover,.btn-warning:active.focus,.btn-warning:active:focus,.btn-warning:active:hover,.open>.btn-warning.dropdown-toggle.focus,.open>.btn-warning.dropdown-toggle:focus,.open>.btn-warning.dropdown-toggle:hover{color:#fff;background-color:#9b8a30;border-color:#685d20}.btn-warning.active,.btn-warning:active,.open>.btn-warning.dropdown-toggle{background-image:none}.btn-warning.disabled.focus,.btn-warning.disabled:focus,.btn-warning.disabled:hover,.btn-warning[disabled].focus,.btn-warning[disabled]:focus,.btn-warning[disabled]:hover,fieldset[disabled] .btn-warning.focus,fieldset[disabled] .btn-warning:focus,fieldset[disabled] .btn-warning:hover{background-color:#cbb956;border-color:#c5b143}.btn-warning .badge{color:#cbb956;background-color:#fff}.btn-danger{color:#fff;background-color:#bf5329;border-color:#aa4a24}.btn-danger.focus,.btn-danger:focus{color:#fff;background-color:#954120;border-color:#411c0e}.btn-danger.active,.btn-danger:active,.btn-danger:hover,.open>.btn-danger.dropdown-toggle{color:#fff;background-color:#954120;border-color:#78341a}.btn-danger.active.focus,.btn-danger.active:focus,.btn-danger.active:hover,.btn-danger:active.focus,.btn-danger:active:focus,.btn-danger:active:hover,.open>.btn-danger.dropdown-toggle.focus,.open>.btn-danger.dropdown-toggle:focus,.open>.btn-danger.dropdown-toggle:hover{color:#fff;background-color:#78341a;border-color:#411c0e}.btn-danger.active,.btn-danger:active,.open>.btn-danger.dropdown-toggle{background-image:none}.btn-danger.disabled.focus,.btn-danger.disabled:focus,.btn-danger.disabled:hover,.btn-danger[disabled].focus,.btn-danger[disabled]:focus,.btn-danger[disabled]:hover,fieldset[disabled] .btn-danger.focus,fieldset[disabled] .btn-danger:focus,fieldset[disabled] .btn-danger:hover{background-color:#bf5329;border-color:#aa4a24}.btn-danger .badge{color:#bf5329;background-color:#fff}.btn-link{color:#3097d1;font-weight:400;border-radius:0}.btn-link,.btn-link.active,.btn-link:active,.btn-link[disabled],fieldset[disabled] .btn-link{background-color:transparent;box-shadow:none}.btn-link,.btn-link:active,.btn-link:focus,.btn-link:hover{border-color:transparent}.btn-link:focus,.btn-link:hover{color:#216a94;text-decoration:underline;background-color:transparent}.btn-link[disabled]:focus,.btn-link[disabled]:hover,fieldset[disabled] .btn-link:focus,fieldset[disabled] .btn-link:hover{color:#777;text-decoration:none}.btn-group-lg>.btn,.btn-lg{padding:10px 16px;font-size:18px;line-height:1.33333;border-radius:6px}.btn-group-sm>.btn,.btn-sm{padding:5px 10px;font-size:12px;line-height:1.5;border-radius:3px}.btn-group-xs>.btn,.btn-xs{padding:1px 5px;font-size:12px;line-height:1.5;border-radius:3px}.btn-block{display:block;width:100%}.btn-block+.btn-block{margin-top:5px}input[type=button].btn-block,input[type=reset].btn-block,input[type=submit].btn-block{width:100%}.fade{opacity:0;-webkit-transition:opacity .15s linear;transition:opacity .15s linear}.fade.in{opacity:1}.collapse{display:none}.collapse.in{display:block}tr.collapse.in{display:table-row}tbody.collapse.in{display:table-row-group}.collapsing{position:relative;height:0;overflow:hidden;-webkit-transition-property:height,visibility;transition-property:height,visibility;-webkit-transition-duration:.35s;transition-duration:.35s;-webkit-transition-timing-function:ease;transition-timing-function:ease}.caret{display:inline-block;width:0;height:0;margin-left:2px;vertical-align:middle;border-top:4px dashed;border-top:4px solid\9;border-right:4px solid transparent;border-left:4px solid transparent}.dropdown,.dropup{position:relative}.dropdown-toggle:focus{outline:0}.dropdown-menu{position:absolute;top:100%;left:0;z-index:1000;display:none;float:left;min-width:160px;padding:5px 0;margin:2px 0 0;list-style:none;font-size:14px;text-align:left;background-color:#fff;border:1px solid #ccc;border:1px solid rgba(0,0,0,.15);border-radius:4px;box-shadow:0 6px 12px rgba(0,0,0,.175);background-clip:padding-box}.dropdown-menu.pull-right{right:0;left:auto}.dropdown-menu .divider{height:1px;margin:10px 0;overflow:hidden;background-color:#e5e5e5}.dropdown-menu>li>a{display:block;padding:3px 20px;clear:both;font-weight:400;line-height:1.6;color:#333;white-space:nowrap}.dropdown-menu>li>a:focus,.dropdown-menu>li>a:hover{text-decoration:none;color:#262626;background-color:#f5f5f5}.dropdown-menu>.active>a,.dropdown-menu>.active>a:focus,.dropdown-menu>.active>a:hover{color:#fff;text-decoration:none;outline:0;background-color:#3097d1}.dropdown-menu>.disabled>a,.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{color:#777}.dropdown-menu>.disabled>a:focus,.dropdown-menu>.disabled>a:hover{text-decoration:none;background-color:transparent;background-image:none;filter:progid:DXImageTransform.Microsoft.gradient(enabled = false);cursor:not-allowed}.open>.dropdown-menu{display:block}.open>a{outline:0}.dropdown-menu-right{left:auto;right:0}.dropdown-menu-left{left:0;right:auto}.dropdown-header{display:block;padding:3px 20px;font-size:12px;line-height:1.6;color:#777;white-space:nowrap}.dropdown-backdrop{position:fixed;left:0;right:0;bottom:0;top:0;z-index:990}.pull-right>.dropdown-menu{right:0;left:auto}.dropup .caret,.navbar-fixed-bottom .dropdown .caret{border-top:0;border-bottom:4px dashed;border-bottom:4px solid\9;content:""}.dropup .dropdown-menu,.navbar-fixed-bottom .dropdown .dropdown-menu{top:auto;bottom:100%;margin-bottom:2px}@media (min-width:768px){.navbar-right .dropdown-menu{right:0;left:auto}.navbar-right .dropdown-menu-left{left:0;right:auto}}.btn-group,.btn-group-vertical{position:relative;display:inline-block;vertical-align:middle}.btn-group-vertical>.btn,.btn-group>.btn{position:relative;float:left}.btn-group-vertical>.btn.active,.btn-group-vertical>.btn:active,.btn-group-vertical>.btn:focus,.btn-group-vertical>.btn:hover,.btn-group>.btn.active,.btn-group>.btn:active,.btn-group>.btn:focus,.btn-group>.btn:hover{z-index:2}.btn-group .btn+.btn,.btn-group .btn+.btn-group,.btn-group .btn-group+.btn,.btn-group .btn-group+.btn-group{margin-left:-1px}.btn-toolbar{margin-left:-5px}.btn-toolbar:after,.btn-toolbar:before{content:" ";display:table}.btn-toolbar:after{clear:both}.btn-toolbar .btn,.btn-toolbar .btn-group,.btn-toolbar .input-group{float:left}.btn-toolbar>.btn,.btn-toolbar>.btn-group,.btn-toolbar>.input-group{margin-left:5px}.btn-group>.btn:not(:first-child):not(:last-child):not(.dropdown-toggle){border-radius:0}.btn-group>.btn:first-child{margin-left:0}.btn-group>.btn:first-child:not(:last-child):not(.dropdown-toggle){border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn:last-child:not(:first-child),.btn-group>.dropdown-toggle:not(:first-child){border-bottom-left-radius:0;border-top-left-radius:0}.btn-group>.btn-group{float:left}.btn-group>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-top-right-radius:0}.btn-group>.btn-group:last-child:not(:first-child)>.btn:first-child{border-bottom-left-radius:0;border-top-left-radius:0}.btn-group .dropdown-toggle:active,.btn-group.open .dropdown-toggle{outline:0}.btn-group>.btn+.dropdown-toggle{padding-left:8px;padding-right:8px}.btn-group-lg.btn-group>.btn+.dropdown-toggle,.btn-group>.btn-lg+.dropdown-toggle{padding-left:12px;padding-right:12px}.btn-group.open .dropdown-toggle{box-shadow:inset 0 3px 5px rgba(0,0,0,.125)}.btn-group.open .dropdown-toggle.btn-link{box-shadow:none}.btn .caret{margin-left:0}.btn-group-lg>.btn .caret,.btn-lg .caret{border-width:5px 5px 0;border-bottom-width:0}.dropup .btn-group-lg>.btn .caret,.dropup .btn-lg .caret{border-width:0 5px 5px}.btn-group-vertical>.btn,.btn-group-vertical>.btn-group,.btn-group-vertical>.btn-group>.btn{display:block;float:none;width:100%;max-width:100%}.btn-group-vertical>.btn-group:after,.btn-group-vertical>.btn-group:before{content:" ";display:table}.btn-group-vertical>.btn-group:after{clear:both}.btn-group-vertical>.btn-group>.btn{float:none}.btn-group-vertical>.btn+.btn,.btn-group-vertical>.btn+.btn-group,.btn-group-vertical>.btn-group+.btn,.btn-group-vertical>.btn-group+.btn-group{margin-top:-1px;margin-left:0}.btn-group-vertical>.btn:not(:first-child):not(:last-child){border-radius:0}.btn-group-vertical>.btn:first-child:not(:last-child){border-top-right-radius:4px;border-top-left-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn:last-child:not(:first-child){border-top-right-radius:0;border-top-left-radius:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}.btn-group-vertical>.btn-group:not(:first-child):not(:last-child)>.btn{border-radius:0}.btn-group-vertical>.btn-group:first-child:not(:last-child)>.btn:last-child,.btn-group-vertical>.btn-group:first-child:not(:last-child)>.dropdown-toggle{border-bottom-right-radius:0;border-bottom-left-radius:0}.btn-group-vertical>.btn-group:last-child:not(:first-child)>.btn:first-child{border-top-right-radius:0;border-top-left-radius:0}.btn-group-justified{display:table;width:100%;table-layout:fixed;border-collapse:separate}.btn-group-justified>.btn,.btn-group-justified>.btn-group{float:none;display:table-cell;width:1%}.btn-group-justified>.btn-group .btn{width:100%}.btn-group-justified>.btn-group .dropdown-menu{left:auto}[data-toggle=buttons]>.btn-group>.btn input[type=checkbox],[data-toggle=buttons]>.btn-group>.btn input[type=radio],[data-toggle=buttons]>.btn input[type=checkbox],[data-toggle=buttons]>.btn input[type=radio]{position:absolute;clip:rect(0,0,0,0);pointer-events:none}.input-group{position:relative;display:table;border-collapse:separate}.input-group[class*=col-]{float:none;padding-left:0;padding-right:0}.input-group .form-control{position:relative;z-index:2;float:left;width:100%;margin-bottom:0}.input-group .form-control:focus{z-index:3}.input-group-addon,.input-group-btn,.input-group .form-control{display:table-cell}.input-group-addon:not(:first-child):not(:last-child),.input-group-btn:not(:first-child):not(:last-child),.input-group .form-control:not(:first-child):not(:last-child){border-radius:0}.input-group-addon,.input-group-btn{width:1%;white-space:nowrap;vertical-align:middle}.input-group-addon{padding:6px 12px;font-size:14px;font-weight:400;line-height:1;color:#555;text-align:center;background-color:#eee;border:1px solid #ccd0d2;border-radius:4px}.input-group-addon.input-sm,.input-group-sm>.input-group-addon,.input-group-sm>.input-group-btn>.input-group-addon.btn{padding:5px 10px;font-size:12px;border-radius:3px}.input-group-addon.input-lg,.input-group-lg>.input-group-addon,.input-group-lg>.input-group-btn>.input-group-addon.btn{padding:10px 16px;font-size:18px;border-radius:6px}.input-group-addon input[type=checkbox],.input-group-addon input[type=radio]{margin-top:0}.input-group-addon:first-child,.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group>.btn,.input-group-btn:first-child>.dropdown-toggle,.input-group-btn:last-child>.btn-group:not(:last-child)>.btn,.input-group-btn:last-child>.btn:not(:last-child):not(.dropdown-toggle),.input-group .form-control:first-child{border-bottom-right-radius:0;border-top-right-radius:0}.input-group-addon:first-child{border-right:0}.input-group-addon:last-child,.input-group-btn:first-child>.btn-group:not(:first-child)>.btn,.input-group-btn:first-child>.btn:not(:first-child),.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group>.btn,.input-group-btn:last-child>.dropdown-toggle,.input-group .form-control:last-child{border-bottom-left-radius:0;border-top-left-radius:0}.input-group-addon:last-child{border-left:0}.input-group-btn{font-size:0;white-space:nowrap}.input-group-btn,.input-group-btn>.btn{position:relative}.input-group-btn>.btn+.btn{margin-left:-1px}.input-group-btn>.btn:active,.input-group-btn>.btn:focus,.input-group-btn>.btn:hover{z-index:2}.input-group-btn:first-child>.btn,.input-group-btn:first-child>.btn-group{margin-right:-1px}.input-group-btn:last-child>.btn,.input-group-btn:last-child>.btn-group{z-index:2;margin-left:-1px}.nav{margin-bottom:0;padding-left:0;list-style:none}.nav:after,.nav:before{content:" ";display:table}.nav:after{clear:both}.nav>li,.nav>li>a{position:relative;display:block}.nav>li>a{padding:10px 15px}.nav>li>a:focus,.nav>li>a:hover{text-decoration:none;background-color:#eee}.nav>li.disabled>a{color:#777}.nav>li.disabled>a:focus,.nav>li.disabled>a:hover{color:#777;text-decoration:none;background-color:transparent;cursor:not-allowed}.nav .open>a,.nav .open>a:focus,.nav .open>a:hover{background-color:#eee;border-color:#3097d1}.nav .nav-divider{height:1px;margin:10px 0;overflow:hidden;background-color:#e5e5e5}.nav>li>a>img{max-width:none}.nav-tabs{border-bottom:1px solid #ddd}.nav-tabs>li{float:left;margin-bottom:-1px}.nav-tabs>li>a{margin-right:2px;line-height:1.6;border:1px solid transparent;border-radius:4px 4px 0 0}.nav-tabs>li>a:hover{border-color:#eee #eee #ddd}.nav-tabs>li.active>a,.nav-tabs>li.active>a:focus,.nav-tabs>li.active>a:hover{color:#555;background-color:#f5f8fa;border:1px solid #ddd;border-bottom-color:transparent;cursor:default}.nav-pills>li{float:left}.nav-pills>li>a{border-radius:4px}.nav-pills>li+li{margin-left:2px}.nav-pills>li.active>a,.nav-pills>li.active>a:focus,.nav-pills>li.active>a:hover{color:#fff;background-color:#3097d1}.nav-stacked>li{float:none}.nav-stacked>li+li{margin-top:2px;margin-left:0}.nav-justified,.nav-tabs.nav-justified{width:100%}.nav-justified>li,.nav-tabs.nav-justified>li{float:none}.nav-justified>li>a,.nav-tabs.nav-justified>li>a{text-align:center;margin-bottom:5px}.nav-justified>.dropdown .dropdown-menu{top:auto;left:auto}@media (min-width:768px){.nav-justified>li,.nav-tabs.nav-justified>li{display:table-cell;width:1%}.nav-justified>li>a,.nav-tabs.nav-justified>li>a{margin-bottom:0}}.nav-tabs-justified,.nav-tabs.nav-justified{border-bottom:0}.nav-tabs-justified>li>a,.nav-tabs.nav-justified>li>a{margin-right:0;border-radius:4px}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border:1px solid #ddd}@media (min-width:768px){.nav-tabs-justified>li>a,.nav-tabs.nav-justified>li>a{border-bottom:1px solid #ddd;border-radius:4px 4px 0 0}.nav-tabs-justified>.active>a,.nav-tabs-justified>.active>a:focus,.nav-tabs-justified>.active>a:hover,.nav-tabs.nav-justified>.active>a,.nav-tabs.nav-justified>.active>a:focus,.nav-tabs.nav-justified>.active>a:hover{border-bottom-color:#f5f8fa}}.tab-content>.tab-pane{display:none}.tab-content>.active{display:block}.nav-tabs .dropdown-menu{margin-top:-1px;border-top-right-radius:0;border-top-left-radius:0}.navbar{position:relative;min-height:50px;margin-bottom:22px;border:1px solid transparent}.navbar:after,.navbar:before{content:" ";display:table}.navbar:after{clear:both}@media (min-width:768px){.navbar{border-radius:4px}}.navbar-header:after,.navbar-header:before{content:" ";display:table}.navbar-header:after{clear:both}@media (min-width:768px){.navbar-header{float:left}}.navbar-collapse{overflow-x:visible;padding-right:15px;padding-left:15px;border-top:1px solid transparent;box-shadow:inset 0 1px 0 hsla(0,0%,100%,.1);-webkit-overflow-scrolling:touch}.navbar-collapse:after,.navbar-collapse:before{content:" ";display:table}.navbar-collapse:after{clear:both}.navbar-collapse.in{overflow-y:auto}@media (min-width:768px){.navbar-collapse{width:auto;border-top:0;box-shadow:none}.navbar-collapse.collapse{display:block!important;height:auto!important;padding-bottom:0;overflow:visible!important}.navbar-collapse.in{overflow-y:visible}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse,.navbar-static-top .navbar-collapse{padding-left:0;padding-right:0}}.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:340px}@media (max-device-width:480px) and (orientation:landscape){.navbar-fixed-bottom .navbar-collapse,.navbar-fixed-top .navbar-collapse{max-height:200px}}.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:-15px;margin-left:-15px}@media (min-width:768px){.container-fluid>.navbar-collapse,.container-fluid>.navbar-header,.container>.navbar-collapse,.container>.navbar-header{margin-right:0;margin-left:0}}.navbar-static-top{z-index:1000;border-width:0 0 1px}@media (min-width:768px){.navbar-static-top{border-radius:0}}.navbar-fixed-bottom,.navbar-fixed-top{position:fixed;right:0;left:0;z-index:1030}@media (min-width:768px){.navbar-fixed-bottom,.navbar-fixed-top{border-radius:0}}.navbar-fixed-top{top:0;border-width:0 0 1px}.navbar-fixed-bottom{bottom:0;margin-bottom:0;border-width:1px 0 0}.navbar-brand{float:left;padding:14px 15px;font-size:18px;line-height:22px;height:50px}.navbar-brand:focus,.navbar-brand:hover{text-decoration:none}.navbar-brand>img{display:block}@media (min-width:768px){.navbar>.container-fluid .navbar-brand,.navbar>.container .navbar-brand{margin-left:-15px}}.navbar-toggle{position:relative;float:right;margin-right:15px;padding:9px 10px;margin-top:8px;margin-bottom:8px;background-color:transparent;background-image:none;border:1px solid transparent;border-radius:4px}.navbar-toggle:focus{outline:0}.navbar-toggle .icon-bar{display:block;width:22px;height:2px;border-radius:1px}.navbar-toggle .icon-bar+.icon-bar{margin-top:4px}@media (min-width:768px){.navbar-toggle{display:none}}.navbar-nav{margin:7px -15px}.navbar-nav>li>a{padding-top:10px;padding-bottom:10px;line-height:22px}@media (max-width:767px){.navbar-nav .open .dropdown-menu{position:static;float:none;width:auto;margin-top:0;background-color:transparent;border:0;box-shadow:none}.navbar-nav .open .dropdown-menu .dropdown-header,.navbar-nav .open .dropdown-menu>li>a{padding:5px 15px 5px 25px}.navbar-nav .open .dropdown-menu>li>a{line-height:22px}.navbar-nav .open .dropdown-menu>li>a:focus,.navbar-nav .open .dropdown-menu>li>a:hover{background-image:none}}@media (min-width:768px){.navbar-nav{float:left;margin:0}.navbar-nav>li{float:left}.navbar-nav>li>a{padding-top:14px;padding-bottom:14px}}.navbar-form{margin:7px -15px;padding:10px 15px;border-top:1px solid transparent;border-bottom:1px solid transparent;box-shadow:inset 0 1px 0 hsla(0,0%,100%,.1),0 1px 0 hsla(0,0%,100%,.1)}@media (min-width:768px){.navbar-form .form-group{display:inline-block;margin-bottom:0;vertical-align:middle}.navbar-form .form-control{display:inline-block;width:auto;vertical-align:middle}.navbar-form .form-control-static{display:inline-block}.navbar-form .input-group{display:inline-table;vertical-align:middle}.navbar-form .input-group .form-control,.navbar-form .input-group .input-group-addon,.navbar-form .input-group .input-group-btn{width:auto}.navbar-form .input-group>.form-control{width:100%}.navbar-form .control-label{margin-bottom:0;vertical-align:middle}.navbar-form .checkbox,.navbar-form .radio{display:inline-block;margin-top:0;margin-bottom:0;vertical-align:middle}.navbar-form .checkbox label,.navbar-form .radio label{padding-left:0}.navbar-form .checkbox input[type=checkbox],.navbar-form .radio input[type=radio]{position:relative;margin-left:0}.navbar-form .has-feedback .form-control-feedback{top:0}}@media (max-width:767px){.navbar-form .form-group{margin-bottom:5px}.navbar-form .form-group:last-child{margin-bottom:0}}@media (min-width:768px){.navbar-form{width:auto;border:0;margin-left:0;margin-right:0;padding-top:0;padding-bottom:0;box-shadow:none}}.navbar-nav>li>.dropdown-menu{margin-top:0;border-top-right-radius:0;border-top-left-radius:0}.navbar-fixed-bottom .navbar-nav>li>.dropdown-menu{margin-bottom:0;border-top-right-radius:4px;border-top-left-radius:4px;border-bottom-right-radius:0;border-bottom-left-radius:0}.navbar-btn{margin-top:7px;margin-bottom:7px}.btn-group-sm>.navbar-btn.btn,.navbar-btn.btn-sm{margin-top:10px;margin-bottom:10px}.btn-group-xs>.navbar-btn.btn,.navbar-btn.btn-xs,.navbar-text{margin-top:14px;margin-bottom:14px}@media (min-width:768px){.navbar-text{float:left;margin-left:15px;margin-right:15px}}@media (min-width:768px){.navbar-left{float:left!important}.navbar-right{float:right!important;margin-right:-15px}.navbar-right~.navbar-right{margin-right:0}}.navbar-default{background-color:#fff;border-color:#d3e0e9}.navbar-default .navbar-brand{color:#777}.navbar-default .navbar-brand:focus,.navbar-default .navbar-brand:hover{color:#5e5e5e;background-color:transparent}.navbar-default .navbar-nav>li>a,.navbar-default .navbar-text{color:#777}.navbar-default .navbar-nav>li>a:focus,.navbar-default .navbar-nav>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav>.active>a,.navbar-default .navbar-nav>.active>a:focus,.navbar-default .navbar-nav>.active>a:hover{color:#555;background-color:#eee}.navbar-default .navbar-nav>.disabled>a,.navbar-default .navbar-nav>.disabled>a:focus,.navbar-default .navbar-nav>.disabled>a:hover{color:#ccc;background-color:transparent}.navbar-default .navbar-toggle{border-color:#ddd}.navbar-default .navbar-toggle:focus,.navbar-default .navbar-toggle:hover{background-color:#ddd}.navbar-default .navbar-toggle .icon-bar{background-color:#888}.navbar-default .navbar-collapse,.navbar-default .navbar-form{border-color:#d3e0e9}.navbar-default .navbar-nav>.open>a,.navbar-default .navbar-nav>.open>a:focus,.navbar-default .navbar-nav>.open>a:hover{background-color:#eee;color:#555}@media (max-width:767px){.navbar-default .navbar-nav .open .dropdown-menu>li>a{color:#777}.navbar-default .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>li>a:hover{color:#333;background-color:transparent}.navbar-default .navbar-nav .open .dropdown-menu>.active>a,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.active>a:hover{color:#555;background-color:#eee}.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-default .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#ccc;background-color:transparent}}.navbar-default .navbar-link{color:#777}.navbar-default .navbar-link:hover{color:#333}.navbar-default .btn-link{color:#777}.navbar-default .btn-link:focus,.navbar-default .btn-link:hover{color:#333}.navbar-default .btn-link[disabled]:focus,.navbar-default .btn-link[disabled]:hover,fieldset[disabled] .navbar-default .btn-link:focus,fieldset[disabled] .navbar-default .btn-link:hover{color:#ccc}.navbar-inverse{background-color:#222;border-color:#090909}.navbar-inverse .navbar-brand{color:#9d9d9d}.navbar-inverse .navbar-brand:focus,.navbar-inverse .navbar-brand:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>li>a,.navbar-inverse .navbar-text{color:#9d9d9d}.navbar-inverse .navbar-nav>li>a:focus,.navbar-inverse .navbar-nav>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav>.active>a,.navbar-inverse .navbar-nav>.active>a:focus,.navbar-inverse .navbar-nav>.active>a:hover{color:#fff;background-color:#090909}.navbar-inverse .navbar-nav>.disabled>a,.navbar-inverse .navbar-nav>.disabled>a:focus,.navbar-inverse .navbar-nav>.disabled>a:hover{color:#444;background-color:transparent}.navbar-inverse .navbar-toggle{border-color:#333}.navbar-inverse .navbar-toggle:focus,.navbar-inverse .navbar-toggle:hover{background-color:#333}.navbar-inverse .navbar-toggle .icon-bar{background-color:#fff}.navbar-inverse .navbar-collapse,.navbar-inverse .navbar-form{border-color:#101010}.navbar-inverse .navbar-nav>.open>a,.navbar-inverse .navbar-nav>.open>a:focus,.navbar-inverse .navbar-nav>.open>a:hover{background-color:#090909;color:#fff}@media (max-width:767px){.navbar-inverse .navbar-nav .open .dropdown-menu>.dropdown-header{border-color:#090909}.navbar-inverse .navbar-nav .open .dropdown-menu .divider{background-color:#090909}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a{color:#9d9d9d}.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>li>a:hover{color:#fff;background-color:transparent}.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.active>a:hover{color:#fff;background-color:#090909}.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:focus,.navbar-inverse .navbar-nav .open .dropdown-menu>.disabled>a:hover{color:#444;background-color:transparent}}.navbar-inverse .navbar-link{color:#9d9d9d}.navbar-inverse .navbar-link:hover{color:#fff}.navbar-inverse .btn-link{color:#9d9d9d}.navbar-inverse .btn-link:focus,.navbar-inverse .btn-link:hover{color:#fff}.navbar-inverse .btn-link[disabled]:focus,.navbar-inverse .btn-link[disabled]:hover,fieldset[disabled] .navbar-inverse .btn-link:focus,fieldset[disabled] .navbar-inverse .btn-link:hover{color:#444}.breadcrumb{padding:8px 15px;margin-bottom:22px;list-style:none;background-color:#f5f5f5;border-radius:4px}.breadcrumb>li{display:inline-block}.breadcrumb>li+li:before{content:"/\A0";padding:0 5px;color:#ccc}.breadcrumb>.active{color:#777}.pagination{display:inline-block;padding-left:0;margin:22px 0;border-radius:4px}.pagination>li{display:inline}.pagination>li>a,.pagination>li>span{position:relative;float:left;padding:6px 12px;line-height:1.6;text-decoration:none;color:#3097d1;background-color:#fff;border:1px solid #ddd;margin-left:-1px}.pagination>li:first-child>a,.pagination>li:first-child>span{margin-left:0;border-bottom-left-radius:4px;border-top-left-radius:4px}.pagination>li:last-child>a,.pagination>li:last-child>span{border-bottom-right-radius:4px;border-top-right-radius:4px}.pagination>li>a:focus,.pagination>li>a:hover,.pagination>li>span:focus,.pagination>li>span:hover{z-index:2;color:#216a94;background-color:#eee;border-color:#ddd}.pagination>.active>a,.pagination>.active>a:focus,.pagination>.active>a:hover,.pagination>.active>span,.pagination>.active>span:focus,.pagination>.active>span:hover{z-index:3;color:#fff;background-color:#3097d1;border-color:#3097d1;cursor:default}.pagination>.disabled>a,.pagination>.disabled>a:focus,.pagination>.disabled>a:hover,.pagination>.disabled>span,.pagination>.disabled>span:focus,.pagination>.disabled>span:hover{color:#777;background-color:#fff;border-color:#ddd;cursor:not-allowed}.pagination-lg>li>a,.pagination-lg>li>span{padding:10px 16px;font-size:18px;line-height:1.33333}.pagination-lg>li:first-child>a,.pagination-lg>li:first-child>span{border-bottom-left-radius:6px;border-top-left-radius:6px}.pagination-lg>li:last-child>a,.pagination-lg>li:last-child>span{border-bottom-right-radius:6px;border-top-right-radius:6px}.pagination-sm>li>a,.pagination-sm>li>span{padding:5px 10px;font-size:12px;line-height:1.5}.pagination-sm>li:first-child>a,.pagination-sm>li:first-child>span{border-bottom-left-radius:3px;border-top-left-radius:3px}.pagination-sm>li:last-child>a,.pagination-sm>li:last-child>span{border-bottom-right-radius:3px;border-top-right-radius:3px}.pager{padding-left:0;margin:22px 0;list-style:none;text-align:center}.pager:after,.pager:before{content:" ";display:table}.pager:after{clear:both}.pager li{display:inline}.pager li>a,.pager li>span{display:inline-block;padding:5px 14px;background-color:#fff;border:1px solid #ddd;border-radius:15px}.pager li>a:focus,.pager li>a:hover{text-decoration:none;background-color:#eee}.pager .next>a,.pager .next>span{float:right}.pager .previous>a,.pager .previous>span{float:left}.pager .disabled>a,.pager .disabled>a:focus,.pager .disabled>a:hover,.pager .disabled>span{color:#777;background-color:#fff;cursor:not-allowed}.label{display:inline;padding:.2em .6em .3em;font-size:75%;font-weight:700;line-height:1;color:#fff;text-align:center;white-space:nowrap;vertical-align:baseline;border-radius:.25em}.label:empty{display:none}.btn .label{position:relative;top:-1px}a.label:focus,a.label:hover{color:#fff;text-decoration:none;cursor:pointer}.label-default{background-color:#777}.label-default[href]:focus,.label-default[href]:hover{background-color:#5e5e5e}.label-primary{background-color:#3097d1}.label-primary[href]:focus,.label-primary[href]:hover{background-color:#2579a9}.label-success{background-color:#2ab27b}.label-success[href]:focus,.label-success[href]:hover{background-color:#20895e}.label-info{background-color:#8eb4cb}.label-info[href]:focus,.label-info[href]:hover{background-color:#6b9dbb}.label-warning{background-color:#cbb956}.label-warning[href]:focus,.label-warning[href]:hover{background-color:#b6a338}.label-danger{background-color:#bf5329}.label-danger[href]:focus,.label-danger[href]:hover{background-color:#954120}.badge{display:inline-block;min-width:10px;padding:3px 7px;font-size:12px;font-weight:700;color:#fff;line-height:1;vertical-align:middle;white-space:nowrap;text-align:center;background-color:#777;border-radius:10px}.badge:empty{display:none}.btn .badge{position:relative;top:-1px}.btn-group-xs>.btn .badge,.btn-xs .badge{top:0;padding:1px 5px}.list-group-item.active>.badge,.nav-pills>.active>a>.badge{color:#3097d1;background-color:#fff}.list-group-item>.badge{float:right}.list-group-item>.badge+.badge{margin-right:5px}.nav-pills>li>a>.badge{margin-left:3px}a.badge:focus,a.badge:hover{color:#fff;text-decoration:none;cursor:pointer}.jumbotron{padding-top:30px;padding-bottom:30px;margin-bottom:30px;background-color:#eee}.jumbotron,.jumbotron .h1,.jumbotron h1{color:inherit}.jumbotron p{margin-bottom:15px;font-size:21px;font-weight:200}.jumbotron>hr{border-top-color:#d5d5d5}.container-fluid .jumbotron,.container .jumbotron{border-radius:6px;padding-left:15px;padding-right:15px}.jumbotron .container{max-width:100%}@media screen and (min-width:768px){.jumbotron{padding-top:48px;padding-bottom:48px}.container-fluid .jumbotron,.container .jumbotron{padding-left:60px;padding-right:60px}.jumbotron .h1,.jumbotron h1{font-size:63px}}.thumbnail{display:block;padding:4px;margin-bottom:22px;line-height:1.6;background-color:#f5f8fa;border:1px solid #ddd;border-radius:4px;-webkit-transition:border .2s ease-in-out;transition:border .2s ease-in-out}.thumbnail>img,.thumbnail a>img{display:block;max-width:100%;height:auto;margin-left:auto;margin-right:auto}.thumbnail .caption{padding:9px;color:#636b6f}a.thumbnail.active,a.thumbnail:focus,a.thumbnail:hover{border-color:#3097d1}.alert{padding:15px;margin-bottom:22px;border:1px solid transparent;border-radius:4px}.alert h4{margin-top:0;color:inherit}.alert .alert-link{font-weight:700}.alert>p,.alert>ul{margin-bottom:0}.alert>p+p{margin-top:5px}.alert-dismissable,.alert-dismissible{padding-right:35px}.alert-dismissable .close,.alert-dismissible .close{position:relative;top:-2px;right:-21px;color:inherit}.alert-success{background-color:#dff0d8;border-color:#d6e9c6;color:#3c763d}.alert-success hr{border-top-color:#c9e2b3}.alert-success .alert-link{color:#2b542c}.alert-info{background-color:#d9edf7;border-color:#bce8f1;color:#31708f}.alert-info hr{border-top-color:#a6e1ec}.alert-info .alert-link{color:#245269}.alert-warning{background-color:#fcf8e3;border-color:#faebcc;color:#8a6d3b}.alert-warning hr{border-top-color:#f7e1b5}.alert-warning .alert-link{color:#66512c}.alert-danger{background-color:#f2dede;border-color:#ebccd1;color:#a94442}.alert-danger hr{border-top-color:#e4b9c0}.alert-danger .alert-link{color:#843534}@-webkit-keyframes progress-bar-stripes{0%{background-position:40px 0}to{background-position:0 0}}@keyframes progress-bar-stripes{0%{background-position:40px 0}to{background-position:0 0}}.progress{overflow:hidden;height:22px;margin-bottom:22px;background-color:#f5f5f5;border-radius:4px;box-shadow:inset 0 1px 2px rgba(0,0,0,.1)}.progress-bar{float:left;width:0;height:100%;font-size:12px;line-height:22px;color:#fff;text-align:center;background-color:#3097d1;box-shadow:inset 0 -1px 0 rgba(0,0,0,.15);-webkit-transition:width .6s ease;transition:width .6s ease}.progress-bar-striped,.progress-striped .progress-bar{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent);background-size:40px 40px}.progress-bar.active,.progress.active .progress-bar{-webkit-animation:progress-bar-stripes 2s linear infinite;animation:progress-bar-stripes 2s linear infinite}.progress-bar-success{background-color:#2ab27b}.progress-striped .progress-bar-success{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent)}.progress-bar-info{background-color:#8eb4cb}.progress-striped .progress-bar-info{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent)}.progress-bar-warning{background-color:#cbb956}.progress-striped .progress-bar-warning{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent)}.progress-bar-danger{background-color:#bf5329}.progress-striped .progress-bar-danger{background-image:-webkit-linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent);background-image:linear-gradient(45deg,hsla(0,0%,100%,.15) 25%,transparent 0,transparent 50%,hsla(0,0%,100%,.15) 0,hsla(0,0%,100%,.15) 75%,transparent 0,transparent)}.media{margin-top:15px}.media:first-child{margin-top:0}.media,.media-body{zoom:1;overflow:hidden}.media-body{width:10000px}.media-object{display:block}.media-object.img-thumbnail{max-width:none}.media-right,.media>.pull-right{padding-left:10px}.media-left,.media>.pull-left{padding-right:10px}.media-body,.media-left,.media-right{display:table-cell;vertical-align:top}.media-middle{vertical-align:middle}.media-bottom{vertical-align:bottom}.media-heading{margin-top:0;margin-bottom:5px}.media-list{padding-left:0;list-style:none}.list-group{margin-bottom:20px;padding-left:0}.list-group-item{position:relative;display:block;padding:10px 15px;margin-bottom:-1px;background-color:#fff;border:1px solid #d3e0e9}.list-group-item:first-child{border-top-right-radius:4px;border-top-left-radius:4px}.list-group-item:last-child{margin-bottom:0;border-bottom-right-radius:4px;border-bottom-left-radius:4px}a.list-group-item,button.list-group-item{color:#555}a.list-group-item .list-group-item-heading,button.list-group-item .list-group-item-heading{color:#333}a.list-group-item:focus,a.list-group-item:hover,button.list-group-item:focus,button.list-group-item:hover{text-decoration:none;color:#555;background-color:#f5f5f5}button.list-group-item{width:100%;text-align:left}.list-group-item.disabled,.list-group-item.disabled:focus,.list-group-item.disabled:hover{background-color:#eee;color:#777;cursor:not-allowed}.list-group-item.disabled .list-group-item-heading,.list-group-item.disabled:focus .list-group-item-heading,.list-group-item.disabled:hover .list-group-item-heading{color:inherit}.list-group-item.disabled .list-group-item-text,.list-group-item.disabled:focus .list-group-item-text,.list-group-item.disabled:hover .list-group-item-text{color:#777}.list-group-item.active,.list-group-item.active:focus,.list-group-item.active:hover{z-index:2;color:#fff;background-color:#3097d1;border-color:#3097d1}.list-group-item.active .list-group-item-heading,.list-group-item.active .list-group-item-heading>.small,.list-group-item.active .list-group-item-heading>small,.list-group-item.active:focus .list-group-item-heading,.list-group-item.active:focus .list-group-item-heading>.small,.list-group-item.active:focus .list-group-item-heading>small,.list-group-item.active:hover .list-group-item-heading,.list-group-item.active:hover .list-group-item-heading>.small,.list-group-item.active:hover .list-group-item-heading>small{color:inherit}.list-group-item.active .list-group-item-text,.list-group-item.active:focus .list-group-item-text,.list-group-item.active:hover .list-group-item-text{color:#d7ebf6}.list-group-item-success{color:#3c763d;background-color:#dff0d8}a.list-group-item-success,button.list-group-item-success{color:#3c763d}a.list-group-item-success .list-group-item-heading,button.list-group-item-success .list-group-item-heading{color:inherit}a.list-group-item-success:focus,a.list-group-item-success:hover,button.list-group-item-success:focus,button.list-group-item-success:hover{color:#3c763d;background-color:#d0e9c6}a.list-group-item-success.active,a.list-group-item-success.active:focus,a.list-group-item-success.active:hover,button.list-group-item-success.active,button.list-group-item-success.active:focus,button.list-group-item-success.active:hover{color:#fff;background-color:#3c763d;border-color:#3c763d}.list-group-item-info{color:#31708f;background-color:#d9edf7}a.list-group-item-info,button.list-group-item-info{color:#31708f}a.list-group-item-info .list-group-item-heading,button.list-group-item-info .list-group-item-heading{color:inherit}a.list-group-item-info:focus,a.list-group-item-info:hover,button.list-group-item-info:focus,button.list-group-item-info:hover{color:#31708f;background-color:#c4e3f3}a.list-group-item-info.active,a.list-group-item-info.active:focus,a.list-group-item-info.active:hover,button.list-group-item-info.active,button.list-group-item-info.active:focus,button.list-group-item-info.active:hover{color:#fff;background-color:#31708f;border-color:#31708f}.list-group-item-warning{color:#8a6d3b;background-color:#fcf8e3}a.list-group-item-warning,button.list-group-item-warning{color:#8a6d3b}a.list-group-item-warning .list-group-item-heading,button.list-group-item-warning .list-group-item-heading{color:inherit}a.list-group-item-warning:focus,a.list-group-item-warning:hover,button.list-group-item-warning:focus,button.list-group-item-warning:hover{color:#8a6d3b;background-color:#faf2cc}a.list-group-item-warning.active,a.list-group-item-warning.active:focus,a.list-group-item-warning.active:hover,button.list-group-item-warning.active,button.list-group-item-warning.active:focus,button.list-group-item-warning.active:hover{color:#fff;background-color:#8a6d3b;border-color:#8a6d3b}.list-group-item-danger{color:#a94442;background-color:#f2dede}a.list-group-item-danger,button.list-group-item-danger{color:#a94442}a.list-group-item-danger .list-group-item-heading,button.list-group-item-danger .list-group-item-heading{color:inherit}a.list-group-item-danger:focus,a.list-group-item-danger:hover,button.list-group-item-danger:focus,button.list-group-item-danger:hover{color:#a94442;background-color:#ebcccc}a.list-group-item-danger.active,a.list-group-item-danger.active:focus,a.list-group-item-danger.active:hover,button.list-group-item-danger.active,button.list-group-item-danger.active:focus,button.list-group-item-danger.active:hover{color:#fff;background-color:#a94442;border-color:#a94442}.list-group-item-heading{margin-top:0;margin-bottom:5px}.list-group-item-text{margin-bottom:0;line-height:1.3}.panel{margin-bottom:22px;background-color:#fff;border:1px solid transparent;border-radius:4px;box-shadow:0 1px 1px rgba(0,0,0,.05)}.panel-body{padding:15px}.panel-body:after,.panel-body:before{content:" ";display:table}.panel-body:after{clear:both}.panel-heading{padding:10px 15px;border-bottom:1px solid transparent;border-top-right-radius:3px;border-top-left-radius:3px}.panel-heading>.dropdown .dropdown-toggle,.panel-title{color:inherit}.panel-title{margin-top:0;margin-bottom:0;font-size:16px}.panel-title>.small,.panel-title>.small>a,.panel-title>a,.panel-title>small,.panel-title>small>a{color:inherit}.panel-footer{padding:10px 15px;background-color:#f5f5f5;border-top:1px solid #d3e0e9;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.list-group,.panel>.panel-collapse>.list-group{margin-bottom:0}.panel>.list-group .list-group-item,.panel>.panel-collapse>.list-group .list-group-item{border-width:1px 0;border-radius:0}.panel>.list-group:first-child .list-group-item:first-child,.panel>.panel-collapse>.list-group:first-child .list-group-item:first-child{border-top:0;border-top-right-radius:3px;border-top-left-radius:3px}.panel>.list-group:last-child .list-group-item:last-child,.panel>.panel-collapse>.list-group:last-child .list-group-item:last-child{border-bottom:0;border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.panel-heading+.panel-collapse>.list-group .list-group-item:first-child{border-top-right-radius:0;border-top-left-radius:0}.list-group+.panel-footer,.panel-heading+.list-group .list-group-item:first-child{border-top-width:0}.panel>.panel-collapse>.table,.panel>.table,.panel>.table-responsive>.table{margin-bottom:0}.panel>.panel-collapse>.table caption,.panel>.table-responsive>.table caption,.panel>.table caption{padding-left:15px;padding-right:15px}.panel>.table-responsive:first-child>.table:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child,.panel>.table:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child,.panel>.table:first-child>thead:first-child>tr:first-child{border-top-right-radius:3px;border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:first-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:first-child,.panel>.table:first-child>thead:first-child>tr:first-child td:first-child,.panel>.table:first-child>thead:first-child>tr:first-child th:first-child{border-top-left-radius:3px}.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table-responsive:first-child>.table:first-child>thead:first-child>tr:first-child th:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child td:last-child,.panel>.table:first-child>tbody:first-child>tr:first-child th:last-child,.panel>.table:first-child>thead:first-child>tr:first-child td:last-child,.panel>.table:first-child>thead:first-child>tr:first-child th:last-child{border-top-right-radius:3px}.panel>.table-responsive:last-child>.table:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child,.panel>.table:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child{border-bottom-right-radius:3px;border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:first-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:first-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:first-child{border-bottom-left-radius:3px}.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table-responsive:last-child>.table:last-child>tfoot:last-child>tr:last-child th:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child td:last-child,.panel>.table:last-child>tbody:last-child>tr:last-child th:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child td:last-child,.panel>.table:last-child>tfoot:last-child>tr:last-child th:last-child{border-bottom-right-radius:3px}.panel>.panel-body+.table,.panel>.panel-body+.table-responsive,.panel>.table+.panel-body,.panel>.table-responsive+.panel-body{border-top:1px solid #ddd}.panel>.table>tbody:first-child>tr:first-child td,.panel>.table>tbody:first-child>tr:first-child th{border-top:0}.panel>.table-bordered,.panel>.table-responsive>.table-bordered{border:0}.panel>.table-bordered>tbody>tr>td:first-child,.panel>.table-bordered>tbody>tr>th:first-child,.panel>.table-bordered>tfoot>tr>td:first-child,.panel>.table-bordered>tfoot>tr>th:first-child,.panel>.table-bordered>thead>tr>td:first-child,.panel>.table-bordered>thead>tr>th:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:first-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:first-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:first-child,.panel>.table-responsive>.table-bordered>thead>tr>td:first-child,.panel>.table-responsive>.table-bordered>thead>tr>th:first-child{border-left:0}.panel>.table-bordered>tbody>tr>td:last-child,.panel>.table-bordered>tbody>tr>th:last-child,.panel>.table-bordered>tfoot>tr>td:last-child,.panel>.table-bordered>tfoot>tr>th:last-child,.panel>.table-bordered>thead>tr>td:last-child,.panel>.table-bordered>thead>tr>th:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>td:last-child,.panel>.table-responsive>.table-bordered>tbody>tr>th:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>td:last-child,.panel>.table-responsive>.table-bordered>tfoot>tr>th:last-child,.panel>.table-responsive>.table-bordered>thead>tr>td:last-child,.panel>.table-responsive>.table-bordered>thead>tr>th:last-child{border-right:0}.panel>.table-bordered>tbody>tr:first-child>td,.panel>.table-bordered>tbody>tr:first-child>th,.panel>.table-bordered>tbody>tr:last-child>td,.panel>.table-bordered>tbody>tr:last-child>th,.panel>.table-bordered>tfoot>tr:last-child>td,.panel>.table-bordered>tfoot>tr:last-child>th,.panel>.table-bordered>thead>tr:first-child>td,.panel>.table-bordered>thead>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:first-child>th,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>td,.panel>.table-responsive>.table-bordered>tbody>tr:last-child>th,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>td,.panel>.table-responsive>.table-bordered>tfoot>tr:last-child>th,.panel>.table-responsive>.table-bordered>thead>tr:first-child>td,.panel>.table-responsive>.table-bordered>thead>tr:first-child>th{border-bottom:0}.panel>.table-responsive{border:0;margin-bottom:0}.panel-group{margin-bottom:22px}.panel-group .panel{margin-bottom:0;border-radius:4px}.panel-group .panel+.panel{margin-top:5px}.panel-group .panel-heading{border-bottom:0}.panel-group .panel-heading+.panel-collapse>.list-group,.panel-group .panel-heading+.panel-collapse>.panel-body{border-top:1px solid #d3e0e9}.panel-group .panel-footer{border-top:0}.panel-group .panel-footer+.panel-collapse .panel-body{border-bottom:1px solid #d3e0e9}.panel-default{border-color:#d3e0e9}.panel-default>.panel-heading{color:#333;background-color:#fff;border-color:#d3e0e9}.panel-default>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d3e0e9}.panel-default>.panel-heading .badge{color:#fff;background-color:#333}.panel-default>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d3e0e9}.panel-primary{border-color:#3097d1}.panel-primary>.panel-heading{color:#fff;background-color:#3097d1;border-color:#3097d1}.panel-primary>.panel-heading+.panel-collapse>.panel-body{border-top-color:#3097d1}.panel-primary>.panel-heading .badge{color:#3097d1;background-color:#fff}.panel-primary>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#3097d1}.panel-success{border-color:#d6e9c6}.panel-success>.panel-heading{color:#3c763d;background-color:#dff0d8;border-color:#d6e9c6}.panel-success>.panel-heading+.panel-collapse>.panel-body{border-top-color:#d6e9c6}.panel-success>.panel-heading .badge{color:#dff0d8;background-color:#3c763d}.panel-success>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#d6e9c6}.panel-info{border-color:#bce8f1}.panel-info>.panel-heading{color:#31708f;background-color:#d9edf7;border-color:#bce8f1}.panel-info>.panel-heading+.panel-collapse>.panel-body{border-top-color:#bce8f1}.panel-info>.panel-heading .badge{color:#d9edf7;background-color:#31708f}.panel-info>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#bce8f1}.panel-warning{border-color:#faebcc}.panel-warning>.panel-heading{color:#8a6d3b;background-color:#fcf8e3;border-color:#faebcc}.panel-warning>.panel-heading+.panel-collapse>.panel-body{border-top-color:#faebcc}.panel-warning>.panel-heading .badge{color:#fcf8e3;background-color:#8a6d3b}.panel-warning>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#faebcc}.panel-danger{border-color:#ebccd1}.panel-danger>.panel-heading{color:#a94442;background-color:#f2dede;border-color:#ebccd1}.panel-danger>.panel-heading+.panel-collapse>.panel-body{border-top-color:#ebccd1}.panel-danger>.panel-heading .badge{color:#f2dede;background-color:#a94442}.panel-danger>.panel-footer+.panel-collapse>.panel-body{border-bottom-color:#ebccd1}.embed-responsive{position:relative;display:block;height:0;padding:0;overflow:hidden}.embed-responsive .embed-responsive-item,.embed-responsive embed,.embed-responsive iframe,.embed-responsive object,.embed-responsive video{position:absolute;top:0;left:0;bottom:0;height:100%;width:100%;border:0}.embed-responsive-16by9{padding-bottom:56.25%}.embed-responsive-4by3{padding-bottom:75%}.well{min-height:20px;padding:19px;margin-bottom:20px;background-color:#f5f5f5;border:1px solid #e3e3e3;border-radius:4px;box-shadow:inset 0 1px 1px rgba(0,0,0,.05)}.well blockquote{border-color:#ddd;border-color:rgba(0,0,0,.15)}.well-lg{padding:24px;border-radius:6px}.well-sm{padding:9px;border-radius:3px}.close{float:right;font-size:21px;font-weight:700;line-height:1;color:#000;text-shadow:0 1px 0 #fff;opacity:.2;filter:alpha(opacity=20)}.close:focus,.close:hover{color:#000;text-decoration:none;cursor:pointer;opacity:.5;filter:alpha(opacity=50)}button.close{padding:0;cursor:pointer;background:transparent;border:0;-webkit-appearance:none}.modal,.modal-open{overflow:hidden}.modal{display:none;position:fixed;top:0;right:0;bottom:0;left:0;z-index:1050;-webkit-overflow-scrolling:touch;outline:0}.modal.fade .modal-dialog{-webkit-transform:translateY(-25%);transform:translateY(-25%);-webkit-transition:-webkit-transform .3s ease-out;transition:-webkit-transform .3s ease-out;transition:transform .3s ease-out;transition:transform .3s ease-out,-webkit-transform .3s ease-out}.modal.in .modal-dialog{-webkit-transform:translate(0);transform:translate(0)}.modal-open .modal{overflow-x:hidden;overflow-y:auto}.modal-dialog{position:relative;width:auto;margin:10px}.modal-content{position:relative;background-color:#fff;border:1px solid #999;border:1px solid rgba(0,0,0,.2);border-radius:6px;box-shadow:0 3px 9px rgba(0,0,0,.5);background-clip:padding-box;outline:0}.modal-backdrop{position:fixed;top:0;right:0;bottom:0;left:0;z-index:1040;background-color:#000}.modal-backdrop.fade{opacity:0;filter:alpha(opacity=0)}.modal-backdrop.in{opacity:.5;filter:alpha(opacity=50)}.modal-header{padding:15px;border-bottom:1px solid #e5e5e5}.modal-header:after,.modal-header:before{content:" ";display:table}.modal-header:after{clear:both}.modal-header .close{margin-top:-2px}.modal-title{margin:0;line-height:1.6}.modal-body{position:relative;padding:15px}.modal-footer{padding:15px;text-align:right;border-top:1px solid #e5e5e5}.modal-footer:after,.modal-footer:before{content:" ";display:table}.modal-footer:after{clear:both}.modal-footer .btn+.btn{margin-left:5px;margin-bottom:0}.modal-footer .btn-group .btn+.btn{margin-left:-1px}.modal-footer .btn-block+.btn-block{margin-left:0}.modal-scrollbar-measure{position:absolute;top:-9999px;width:50px;height:50px;overflow:scroll}@media (min-width:768px){.modal-dialog{width:600px;margin:30px auto}.modal-content{box-shadow:0 5px 15px rgba(0,0,0,.5)}.modal-sm{width:300px}}@media (min-width:992px){.modal-lg{width:900px}}.tooltip{position:absolute;z-index:1070;display:block;font-family:Raleway,sans-serif;font-style:normal;font-weight:400;letter-spacing:normal;line-break:auto;line-height:1.6;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;white-space:normal;word-break:normal;word-spacing:normal;word-wrap:normal;font-size:12px;opacity:0;filter:alpha(opacity=0)}.tooltip.in{opacity:.9;filter:alpha(opacity=90)}.tooltip.top{margin-top:-3px;padding:5px 0}.tooltip.right{margin-left:3px;padding:0 5px}.tooltip.bottom{margin-top:3px;padding:5px 0}.tooltip.left{margin-left:-3px;padding:0 5px}.tooltip-inner{max-width:200px;padding:3px 8px;color:#fff;text-align:center;background-color:#000;border-radius:4px}.tooltip-arrow{position:absolute;width:0;height:0;border-color:transparent;border-style:solid}.tooltip.top .tooltip-arrow{bottom:0;left:50%;margin-left:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-left .tooltip-arrow{right:5px}.tooltip.top-left .tooltip-arrow,.tooltip.top-right .tooltip-arrow{bottom:0;margin-bottom:-5px;border-width:5px 5px 0;border-top-color:#000}.tooltip.top-right .tooltip-arrow{left:5px}.tooltip.right .tooltip-arrow{top:50%;left:0;margin-top:-5px;border-width:5px 5px 5px 0;border-right-color:#000}.tooltip.left .tooltip-arrow{top:50%;right:0;margin-top:-5px;border-width:5px 0 5px 5px;border-left-color:#000}.tooltip.bottom .tooltip-arrow{top:0;left:50%;margin-left:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-left .tooltip-arrow{top:0;right:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.tooltip.bottom-right .tooltip-arrow{top:0;left:5px;margin-top:-5px;border-width:0 5px 5px;border-bottom-color:#000}.popover{position:absolute;top:0;left:0;z-index:1060;display:none;max-width:276px;padding:1px;font-family:Raleway,sans-serif;font-style:normal;font-weight:400;letter-spacing:normal;line-break:auto;line-height:1.6;text-align:left;text-align:start;text-decoration:none;text-shadow:none;text-transform:none;white-space:normal;word-break:normal;word-spacing:normal;word-wrap:normal;font-size:14px;background-color:#fff;background-clip:padding-box;border:1px solid #ccc;border:1px solid rgba(0,0,0,.2);border-radius:6px;box-shadow:0 5px 10px rgba(0,0,0,.2)}.popover.top{margin-top:-10px}.popover.right{margin-left:10px}.popover.bottom{margin-top:10px}.popover.left{margin-left:-10px}.popover-title{margin:0;padding:8px 14px;font-size:14px;background-color:#f7f7f7;border-bottom:1px solid #ebebeb;border-radius:5px 5px 0 0}.popover-content{padding:9px 14px}.popover>.arrow,.popover>.arrow:after{position:absolute;display:block;width:0;height:0;border-color:transparent;border-style:solid}.popover>.arrow{border-width:11px}.popover>.arrow:after{border-width:10px;content:""}.popover.top>.arrow{left:50%;margin-left:-11px;border-bottom-width:0;border-top-color:#999;border-top-color:rgba(0,0,0,.25);bottom:-11px}.popover.top>.arrow:after{content:" ";bottom:1px;margin-left:-10px;border-bottom-width:0;border-top-color:#fff}.popover.right>.arrow{top:50%;left:-11px;margin-top:-11px;border-left-width:0;border-right-color:#999;border-right-color:rgba(0,0,0,.25)}.popover.right>.arrow:after{content:" ";left:1px;bottom:-10px;border-left-width:0;border-right-color:#fff}.popover.bottom>.arrow{left:50%;margin-left:-11px;border-top-width:0;border-bottom-color:#999;border-bottom-color:rgba(0,0,0,.25);top:-11px}.popover.bottom>.arrow:after{content:" ";top:1px;margin-left:-10px;border-top-width:0;border-bottom-color:#fff}.popover.left>.arrow{top:50%;right:-11px;margin-top:-11px;border-right-width:0;border-left-color:#999;border-left-color:rgba(0,0,0,.25)}.popover.left>.arrow:after{content:" ";right:1px;border-right-width:0;border-left-color:#fff;bottom:-10px}.carousel,.carousel-inner{position:relative}.carousel-inner{overflow:hidden;width:100%}.carousel-inner>.item{display:none;position:relative;-webkit-transition:left .6s ease-in-out;transition:left .6s ease-in-out}.carousel-inner>.item>a>img,.carousel-inner>.item>img{display:block;max-width:100%;height:auto;line-height:1}@media (-webkit-transform-3d),(transform-3d){.carousel-inner>.item{-webkit-transition:-webkit-transform .6s ease-in-out;transition:-webkit-transform .6s ease-in-out;transition:transform .6s ease-in-out;transition:transform .6s ease-in-out,-webkit-transform .6s ease-in-out;-webkit-backface-visibility:hidden;backface-visibility:hidden;-webkit-perspective:1000px;perspective:1000px}.carousel-inner>.item.active.right,.carousel-inner>.item.next{-webkit-transform:translate3d(100%,0,0);transform:translate3d(100%,0,0);left:0}.carousel-inner>.item.active.left,.carousel-inner>.item.prev{-webkit-transform:translate3d(-100%,0,0);transform:translate3d(-100%,0,0);left:0}.carousel-inner>.item.active,.carousel-inner>.item.next.left,.carousel-inner>.item.prev.right{-webkit-transform:translateZ(0);transform:translateZ(0);left:0}}.carousel-inner>.active,.carousel-inner>.next,.carousel-inner>.prev{display:block}.carousel-inner>.active{left:0}.carousel-inner>.next,.carousel-inner>.prev{position:absolute;top:0;width:100%}.carousel-inner>.next{left:100%}.carousel-inner>.prev{left:-100%}.carousel-inner>.next.left,.carousel-inner>.prev.right{left:0}.carousel-inner>.active.left{left:-100%}.carousel-inner>.active.right{left:100%}.carousel-control{position:absolute;top:0;left:0;bottom:0;width:15%;opacity:.5;filter:alpha(opacity=50);font-size:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6);background-color:transparent}.carousel-control.left{background-image:-webkit-linear-gradient(left,rgba(0,0,0,.5),rgba(0,0,0,.0001));background-image:linear-gradient(90deg,rgba(0,0,0,.5) 0,rgba(0,0,0,.0001));background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#80000000",endColorstr="#00000000",GradientType=1)}.carousel-control.right{left:auto;right:0;background-image:-webkit-linear-gradient(left,rgba(0,0,0,.0001),rgba(0,0,0,.5));background-image:linear-gradient(90deg,rgba(0,0,0,.0001) 0,rgba(0,0,0,.5));background-repeat:repeat-x;filter:progid:DXImageTransform.Microsoft.gradient(startColorstr="#00000000",endColorstr="#80000000",GradientType=1)}.carousel-control:focus,.carousel-control:hover{outline:0;color:#fff;text-decoration:none;opacity:.9;filter:alpha(opacity=90)}.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{position:absolute;top:50%;margin-top:-10px;z-index:5;display:inline-block}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{left:50%;margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{right:50%;margin-right:-10px}.carousel-control .icon-next,.carousel-control .icon-prev{width:20px;height:20px;line-height:1;font-family:serif}.carousel-control .icon-prev:before{content:"\2039"}.carousel-control .icon-next:before{content:"\203A"}.carousel-indicators{position:absolute;bottom:10px;left:50%;z-index:15;width:60%;margin-left:-30%;padding-left:0;list-style:none;text-align:center}.carousel-indicators li{display:inline-block;width:10px;height:10px;margin:1px;text-indent:-999px;border:1px solid #fff;border-radius:10px;cursor:pointer;background-color:#000\9;background-color:transparent}.carousel-indicators .active{margin:0;width:12px;height:12px;background-color:#fff}.carousel-caption{position:absolute;left:15%;right:15%;bottom:20px;z-index:10;padding-top:20px;padding-bottom:20px;color:#fff;text-align:center;text-shadow:0 1px 2px rgba(0,0,0,.6)}.carousel-caption .btn{text-shadow:none}@media screen and (min-width:768px){.carousel-control .glyphicon-chevron-left,.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next,.carousel-control .icon-prev{width:30px;height:30px;margin-top:-10px;font-size:30px}.carousel-control .glyphicon-chevron-left,.carousel-control .icon-prev{margin-left:-10px}.carousel-control .glyphicon-chevron-right,.carousel-control .icon-next{margin-right:-10px}.carousel-caption{left:20%;right:20%;padding-bottom:30px}.carousel-indicators{bottom:20px}}.clearfix:after,.clearfix:before{content:" ";display:table}.clearfix:after{clear:both}.center-block{display:block;margin-left:auto;margin-right:auto}.pull-right{float:right!important}.pull-left{float:left!important}.hide{display:none!important}.show{display:block!important}.invisible{visibility:hidden}.text-hide{font:0/0 a;color:transparent;text-shadow:none;background-color:transparent;border:0}.hidden{display:none!important}.affix{position:fixed}@-ms-viewport{width:device-width}.visible-lg,.visible-lg-block,.visible-lg-inline,.visible-lg-inline-block,.visible-md,.visible-md-block,.visible-md-inline,.visible-md-inline-block,.visible-sm,.visible-sm-block,.visible-sm-inline,.visible-sm-inline-block,.visible-xs,.visible-xs-block,.visible-xs-inline,.visible-xs-inline-block{display:none!important}@media (max-width:767px){.visible-xs{display:block!important}table.visible-xs{display:table!important}tr.visible-xs{display:table-row!important}td.visible-xs,th.visible-xs{display:table-cell!important}}@media (max-width:767px){.visible-xs-block{display:block!important}}@media (max-width:767px){.visible-xs-inline{display:inline!important}}@media (max-width:767px){.visible-xs-inline-block{display:inline-block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm{display:block!important}table.visible-sm{display:table!important}tr.visible-sm{display:table-row!important}td.visible-sm,th.visible-sm{display:table-cell!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-block{display:block!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline{display:inline!important}}@media (min-width:768px) and (max-width:991px){.visible-sm-inline-block{display:inline-block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md{display:block!important}table.visible-md{display:table!important}tr.visible-md{display:table-row!important}td.visible-md,th.visible-md{display:table-cell!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-block{display:block!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline{display:inline!important}}@media (min-width:992px) and (max-width:1199px){.visible-md-inline-block{display:inline-block!important}}@media (min-width:1200px){.visible-lg{display:block!important}table.visible-lg{display:table!important}tr.visible-lg{display:table-row!important}td.visible-lg,th.visible-lg{display:table-cell!important}}@media (min-width:1200px){.visible-lg-block{display:block!important}}@media (min-width:1200px){.visible-lg-inline{display:inline!important}}@media (min-width:1200px){.visible-lg-inline-block{display:inline-block!important}}@media (max-width:767px){.hidden-xs{display:none!important}}@media (min-width:768px) and (max-width:991px){.hidden-sm{display:none!important}}@media (min-width:992px) and (max-width:1199px){.hidden-md{display:none!important}}@media (min-width:1200px){.hidden-lg{display:none!important}}.visible-print{display:none!important}@media print{.visible-print{display:block!important}table.visible-print{display:table!important}tr.visible-print{display:table-row!important}td.visible-print,th.visible-print{display:table-cell!important}}.visible-print-block{display:none!important}@media print{.visible-print-block{display:block!important}}.visible-print-inline{display:none!important}@media print{.visible-print-inline{display:inline!important}}.visible-print-inline-block{display:none!important}@media print{.visible-print-inline-block{display:inline-block!important}}@media print{.hidden-print{display:none!important}}
laravel_laravel
2017-01-28
1078776e953d35bd67af0971fe78efa037d8fb83
app/Http/Middleware/TrimStrings.php
18
<?php namespace App\Http\Middleware; use Illuminate\Foundation\Http\Middleware\TrimStrings as BaseTrimmer; class TrimStrings extends BaseTrimmer { /** * The names of the attributes that should not be trimmed. * * @var array */ protected $except = [ 'password', 'password_confirmation', ]; }
laravel_laravel
2017-01-28
1078776e953d35bd67af0971fe78efa037d8fb83
webpack.mix.js
15
const { mix } = require('laravel-mix'); /* |-------------------------------------------------------------------------- | Mix Asset Management |-------------------------------------------------------------------------- | | Mix provides a clean, fluent API for defining some Webpack build steps | for your Laravel application. By default, we are compiling the Sass | file for the application as well as bundling up all the JS files. | */ mix.js('resources/assets/js/app.js', 'public/js') .sass('resources/assets/sass/app.scss', 'public/css');
laravel_laravel
2017-01-28
1078776e953d35bd67af0971fe78efa037d8fb83